main.rs (7974B)
1 use arboard::Clipboard; 2 use core::str; 3 use dotenvy::dotenv; 4 use serde::Deserialize; 5 use std::env; 6 use std::process::Command; 7 8 fn get_git_diff() -> Result<String, Box<dyn std::error::Error>> { 9 let diff = Command::new("git").arg("diff").arg("--cached").output()?; 10 11 if !diff.status.success() { 12 println!("error get_git_diff {}", diff.status); 13 return Ok(String::new()); 14 } 15 16 let diff_text_string = String::from_utf8(diff.stdout)?; 17 Ok(diff_text_string) 18 } 19 20 fn main() -> Result<(), Box<dyn std::error::Error>> { 21 let _ = dotenv().ok(); 22 let diff: String = match get_git_diff() { 23 Ok(message) => message, 24 Err(e) => { 25 println!("error get_git_diff {}", e); 26 return Ok(()); 27 } 28 }; 29 if diff.is_empty() { 30 println!("Nothing to commit"); 31 return Ok(()); 32 } 33 34 let args: Vec<String> = env::args().collect(); 35 let mut api_key_arg: Option<String> = None; 36 let mut i = 1; 37 while i < args.len() { 38 let a = &args[i]; 39 if a == "--help" || a == "-h" { 40 println!("Usage:"); 41 println!(" Provide Gemini API key via one of:"); 42 println!(" - As first positional argument: <program> <API_KEY>"); 43 println!(" - Using --api-key=<KEY>"); 44 println!(" - Using -k <KEY>"); 45 println!(" Or set GEMINI_API_KEY in environment (or in a .env file)."); 46 return Ok(()); 47 } else if let Some(rest) = a.strip_prefix("--api-key=") { 48 api_key_arg = Some(rest.to_string()); 49 break; 50 } else if a == "-k" { 51 if i + 1 < args.len() { 52 api_key_arg = Some(args[i + 1].clone()); 53 } 54 break; 55 } else if !a.starts_with('-') { 56 api_key_arg = Some(a.clone()); 57 break; 58 } 59 i += 1; 60 } 61 62 let api_key: String = if let Some(key) = api_key_arg { 63 key 64 } else { 65 match env::var("GEMINI_API_KEY") { 66 Ok(api_key) => api_key, 67 Err(_) => { 68 println!( 69 "No API key provided. Provide it via --api-key, -k, positional arg, or set GEMINI_API_KEY in environment (.env is optional)." 70 ); 71 return Ok(()); 72 } 73 } 74 }; 75 76 let prompto = create_prompt(&diff); 77 let message = generate_commit_message(&prompto, api_key)?; 78 79 println!("{}", message); 80 81 match copy_to_clip(&message) { 82 Ok(_) => {} 83 Err(e) => eprintln!("fail to copy to clip {:?}", e), 84 } 85 Ok(()) 86 } 87 88 fn copy_to_clip(message: &str) -> Result<(), Box<dyn std::error::Error>> { 89 let mut clipboard = Clipboard::new()?; 90 clipboard.set_text(message)?; 91 Ok(()) 92 } 93 94 const COMMIT_MESSAGE_GUIDELINE: &str = r#" 95 Please generate a concise yet appropriate commit message based on the provided Git diff, following Conventional Commits. 96 The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. 97 98 1. Commits MUST be prefixed with a type, which consists of a noun, feat, fix, etc., followed by the OPTIONAL scope, OPTIONAL !, and REQUIRED terminal colon and space. 99 2. The type feat MUST be used when a commit adds a new feature to your application or library. 100 3. The type fix MUST be used when a commit represents a bug fix for your application. 101 4. A scope MAY be provided after a type. A scope MUST consist of a noun describing a section of the codebase surrounded by parenthesis, e.g., fix(parser): 102 5. A description MUST immediately follow the colon and space after the type/scope prefix. The description is a short summary of the code changes, e.g., fix: array parsing issue when multiple spaces were contained in string. 103 6. A longer commit body MAY be provided after the short description, providing additional contextual information about the code changes. The body MUST begin one blank line after the description. 104 7. A commit body is free-form and MAY consist of any number of newline separated paragraphs. 105 8. One or more footers MAY be provided one blank line after the body. Each footer MUST consist of a word token, followed by either a :<space> or <space># separator, followed by a string value (this is inspired by the git trailer convention). 106 9. A footer’s token MUST use - in place of whitespace characters, e.g., Acked-by (this helps differentiate the footer section from a multi-paragraph body). An exception is made for BREAKING CHANGE, which MAY also be used as a token. 107 10. A footer’s value MAY contain spaces and newlines, and parsing MUST terminate when the next valid footer token/separator pair is observed. 108 11. Breaking changes MUST be indicated in the type/scope prefix of a commit, or as an entry in the footer. 109 12. If included as a footer, a breaking change MUST consist of the uppercase text BREAKING CHANGE, followed by a colon, space, and description, e.g., BREAKING CHANGE: environment variables now take precedence over config files. 110 13. If included in the type/scope prefix, breaking changes MUST be indicated by a ! immediately before the :. If ! is used, BREAKING CHANGE: MAY be omitted from the footer section, and the commit description SHALL be used to describe the breaking change. 111 14. Types other than feat and fix MAY be used in your commit messages, e.g., docs: update ref docs. 112 15. The units of information that make up Conventional Commits MUST NOT be treated as case sensitive by implementors, with the exception of BREAKING CHANGE which MUST be uppercase. 113 16. BREAKING-CHANGE MUST be synonymous with BREAKING CHANGE, when used as a token in a footer. 114 17. Do not include ``` in the generated commit message. 115 "#; 116 117 fn create_prompt(diff: &str) -> String { 118 format!( 119 "{}\n\n---\n\n## Git Diff\n\n```diff\n{}\n```", 120 COMMIT_MESSAGE_GUIDELINE, diff 121 ) 122 } 123 124 #[derive(Deserialize, Debug)] 125 struct Part { 126 text: String, 127 } 128 129 #[derive(Deserialize, Debug)] 130 struct Content { 131 parts: Vec<Part>, 132 } 133 134 #[derive(Deserialize, Debug)] 135 struct Candidate { 136 content: Option<Content>, 137 finish_reason: Option<String>, 138 } 139 140 #[derive(Deserialize, Debug)] 141 struct GeminiResponse { 142 candidates: Vec<Candidate>, 143 prompt_feedback: Option<serde_json::Value>, 144 } 145 146 fn generate_commit_message( 147 prompt: &str, 148 api_key: String, 149 ) -> Result<String, Box<dyn std::error::Error>> { 150 let url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-lite-latest:generateContent"; 151 152 let payload = serde_json::json!({ 153 "contents": [ 154 { 155 "parts": [ 156 {"text": prompt} 157 ] 158 } 159 ], 160 }); 161 162 let body = ureq::post(url) 163 .header("X-Goog-Api-Key", &api_key) 164 .send_json(payload)? 165 .body_mut() 166 .read_json::<GeminiResponse>()?; 167 168 let commit_message = body 169 .candidates 170 .first() 171 .and_then(|c| c.content.as_ref()) 172 .and_then(|content| content.parts.first()) 173 .map(|part| part.text.trim().to_string()); 174 175 match commit_message { 176 Some(text) => Ok(text), 177 None => { 178 let reason = body 179 .candidates 180 .first() 181 .and_then(|c| c.finish_reason.as_ref()) 182 .unwrap_or(&"不明 (candidatesが空か構造不正)".to_string()) 183 .clone(); 184 185 let feedback_info = body 186 .prompt_feedback 187 .map(|f| format!("Prompt Feedback: {:?}", f)) 188 .unwrap_or_else(|| "No Prompt Feedback".to_string()); 189 190 Err(format!( 191 "Gemini APIは有効なテキストを返しませんでした。\n\ 192 原因: finish_reason='{}'\n\ 193 詳細: {}", 194 reason, feedback_info 195 ) 196 .into()) 197 } 198 } 199 }