1use reqwest::{Client, Error};
2use serde::{Deserialize, Serialize};
3use std::env;
4use std::process::Command;
5
6#[derive(Serialize)]
7struct GenerateTextRequest<'a> {
8 model: &'a str,
9 prompt: &'a str,
10 temperature: f32,
11 max_tokens: usize,
12 n: usize,
13}
14
15#[derive(Deserialize, Debug)]
16pub struct Choice {
17 pub text: String,
18}
19
20#[derive(Deserialize, Debug)]
21pub struct GenerateTextResponse {
22 pub choices: Vec<Choice>,
23}
24
25pub async fn get_commit_messages<'a>(
26 client: &Client,
27 api_key: &str,
28 model: &'a str,
29 prompt: &'a str,
30 temperature: f32,
31 max_tokens: usize,
32 n: usize,
33) -> Result<GenerateTextResponse, Error> {
34 let request_body = GenerateTextRequest {
35 model,
36 prompt,
37 temperature,
38 max_tokens,
39 n,
40 };
41
42 client
43 .post("https://api.openai.com/v1/completions")
44 .header("Authorization", format!("Bearer {}", api_key))
45 .json(&request_body)
46 .send()
47 .await?
48 .json()
49 .await
50}
51
52pub fn spawn_cmd(cmd: &str, args: &[String]) -> String {
53 let output = Command::new(cmd).args(args).output().expect("Failed to execute process");
54
55 String::from_utf8(output.stdout).expect("")
56}
57
58#[test]
59fn test_spawn_cmd() {
60 let output = spawn_cmd("echo", &["test".to_string()]);
61 assert_eq!(output.trim(), String::from("test"));
62}
63
64pub fn check_diff_get_error(diff: &str) -> String {
65 if diff.is_empty() {
66 let is_nocolor = env::var("NO_COLOR").unwrap_or_else(|_| String::from("unset")) != *"unset";
67 let flags: Vec<String> = if is_nocolor {
68 vec!["status".into()]
69 } else {
70 vec!["-c".into(), "color.status=always".into(), "status".into()]
71 };
72
73 spawn_cmd("git", &flags)
74 } else {
75 String::from("")
76 }
77}
78
79#[test]
80fn test_check_diff_get_error() {
81 assert!(check_diff_get_error("").len() > 0);
82 assert!(check_diff_get_error(".").len() == 0);
83}
84
85pub fn get_api_key() -> String {
86 env::var("GPT_API_KEY").unwrap_or_else(|_| String::from(""))
87}
88
89#[cfg(test)]
90mod lib {
91 extern crate temp_env;
92 use super::*;
93
94 #[test]
95 fn test_get_api_key_with_env_var() {
96 temp_env::with_var_unset("GPT_API_KEY", || assert!(get_api_key().is_empty()));
97 }
98
99 #[test]
100 fn test_get_api_key_without_env_var() {
101 temp_env::with_var("GPT_API_KEY", Some("somekey"), || assert!(!get_api_key().is_empty()));
102 }
103}