Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hotfix/json error #5

Merged
merged 3 commits into from
Mar 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 40 additions & 22 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@
* File Created: 2025-03-01 17:17:30
*
* Modified By: mingcheng ([email protected])
* Last Modified: 2025-03-05 10:12:30
* Last Modified: 2025-03-16 23:11:04
*/

use aigitcommit::cli::Cli;
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,
};
Expand All @@ -34,17 +35,17 @@ async fn main() -> std::result::Result<(), Box<dyn Error>> {
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)?;
Expand All @@ -68,11 +69,11 @@ async fn main() -> std::result::Result<(), Box<dyn Error>> {
// 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
Expand Down Expand Up @@ -107,7 +108,24 @@ async fn main() -> std::result::Result<(), Box<dyn Error>> {
];

// 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)?;
Expand All @@ -124,36 +142,36 @@ async fn main() -> std::result::Result<(), Box<dyn Error>> {

// 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)?;
}
}
}
}

// 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(())
Expand Down
11 changes: 7 additions & 4 deletions src/openai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
* Modified By: mingcheng ([email protected])
* 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,
Expand Down Expand Up @@ -96,13 +96,16 @@ impl OpenAI {
&self,
model_name: &str,
message: Vec<ChatCompletionRequestMessage>,
) -> Result<String, Box<dyn Error>> {
) -> Result<String, OpenAIError> {
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| {
Expand All @@ -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
);
}
Expand Down
11 changes: 1 addition & 10 deletions templates/system.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
```
4 changes: 2 additions & 2 deletions templates/user.txt
Original file line number Diff line number Diff line change
@@ -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}}
Expand Down