git_commit_ai.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import subprocess
  2. import os
  3. import google.generativeai as genai
  4. import re
  5. import argparse # Add argparse import
  6. def get_staged_diff(amend=False):
  7. """
  8. Retrieves the diff of staged files using git.
  9. Returns:
  10. str: The diff of the staged files, or None on error.
  11. """
  12. try:
  13. # Use subprocess.run for better control and error handling
  14. if amend:
  15. process = subprocess.run(
  16. [
  17. "git",
  18. "diff",
  19. "HEAD~1",
  20. "--staged",
  21. ], # Corrected: --staged is the correct option
  22. capture_output=True,
  23. text=True, # Ensure output is returned as text
  24. check=True, # Raise an exception for non-zero exit codes
  25. )
  26. else:
  27. process = subprocess.run(
  28. [
  29. "git",
  30. "diff",
  31. "--staged",
  32. ], # Corrected: --staged is the correct option
  33. capture_output=True,
  34. text=True, # Ensure output is returned as text
  35. check=True, # Raise an exception for non-zero exit codes
  36. )
  37. return process.stdout
  38. except subprocess.CalledProcessError as e:
  39. print(f"Error getting staged diff: {e}")
  40. print(f" stderr: {e.stderr}") # Print stderr for more details
  41. return None
  42. except FileNotFoundError:
  43. print(
  44. "Error: git command not found. Please ensure Git is installed and in your PATH."
  45. )
  46. return None
  47. except Exception as e:
  48. print(f"An unexpected error occurred: {e}")
  49. return None
  50. def get_project_files():
  51. """Gets a list of all files tracked in the latest commit (HEAD)."""
  52. try:
  53. process = subprocess.run(
  54. # Changed command to list files in the last commit
  55. ["git", "ls-tree", "-r", "--name-only", "HEAD"],
  56. capture_output=True,
  57. text=True,
  58. check=True,
  59. cwd=os.getcwd(), # Ensure it runs in the correct directory
  60. )
  61. return process.stdout.splitlines()
  62. except subprocess.CalledProcessError as e:
  63. print(f"Error getting project file list: {e}")
  64. print(f" stderr: {e.stderr}")
  65. return [] # Return empty list on error
  66. except FileNotFoundError:
  67. print("Error: git command not found. Is Git installed and in your PATH?")
  68. return []
  69. except Exception as e:
  70. print(f"An unexpected error occurred while listing files: {e}")
  71. return []
  72. def get_file_content(filepath):
  73. """Reads the content of a file relative to the script's CWD."""
  74. # Consider adding checks to prevent reading files outside the repo
  75. try:
  76. # Assuming the script runs from the repo root
  77. with open(filepath, "r", encoding="utf-8") as f:
  78. return f.read()
  79. except FileNotFoundError:
  80. print(f"Warning: File not found: {filepath}")
  81. return None
  82. except IsADirectoryError:
  83. print(f"Warning: Path is a directory, not a file: {filepath}")
  84. return None
  85. except Exception as e:
  86. print(f"Warning: Error reading file {filepath}: {e}")
  87. return None
  88. def generate_commit_message(diff, gemini_api_key):
  89. """
  90. Generates a commit message using the Gemini API, given the diff.
  91. Args:
  92. diff (str): The diff of the staged files.
  93. gemini_api_key (str): Your Gemini API key.
  94. Returns:
  95. str: The generated commit message, or None on error.
  96. """
  97. if not diff:
  98. print("Error: No diff provided to generate commit message.")
  99. return None
  100. genai.configure(api_key=gemini_api_key)
  101. # Use the intended model name
  102. model = genai.GenerativeModel("gemini-2.0-flash")
  103. # Define prompt as a regular string, not f-string, placeholders will be filled by .format()
  104. prompt = """
  105. You are an expert assistant that generates Git commit messages following conventional commit standards.
  106. Analyze the following diff of staged files and generate ONLY the commit message (subject and body) adhering to standard Git conventions.
  107. 1. **Subject Line:** Write a concise, imperative subject line summarizing the change (max 50 characters). Start with a capital letter. Do not end with a period. Use standard commit types like 'feat:', 'fix:', 'refactor:', 'docs:', 'test:', 'chore:', etc.
  108. 2. **Blank Line:** Leave a single blank line between the subject and the body.
  109. 3. **Body:** Write a detailed but precise body explaining the 'what' and 'why' of the changes. Wrap lines at 72 characters. Focus on the motivation for the change and contrast its implementation with the previous behavior. If the change is trivial, the body can be omitted.
  110. **Project Files:**
  111. Here is a list of files in the project:
  112. ```
  113. {project_files_list}
  114. ```
  115. **Contextual Understanding:**
  116. * The diff shows changes in the context of the project files listed above.
  117. * If understanding the relationship between the changed files and other parts of the project is necessary to write an accurate commit message, you may request the content of specific files from the list above.
  118. * To request file content, respond *only* with the exact phrase: `Request content for file: <path/to/file>` where `<path/to/file>` is the relative path from the repository root. Do not add any other text to your response if you are requesting a file.
  119. Diff:
  120. ```diff
  121. {diff}
  122. ```
  123. Generate ONLY the commit message text, without any introductory phrases like "Here is the commit message:", unless you need to request file content.
  124. """
  125. try:
  126. # Get project files to include in the prompt
  127. project_files = get_project_files()
  128. project_files_list = (
  129. "\n".join(project_files)
  130. if project_files
  131. else "(Could not list project files)"
  132. )
  133. # Format the prompt with the diff and file list
  134. formatted_prompt = prompt.format(
  135. diff=diff, project_files_list=project_files_list
  136. )
  137. # Use a conversation history for potential back-and-forth
  138. conversation = [formatted_prompt]
  139. max_requests = 5 # Limit the number of file requests
  140. requests_made = 0
  141. while requests_made < max_requests:
  142. response = model.generate_content("\n".join(conversation))
  143. message = response.text.strip()
  144. # Check if the AI is requesting a file
  145. request_match = re.match(r"^Request content for file: (.*)$", message)
  146. if request_match:
  147. filepath = request_match.group(1).strip()
  148. print(f"AI requests content for: {filepath}")
  149. user_input = input(f"Allow access to '{filepath}'? (y/n): ").lower()
  150. if user_input == "y":
  151. file_content = get_file_content(filepath)
  152. if file_content:
  153. # Provide content to AI
  154. conversation.append(
  155. f"Response for file '{filepath}':\n```\n{file_content}\n```\nNow, generate the commit message based on the diff and this context."
  156. )
  157. else:
  158. # Inform AI file couldn't be read
  159. conversation.append(
  160. f"File '{filepath}' could not be read or was not found. Continue generating the commit message based on the original diff."
  161. )
  162. else:
  163. # Inform AI permission denied
  164. conversation.append(
  165. f"User denied access to file '{filepath}'. Continue generating the commit message based on the original diff."
  166. )
  167. requests_made += 1
  168. else:
  169. # AI did not request a file, assume it's the commit message
  170. break # Exit the loop
  171. else:
  172. # Max requests reached
  173. print(
  174. "Warning: Maximum number of file requests reached. Generating commit message without further context."
  175. )
  176. # Make one last attempt to generate the message without the last request fulfilled
  177. response = model.generate_content(
  178. "\n".join(conversation[:-1])
  179. + "\nGenerate the commit message now based on the available information."
  180. ) # Use conversation up to the last request
  181. message = response.text.strip()
  182. # Extract the final message, remove potential markdown code blocks, and strip whitespace
  183. # Ensure message is not None before processing
  184. if message:
  185. message = re.sub(
  186. r"^\s*```[a-zA-Z]*\s*\n?", "", message, flags=re.MULTILINE
  187. ) # Remove leading code block start
  188. message = re.sub(
  189. r"\n?```\s*$", "", message, flags=re.MULTILINE
  190. ) # Remove trailing code block end
  191. message = message.strip() # Strip leading/trailing whitespace
  192. else:
  193. # Handle case where response.text might be None or empty after failed requests
  194. print(
  195. "Error: Failed to get a valid response from the AI after handling requests."
  196. )
  197. return None
  198. # Basic validation: Check if the message seems plausible (not empty, etc.)
  199. if not message or len(message) < 5: # Arbitrary short length check
  200. print(
  201. f"Warning: Generated commit message seems too short or empty: '{message}'"
  202. )
  203. # Optionally, you could add retry logic here or return None
  204. return message
  205. except Exception as e:
  206. # Provide more context in the error message
  207. print(f"Error generating commit message with Gemini: {e}")
  208. # Consider logging response details if available, e.g., response.prompt_feedback
  209. if hasattr(response, "prompt_feedback"):
  210. print(f"Prompt Feedback: {response.prompt_feedback}")
  211. return None
  212. def create_commit(message, amend=False): # Add amend parameter
  213. """
  214. Creates a git commit with the given message, optionally amending the previous commit.
  215. Args:
  216. message (str): The commit message.
  217. Returns:
  218. bool: True if the commit was successful, False otherwise.
  219. """
  220. if not message:
  221. print("Error: No commit message provided.")
  222. return False
  223. try:
  224. # Build the command list
  225. command = ["git", "commit"]
  226. if amend:
  227. command.append("--amend")
  228. command.extend(["-m", message])
  229. process = subprocess.run(
  230. command, # Use the dynamically built command
  231. check=True, # Important: Raise exception on non-zero exit
  232. capture_output=True, # capture the output
  233. text=True,
  234. )
  235. print(process.stdout) # print the output
  236. return True
  237. except subprocess.CalledProcessError as e:
  238. print(f"Error creating git commit: {e}")
  239. print(e.stderr)
  240. return False
  241. except FileNotFoundError:
  242. print("Error: git command not found. Is Git installed and in your PATH?")
  243. return False
  244. except Exception as e:
  245. print(f"An unexpected error occurred: {e}")
  246. return False
  247. def main():
  248. """
  249. Main function to orchestrate the process of:
  250. 1. Parsing arguments (for --amend).
  251. 2. Getting the staged diff.
  252. 3. Generating a commit message using Gemini.
  253. 4. Creating or amending a git commit with the generated message.
  254. """
  255. # --- Argument Parsing ---
  256. parser = argparse.ArgumentParser(
  257. description="Generate Git commit messages using AI."
  258. )
  259. parser.add_argument(
  260. "-a",
  261. "--amend",
  262. action="store_true",
  263. help="Amend the previous commit instead of creating a new one.",
  264. )
  265. args = parser.parse_args()
  266. # --- ---
  267. gemini_api_key = os.environ.get("GEMINI_API_KEY")
  268. if not gemini_api_key:
  269. print(
  270. "Error: GEMINI_API_KEY environment variable not set.\n"
  271. " Please obtain an API key from Google Cloud and set the environment variable.\n"
  272. " For example: export GEMINI_API_KEY='YOUR_API_KEY'"
  273. )
  274. return
  275. diff = get_staged_diff(amend=args.amend)
  276. if diff is None:
  277. print("Aborting commit due to error getting diff.")
  278. return # Exit the script
  279. if not diff.strip(): # check if the diff is empty
  280. print("Aborting: No changes staged to commit.")
  281. return
  282. message = generate_commit_message(diff, gemini_api_key)
  283. if message is None:
  284. print("Aborting commit due to error generating message.")
  285. return # Exit if message generation failed
  286. print(f"Generated commit message:\n{message}") # Print the message for review
  287. # --- Confirmation ---
  288. action = "amend the last commit" if args.amend else "create a new commit"
  289. user_input = input(f"Do you want to {action} with this message? (y/n): ").lower()
  290. if user_input == "y":
  291. # Pass the amend flag to create_commit
  292. if create_commit(message, amend=args.amend):
  293. print(f"Commit {'amended' if args.amend else 'created'} successfully.")
  294. else:
  295. print(f"Commit {'amendment' if args.amend else 'creation'} failed.")
  296. else:
  297. print(f"Commit {'amendment' if args.amend else 'creation'} aborted by user.")
  298. if __name__ == "__main__":
  299. main()