diff --git a/src/main.rs b/src/main.rs index d2a5c5c..1dc2f52 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,7 +9,7 @@ * File Created: 2025-03-01 17:17:30 * * Modified By: mingcheng (mingcheng@apache.org) - * Last Modified: 2025-03-05 10:12:30 + * Last Modified: 2025-03-16 23:11:04 */ use aigitcommit::cli::Cli; @@ -17,6 +17,7 @@ use aigitcommit::git::Git; use aigitcommit::openai; use aigitcommit::openai::OpenAI; use arboard::Clipboard; +use async_openai::error::OpenAIError; use async_openai::types::{ ChatCompletionRequestSystemMessageArgs, ChatCompletionRequestUserMessageArgs, }; @@ -34,17 +35,17 @@ async fn main() -> std::result::Result<(), Box> { let cli = Cli::parse(); // Initialize logging - tracing_subscriber::fmt() - .with_max_level(if cli.verbose { - trace!("Verbose mode enabled, set the log level to TRACE. It will makes a little bit noise."); - Level::TRACE - } else { - debug!("Verbose mode disabled, set the default log level to WARN"); - Level::WARN - }) - .without_time() - .with_target(false) - .init(); + if cli.verbose { + tracing_subscriber::fmt() + .with_max_level(Level::TRACE) + .without_time() + .with_target(false) + .init(); + + trace!( + "Verbose mode enabled, set the log level to TRACE. It will makes a little bit noise." + ); + } // Check if the specified path is a valid directory let repo_dir = fs::canonicalize(&cli.repo_path)?; @@ -68,11 +69,11 @@ async fn main() -> std::result::Result<(), Box> { // Get the last 5 commit logs // if the repository has less than 5 commits, it will return all logs let logs = repository.get_logs(5)?; - debug!("Got logs size is {}", logs.len()); + debug!("got logs size is {}", logs.len()); // If git commit log is empty, return error if logs.is_empty() { - return Err("No commit logs found".into()); + return Err("no commit logs found".into()); } // Instantiate OpenAI client, ready to send requests to the OpenAI API @@ -107,7 +108,24 @@ async fn main() -> std::result::Result<(), Box> { ]; // Send the request to OpenAI API and get the response - let result = client.chat(&model_name.to_string(), messages).await?; + let result = match client.chat(&model_name.to_string(), messages).await { + Ok(s) => s, + Err(e) => { + let message = match e { + OpenAIError::Reqwest(_) | OpenAIError::StreamError(_) => { + "network request error".to_string() + } + OpenAIError::JSONDeserialize(_err) => "json deserialization error".to_string(), + OpenAIError::InvalidArgument(_) => "invalid argument".to_string(), + OpenAIError::FileSaveError(_) | OpenAIError::FileReadError(_) => { + "io error".to_string() + } + OpenAIError::ApiError(e) => format!("api error {:?}", e), + }; + + return Err(message.into()); + } + }; trace!("write to stdout, and finish the process"); writeln!(std::io::stdout(), "{}", result)?; @@ -124,20 +142,20 @@ async fn main() -> std::result::Result<(), Box> { // directly commit the changes to the repository if the --commit option is enabled if cli.commit { - trace!("Commit option is enabled, will commit the changes to the repository"); + trace!("commit option is enabled, will commit the changes to the repository"); let mut confirm = Confirm::new(); confirm - .with_prompt("Do you want to commit the changes with the generated commit message?") + .with_prompt("do you want to commit the changes with the generated commit message?") .default(false); // Prompt the user for confirmation if --yes option is not enabled if cli.yes || confirm.interact()? { match repository.commit(&result) { Ok(_) => { - writeln!(std::io::stdout(), "Commit successful!")?; + writeln!(std::io::stdout(), "commit successful!")?; } Err(e) => { - writeln!(std::io::stderr(), "Commit failed: {}", e)?; + writeln!(std::io::stderr(), "commit failed: {}", e)?; } } } @@ -145,15 +163,15 @@ async fn main() -> std::result::Result<(), Box> { // If the --save option is enabled, save the commit message to a file if !cli.save.is_empty() { - trace!("Save option is enabled, will save the commit message to a file"); + trace!("save option is enabled, will save the commit message to a file"); let save_path = &cli.save; - debug!("The save file path is {:?}", &save_path); + debug!("the save file path is {:?}", &save_path); let mut file = File::create(save_path)?; file.write_all(result.as_bytes())?; file.flush()?; - writeln!(std::io::stdout(), "Commit message saved to {}", &save_path)?; + writeln!(std::io::stdout(), "commit message saved to {}", &save_path)?; } Ok(()) diff --git a/src/openai.rs b/src/openai.rs index 6040188..3767774 100644 --- a/src/openai.rs +++ b/src/openai.rs @@ -11,9 +11,9 @@ * Modified By: mingcheng (mingcheng@apache.org) * Last Modified: 2025-03-05 10:46:26 */ - use askama::Template; use async_openai::config::OPENAI_API_BASE; +use async_openai::error::OpenAIError; use async_openai::{ Client, config::OpenAIConfig, @@ -96,13 +96,16 @@ impl OpenAI { &self, model_name: &str, message: Vec, - ) -> Result> { + ) -> Result { let request = CreateChatCompletionRequestArgs::default() .model(model_name) .messages(message) .build()?; - let response = self.client.chat().create(request).await?; + let response = match self.client.chat().create(request).await { + Ok(s) => s, + Err(e) => return Err(e), + }; let mut result = vec![]; response.choices.iter().for_each(|choice| { @@ -111,7 +114,7 @@ impl OpenAI { if let Option::Some(usage) = response.usage { debug!( - "Usage: completion_tokens: {}, prompt_tokens: {}, total_tokens: {}", + "usage: completion_tokens: {}, prompt_tokens: {}, total_tokens: {}", usage.completion_tokens, usage.prompt_tokens, usage.total_tokens ); } diff --git a/templates/system.txt b/templates/system.txt index 9c583a1..1921e23 100644 --- a/templates/system.txt +++ b/templates/system.txt @@ -17,7 +17,7 @@ Please generate a git commit message with the specified requirements. - Steer clear of excessive information. - Eliminate formal or superfluous language. -3. An emoji can be used appropriately at the end of the statement. +3. An emoji can be used appropriately at the end of the statement for the first line. 4. Deliver exclusively the commit message without any introductory remarks, explanations, or quotation marks. @@ -27,16 +27,7 @@ Please generate a git commit message with the specified requirements. Here are a few examples that will be demonstrated below. -``` feat: add user auth system - Add JWT tokens for API auth - Handle token refresh for long sessions -``` - -``` -fix: resolve memory leak in worker pool - -- Clean up idle connections -- Add timeout for stale workers -``` diff --git a/templates/user.txt b/templates/user.txt index fa3b9d5..fc70aa7 100644 --- a/templates/user.txt +++ b/templates/user.txt @@ -1,10 +1,10 @@ -The latest commit history from the repository is shown here. +The latest commit history from the repository is shown here, quote by using the "```" charsets. ``` {{logs}} ``` -Additionally, a variety of content is provided below. +Additionally, a variety of content is provided below, quote by using the "```" charsets. ``` {{diffs}}