smartui/commands/
explain_code.rs1use crate::error::Result;
2use crate::gemini::GeminiClientTrait;
3use crate::tts::TTSManager;
4use async_trait::async_trait;
5use std::path::PathBuf;
6use std::fs;
7
8#[async_trait]
9pub trait GenerateContent {
10 async fn generate_content(&self, prompt: &str) -> Result<String>;
11}
12
13pub struct ExplainCodeCommand<T: GeminiClientTrait> {
14 client: T,
15}
16
17impl<T: GeminiClientTrait> ExplainCodeCommand<T> {
18 pub fn new(client: T) -> Self {
19 Self { client }
20 }
21}
22
23#[async_trait]
24impl<T: GeminiClientTrait + Send + Sync> GenerateContent for ExplainCodeCommand<T> {
25 async fn generate_content(&self, prompt: &str) -> Result<String> {
26 let explanation_prompt = format!(
27 "Explain the following code in detail:\n\n{}",
28 prompt
29 );
30
31 self.client.generate_content(explanation_prompt).await
32 }
33}
34
35pub async fn execute<T: GeminiClientTrait + Send + Sync>(
36 client: T,
37 file: PathBuf,
38 language: Option<String>,
39 tts_manager: Option<&TTSManager>,
40) -> Result<()> {
41 let code = fs::read_to_string(&file)?;
42 let explain_command = ExplainCodeCommand::new(client);
43
44 let prompt = if let Some(lang) = language {
45 format!("Explain this {} code:\n\n{}", lang, code)
46 } else {
47 format!("Explain this code:\n\n{}", code)
48 };
49
50 let explanation = explain_command.generate_content(&prompt).await?;
51 println!("{}", explanation);
52
53 if let Some(tts) = tts_manager {
54 tts.speak(&explanation).await?;
55 }
56
57 Ok(())
58}