git_commit_ai.py 12 KB

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