git_rebase_ai.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. import subprocess
  2. import google.generativeai as genai
  3. import os
  4. import argparse
  5. import sys
  6. import datetime
  7. import re
  8. import logging
  9. import tempfile
  10. import json
  11. # --- Configuration ---
  12. # Configure logging
  13. logging.basicConfig(level=logging.WARN, format="%(levelname)s: %(message)s")
  14. # Attempt to get API key from environment variable
  15. API_KEY = os.getenv("GEMINI_API_KEY")
  16. if not API_KEY:
  17. logging.error("GEMINI_API_KEY environment variable not set.")
  18. logging.error(
  19. "Please obtain an API key from Google AI Studio (https://aistudio.google.com/app/apikey)"
  20. )
  21. logging.error("and set it as an environment variable:")
  22. logging.error(" export GEMINI_API_KEY='YOUR_API_KEY' (Linux/macOS)")
  23. logging.error(" set GEMINI_API_KEY=YOUR_API_KEY (Windows CMD)")
  24. logging.error(" $env:GEMINI_API_KEY='YOUR_API_KEY' (Windows PowerShell)")
  25. sys.exit(1)
  26. # Configure the Gemini AI Client
  27. try:
  28. genai.configure(api_key=API_KEY)
  29. # Use a model suitable for complex reasoning like code analysis.
  30. # Adjust model name if needed (e.g., 'gemini-1.5-flash-latest').
  31. MODEL_NAME = os.getenv("GEMINI_MODEL")
  32. if not MODEL_NAME:
  33. logging.error("GEMINI_MODEL environment variable not set.")
  34. logging.error(
  35. "Please set the desired Gemini model name (e.g., 'gemini-1.5-flash-latest')."
  36. )
  37. logging.error(" export GEMINI_MODEL='gemini-1.5-flash-latest' (Linux/macOS)")
  38. logging.error(" set GEMINI_MODEL=gemini-1.5-flash-latest (Windows CMD)")
  39. logging.error(
  40. " $env:GEMINI_MODEL='gemini-1.5-flash-latest' (Windows PowerShell)"
  41. )
  42. sys.exit(1)
  43. model = genai.GenerativeModel(MODEL_NAME)
  44. logging.info(f"Using Gemini model: {MODEL_NAME}")
  45. except Exception as e:
  46. logging.error(f"Error configuring Gemini AI: {e}")
  47. sys.exit(1)
  48. # --- Git Helper Functions ---
  49. def run_git_command(command_list, check=True, capture_output=True, env=None):
  50. """
  51. Runs a Git command as a list of arguments and returns its stdout.
  52. Handles errors and returns None on failure if check=True.
  53. Allows passing environment variables.
  54. """
  55. full_command = []
  56. try:
  57. full_command = ["git"] + command_list
  58. logging.info(f"Running command: {' '.join(full_command)}")
  59. cmd_env = os.environ.copy()
  60. if env:
  61. cmd_env.update(env)
  62. result = subprocess.run(
  63. full_command,
  64. check=check,
  65. capture_output=capture_output,
  66. text=True,
  67. encoding="utf-8",
  68. errors="replace",
  69. env=cmd_env,
  70. )
  71. if result.stdout:
  72. logging.info(f"Command output:\n{result.stdout[:200]}...")
  73. return result.stdout.strip() if capture_output else ""
  74. return ""
  75. except subprocess.CalledProcessError as e:
  76. logging.error(f"Error executing Git command: {' '.join(full_command)}")
  77. stderr_safe = (
  78. e.stderr.strip().encode("utf-8", "replace").decode("utf-8")
  79. if e.stderr
  80. else ""
  81. )
  82. stdout_safe = (
  83. e.stdout.strip().encode("utf-8", "replace").decode("utf-8")
  84. if e.stdout
  85. else ""
  86. )
  87. logging.error(f"Exit Code: {e.returncode}")
  88. if stderr_safe:
  89. logging.error(f"Stderr: {stderr_safe}")
  90. if stdout_safe:
  91. logging.error(f"Stdout: {stdout_safe}")
  92. return None
  93. except FileNotFoundError:
  94. logging.error(
  95. "Error: 'git' command not found. Is Git installed and in your PATH?"
  96. )
  97. sys.exit(1)
  98. except Exception as e:
  99. logging.error(f"Running command: {' '.join(full_command)}")
  100. logging.error(f"An unexpected error occurred running git: {e}")
  101. return None
  102. def check_git_repository():
  103. """Checks if the current directory is the root of a Git repository."""
  104. output = run_git_command(["rev-parse", "--is-inside-work-tree"])
  105. return output == "true"
  106. def get_current_branch():
  107. """Gets the current active Git branch name."""
  108. return run_git_command(["rev-parse", "--abbrev-ref", "HEAD"])
  109. def create_backup_branch(branch_name):
  110. """Creates a timestamped backup branch from the given branch name."""
  111. timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  112. backup_branch_name = f"{branch_name}-backup-{timestamp}"
  113. logging.info(
  114. f"Attempting to create backup branch: {backup_branch_name} from {branch_name}"
  115. )
  116. output = run_git_command(["branch", backup_branch_name, branch_name])
  117. if output is not None:
  118. logging.info(f"Successfully created backup branch: {backup_branch_name}")
  119. return backup_branch_name
  120. else:
  121. logging.error("Failed to create backup branch.")
  122. return None
  123. def get_commit_range(upstream_ref, current_branch):
  124. """
  125. Determines the commit range (merge_base..current_branch).
  126. Returns the range string and the merge base hash.
  127. """
  128. logging.info(
  129. f"Finding merge base between '{upstream_ref}' and '{current_branch}'..."
  130. )
  131. merge_base = run_git_command(["merge-base", upstream_ref, current_branch])
  132. if not merge_base:
  133. logging.error(
  134. f"Could not find merge base between '{upstream_ref}' and '{current_branch}'."
  135. )
  136. logging.error(
  137. f"Ensure '{upstream_ref}' is a valid reference (branch, commit, tag)"
  138. )
  139. logging.error("and that it has been fetched (e.g., 'git fetch origin').")
  140. return None, None # Indicate failure
  141. logging.info(f"Found merge base: {merge_base}")
  142. commit_range = f"{merge_base}..{current_branch}"
  143. return commit_range, merge_base
  144. def get_commits_in_range(commit_range):
  145. """Gets a list of commit hashes and subjects in the specified range (oldest first)."""
  146. log_output = run_git_command(
  147. ["log", "--pretty=format:%h %s", "--reverse", commit_range]
  148. )
  149. if log_output is not None:
  150. commits = log_output.splitlines()
  151. logging.info(f"Found {len(commits)} commits in range {commit_range}.")
  152. return commits
  153. return [] # Return empty list on failure or no commits
  154. def get_commits_data_in_range(commit_range):
  155. # Use --format=%H %s to get full hash for later matching if needed
  156. log_output = run_git_command(
  157. ["log", "--pretty=format:%h %H %s", "--reverse", commit_range]
  158. )
  159. if log_output is not None:
  160. commits = log_output.splitlines()
  161. # Store as list of dicts for easier access
  162. commit_data = []
  163. for line in commits:
  164. parts = line.split(" ", 2)
  165. if len(parts) == 3:
  166. commit_data.append(
  167. {"short_hash": parts[0], "full_hash": parts[1], "subject": parts[2]}
  168. )
  169. logging.info(f"Found {len(commit_data)} commits in range {commit_range}.")
  170. return commit_data
  171. return []
  172. def get_changed_files_in_range(commit_range):
  173. """
  174. Gets a list of files changed in the specified range and generates
  175. a simple directory structure string representation.
  176. """
  177. diff_output = run_git_command(["diff", "--name-only", commit_range])
  178. if diff_output is not None:
  179. files = diff_output.splitlines()
  180. logging.info(f"Found {len(files)} changed files in range {commit_range}.")
  181. # Basic tree structure representation
  182. tree = {}
  183. for file_path in files:
  184. parts = file_path.replace("\\", "/").split("/")
  185. node = tree
  186. for i, part in enumerate(parts):
  187. if not part:
  188. continue
  189. if i == len(parts) - 1:
  190. node[part] = "file"
  191. else:
  192. if part not in node:
  193. node[part] = {}
  194. if isinstance(node[part], dict):
  195. node = node[part]
  196. else:
  197. logging.warning(
  198. f"Path conflict building file tree for: {file_path}"
  199. )
  200. break
  201. def format_tree(d, indent=0):
  202. lines = []
  203. for key, value in sorted(d.items()):
  204. prefix = " " * indent
  205. if isinstance(value, dict):
  206. lines.append(f"{prefix}📁 {key}/")
  207. lines.extend(format_tree(value, indent + 1))
  208. else:
  209. lines.append(f"{prefix}📄 {key}")
  210. return lines
  211. tree_str = "\n".join(format_tree(tree))
  212. return tree_str, files
  213. return "", []
  214. def get_diff_in_range(commit_range):
  215. """Gets the combined diffstat and patch for the specified range."""
  216. diff_output = run_git_command(["diff", "--patch-with-stat", commit_range])
  217. if diff_output is not None:
  218. logging.info(
  219. f"Generated diff for range {commit_range} (length: {len(diff_output)} chars)."
  220. )
  221. else:
  222. logging.warning(f"Could not generate diff for range {commit_range}.")
  223. return diff_output if diff_output is not None else ""
  224. def get_file_content_at_commit(commit_hash, file_path):
  225. """Gets the content of a specific file at a specific commit hash."""
  226. logging.info(f"Fetching content of '{file_path}' at commit {commit_hash[:7]}...")
  227. content = run_git_command(["show", f"{commit_hash}:{file_path}"])
  228. if content is None:
  229. logging.warning(
  230. f"Could not retrieve content for {file_path} at {commit_hash[:7]}."
  231. )
  232. return None
  233. return content
  234. # --- AI Interaction ---
  235. def generate_fixup_suggestion_prompt(
  236. commit_range, merge_base, commits, file_structure, diff
  237. ):
  238. """
  239. Creates a prompt asking the AI specifically to identify potential
  240. fixup candidates within the commit range.
  241. Returns suggestions in a parsable format.
  242. """
  243. commit_list_str = (
  244. "\n".join([f"- {c}" for c in commits]) if commits else "No commits in range."
  245. )
  246. prompt = f"""
  247. You are an expert Git assistant. Your task is to analyze the provided Git commit history and identify commits within the range `{commit_range}` that should be combined using `fixup` during an interactive rebase (`git rebase -i {merge_base}`).
  248. **Goal:** Identify commits that are minor corrections or direct continuations of the immediately preceding commit, where the commit message can be discarded.
  249. **Git Commit Message Conventions (for context):**
  250. * Subject: Imperative, < 50 chars, capitalized, no period. Use types like `feat:`, `fix:`, `refactor:`, etc.
  251. * Body: Explain 'what' and 'why', wrap at 72 chars.
  252. **Provided Context:**
  253. 1. **Commit Range:** `{commit_range}`
  254. 2. **Merge Base Hash:** `{merge_base}`
  255. 3. **Commits in Range (Oldest First - Short Hash & Subject):**
  256. ```
  257. {commit_list_str}
  258. ```
  259. 4. **Changed Files Structure in Range:**
  260. ```
  261. {file_structure if file_structure else "No files changed or unable to list."}
  262. ```
  263. 5. **Combined Diff for the Range (`git diff --patch-with-stat {commit_range}`):**
  264. ```diff
  265. {diff if diff else "No differences found or unable to get diff."}
  266. ```
  267. **Instructions:**
  268. 1. Analyze the commits, their messages, the changed files, and the diff.
  269. 2. Identify commits from the list that are strong candidates for being combined into their **immediately preceding commit** using `fixup` (combine changes, discard message). Focus on small fixes, typo corrections, or direct continuations where the commit message isn't valuable.
  270. 3. For each suggestion, output *only* a line in the following format:
  271. `FIXUP: <hash_to_fixup> INTO <preceding_hash>`
  272. Use the short commit hashes provided in the commit list.
  273. 4. Provide *only* lines in the `FIXUP:` format. Do not include explanations, introductory text, or any other formatting. If no fixups are suggested, output nothing.
  274. **Example Output:**
  275. ```text
  276. FIXUP: hash2 INTO hash1
  277. FIXUP: hash5 INTO hash4
  278. ```
  279. 5. **File Content Request:** If you absolutely need the content of specific files *at specific commits* to confidently determine if they should be fixed up, ask for them clearly ONCE. List the files using this exact format at the end of your response:
  280. `REQUEST_FILES: [commit_hash1:path/to/file1.py, commit_hash2:another/path/file2.js]`
  281. Use the short commit hashes provided in the commit list. Do *not* ask for files unless essential for *this specific task* of identifying fixup candidates.
  282. Now, analyze the provided context and generate *only* the `FIXUP:` lines or `REQUEST_FILES:` line.
  283. """
  284. return prompt
  285. def parse_fixup_suggestions(ai_response_text, commits_in_range):
  286. """Parses AI response for FIXUP: lines and validates hashes."""
  287. fixup_pairs = []
  288. commit_hashes = {
  289. c.split()[0] for c in commits_in_range
  290. } # Set of valid short hashes
  291. for line in ai_response_text.splitlines():
  292. line = line.strip()
  293. if line.startswith("FIXUP:"):
  294. match = re.match(r"FIXUP:\s*(\w+)\s+INTO\s+(\w+)", line, re.IGNORECASE)
  295. if match:
  296. fixup_hash = match.group(1)
  297. target_hash = match.group(2)
  298. # Validate that both hashes were in the original commit list
  299. if fixup_hash in commit_hashes and target_hash in commit_hashes:
  300. fixup_pairs.append({"fixup": fixup_hash, "target": target_hash})
  301. logging.debug(
  302. f"Parsed fixup suggestion: {fixup_hash} into {target_hash}"
  303. )
  304. else:
  305. logging.warning(
  306. f"Ignoring invalid fixup suggestion (hash not in range): {line}"
  307. )
  308. else:
  309. logging.warning(f"Could not parse FIXUP line: {line}")
  310. return fixup_pairs
  311. # --- request_files_from_user function remains the same ---
  312. def request_files_from_user(requested_files_str, commits_in_range):
  313. """
  314. Parses AI request string "REQUEST_FILES: [hash:path, ...]", verifies hashes,
  315. asks user permission, fetches file contents, and returns formatted context.
  316. """
  317. file_requests = []
  318. try:
  319. content_match = re.search(
  320. r"REQUEST_FILES:\s*\[(.*)\]", requested_files_str, re.IGNORECASE | re.DOTALL
  321. )
  322. if not content_match:
  323. logging.warning("Could not parse file request format from AI response.")
  324. return None, None
  325. items_str = content_match.group(1).strip()
  326. if not items_str:
  327. logging.info("AI requested files but the list was empty.")
  328. return None, None
  329. items = [item.strip() for item in items_str.split(",") if item.strip()]
  330. commit_hash_map = {c.split()[0]: c.split()[0] for c in commits_in_range}
  331. for item in items:
  332. if ":" not in item:
  333. logging.warning(
  334. f"Invalid format in requested file item (missing ':'): {item}"
  335. )
  336. continue
  337. commit_hash, file_path = item.split(":", 1)
  338. commit_hash = commit_hash.strip()
  339. file_path = file_path.strip()
  340. if commit_hash not in commit_hash_map:
  341. logging.warning(
  342. f"AI requested file for unknown/out-of-range commit hash '{commit_hash}'. Skipping."
  343. )
  344. continue
  345. file_requests.append({"hash": commit_hash, "path": file_path})
  346. except Exception as e:
  347. logging.error(f"Error parsing requested files string: {e}")
  348. return None, None
  349. if not file_requests:
  350. logging.info("No valid file requests found after parsing AI response.")
  351. return None, None
  352. print("\n----------------------------------------")
  353. print("❓ AI Request for File Content ❓")
  354. print("----------------------------------------")
  355. print("The AI needs the content of the following files at specific commits")
  356. print("to provide more accurate fixup suggestions:")
  357. files_to_fetch = []
  358. for i, req in enumerate(file_requests):
  359. print(f" {i + 1}. File: '{req['path']}' at commit {req['hash']}")
  360. files_to_fetch.append(req)
  361. if not files_to_fetch:
  362. print("\nNo valid files to fetch based on the request.")
  363. return None, None
  364. print("----------------------------------------")
  365. while True:
  366. try:
  367. answer = (
  368. input("Allow fetching these file contents? (yes/no): ").lower().strip()
  369. )
  370. except EOFError:
  371. logging.warning("Input stream closed. Assuming 'no'.")
  372. answer = "no"
  373. if answer == "yes":
  374. logging.info("User approved fetching file content.")
  375. fetched_content_list = []
  376. for req in files_to_fetch:
  377. content = get_file_content_at_commit(req["hash"], req["path"])
  378. if content is not None:
  379. fetched_content_list.append(
  380. f"--- Content of '{req['path']}' at commit {req['hash']} ---\n"
  381. f"```\n{content}\n```\n"
  382. f"--- End Content for {req['path']} at {req['hash']} ---"
  383. )
  384. else:
  385. fetched_content_list.append(
  386. f"--- Could not fetch content of '{req['path']}' at commit {req['hash']} ---"
  387. )
  388. return "\n\n".join(fetched_content_list), requested_files_str
  389. elif answer == "no":
  390. logging.info("User denied fetching file content.")
  391. return None, requested_files_str
  392. else:
  393. print("Please answer 'yes' or 'no'.")
  394. # --- Automatic Rebase Logic ---
  395. def create_rebase_editor_script(script_path, fixup_plan):
  396. """Creates the python script to be used by GIT_SEQUENCE_EDITOR."""
  397. # Create a set of hashes that need to be fixed up
  398. fixups_to_apply = {pair["fixup"] for pair in fixup_plan}
  399. script_content = f"""#!/usr/bin/env python3
  400. import sys
  401. import logging
  402. import re
  403. import os
  404. # Define log file path relative to the script itself
  405. log_file = __file__ + ".log"
  406. # Setup logging within the editor script to write to the log file
  407. logging.basicConfig(filename=log_file, filemode='w', level=logging.WARN, format="%(asctime)s - %(levelname)s: %(message)s")
  408. todo_file_path = sys.argv[1]
  409. logging.info(f"GIT_SEQUENCE_EDITOR script started for: {{todo_file_path}}")
  410. # Hashes that should be changed to 'fixup'
  411. fixups_to_apply = {fixups_to_apply!r}
  412. logging.info(f"Applying fixups for hashes: {{fixups_to_apply}}")
  413. new_lines = []
  414. try:
  415. with open(todo_file_path, 'r', encoding='utf-8') as f:
  416. lines = f.readlines()
  417. for line in lines:
  418. stripped_line = line.strip()
  419. # Skip comments and blank lines
  420. if not stripped_line or stripped_line.startswith('#'):
  421. new_lines.append(line)
  422. continue
  423. # Use regex for more robust parsing of todo lines (action hash ...)
  424. match = re.match(r"^(\w+)\s+([0-9a-fA-F]+)(.*)", stripped_line)
  425. if match:
  426. action = match.group(1).lower()
  427. commit_hash = match.group(2)
  428. rest_of_line = match.group(3)
  429. # Check if this commit should be fixed up
  430. if commit_hash in fixups_to_apply and action == 'pick':
  431. logging.info(f"Changing 'pick {{commit_hash}}' to 'fixup {{commit_hash}}'")
  432. # Replace 'pick' with 'fixup', preserving the rest of the line
  433. new_line = f'f {{commit_hash}}{{rest_of_line}}\\n'
  434. new_lines.append(new_line)
  435. else:
  436. # Keep the original line
  437. new_lines.append(line)
  438. else:
  439. # Keep lines that don't look like standard todo lines
  440. logging.warning(f"Could not parse todo line: {{stripped_line}}")
  441. new_lines.append(line)
  442. logging.info(f"Writing {{len(new_lines)}} lines back to {{todo_file_path}}")
  443. with open(todo_file_path, 'w', encoding='utf-8') as f:
  444. f.writelines(new_lines)
  445. logging.info("GIT_SEQUENCE_EDITOR script finished successfully.")
  446. sys.exit(0) # Explicitly exit successfully
  447. except Exception as e:
  448. logging.error(f"Error in GIT_SEQUENCE_EDITOR script: {{e}}", exc_info=True)
  449. sys.exit(1) # Exit with error code
  450. """
  451. try:
  452. with open(script_path, "w", encoding="utf-8") as f:
  453. f.write(script_content)
  454. # Make the script executable (important on Linux/macOS)
  455. os.chmod(script_path, 0o755)
  456. logging.info(f"Created GIT_SEQUENCE_EDITOR script: {script_path}")
  457. return True
  458. except Exception as e:
  459. logging.error(f"Failed to create GIT_SEQUENCE_EDITOR script: {e}")
  460. return False
  461. def attempt_auto_fixup(merge_base, fixup_plan):
  462. """Attempts to perform the rebase automatically applying fixups."""
  463. if not fixup_plan:
  464. logging.info("No fixup suggestions provided by AI. Skipping auto-rebase.")
  465. return True # Nothing to do, considered success
  466. # Use a temporary directory to hold the script and its log
  467. temp_dir = tempfile.mkdtemp(prefix="git_rebase_")
  468. editor_script_path = os.path.join(temp_dir, "rebase_editor.py")
  469. logging.debug(f"Temporary directory: {temp_dir}")
  470. logging.debug(f"Temporary editor script path: {editor_script_path}")
  471. try:
  472. if not create_rebase_editor_script(editor_script_path, fixup_plan):
  473. return False # Failed to create script
  474. # Prepare environment for the git command
  475. rebase_env = os.environ.copy()
  476. rebase_env["GIT_SEQUENCE_EDITOR"] = editor_script_path
  477. # Prevent Git from opening a standard editor for messages etc.
  478. # 'true' simply exits successfully, accepting default messages
  479. rebase_env["GIT_EDITOR"] = "true"
  480. print("\nAttempting automatic rebase with suggested fixups...")
  481. logging.info(f"Running: git rebase -i {merge_base}")
  482. # Run rebase non-interactively, check=False to handle failures manually
  483. rebase_result = run_git_command(
  484. ["rebase", "-i", merge_base],
  485. check=False, # Don't raise exception on failure, check exit code
  486. capture_output=True, # Capture output to see potential errors
  487. env=rebase_env,
  488. )
  489. # Check the result (run_git_command returns None on CalledProcessError)
  490. if rebase_result is not None:
  491. # Command finished, exit code was likely 0 (success)
  492. print("✅ Automatic fixup rebase completed successfully.")
  493. logging.info("Automatic fixup rebase seems successful.")
  494. return True
  495. else:
  496. # Command failed (non-zero exit code, run_git_command returned None)
  497. print("\n❌ Automatic fixup rebase failed.")
  498. print(
  499. " This likely means merge conflicts occurred or another rebase error happened."
  500. )
  501. logging.warning("Automatic fixup rebase failed. Aborting...")
  502. # Attempt to abort the failed rebase
  503. print(" Attempting to abort the failed rebase (`git rebase --abort`)...")
  504. # Run abort without capturing output, just check success/failure
  505. abort_result = run_git_command(
  506. ["rebase", "--abort"], check=False, capture_output=False
  507. )
  508. # run_git_command returns None on failure (CalledProcessError)
  509. if abort_result is not None:
  510. print(
  511. " Rebase aborted successfully. Your branch is back to its original state."
  512. )
  513. logging.info("Failed rebase aborted successfully.")
  514. else:
  515. print(" ⚠️ Failed to automatically abort the rebase.")
  516. print(" Please run `git rebase --abort` manually to clean up.")
  517. logging.error("Failed to automatically abort the rebase.")
  518. return False
  519. except Exception as e:
  520. logging.error(
  521. f"An unexpected error occurred during auto-fixup attempt: {e}",
  522. exc_info=True,
  523. )
  524. # Might need manual cleanup here too
  525. print("\n❌ An unexpected error occurred during the automatic fixup attempt.")
  526. print(
  527. " You may need to manually check your Git status and potentially run `git rebase --abort`."
  528. )
  529. return False
  530. finally:
  531. # Determine if rebase failed *before* potential cleanup errors
  532. # Note: rebase_result is defined in the outer scope of the try block
  533. rebase_failed = "rebase_result" in locals() and rebase_result is None
  534. # Check if we need to display the editor script log
  535. editor_log_path = editor_script_path + ".log"
  536. verbose_logging = logging.getLogger().isEnabledFor(logging.DEBUG)
  537. if (rebase_failed or verbose_logging) and os.path.exists(editor_log_path):
  538. try:
  539. with open(editor_log_path, "r", encoding="utf-8") as log_f:
  540. log_content = log_f.read()
  541. if log_content:
  542. print("\n--- Rebase Editor Script Log ---")
  543. print(log_content.strip())
  544. print("--- End Log ---")
  545. else:
  546. # Only log if verbose, otherwise it's just noise
  547. if verbose_logging:
  548. logging.debug(
  549. f"Rebase editor script log file was empty: {editor_log_path}"
  550. )
  551. except Exception as log_e:
  552. logging.warning(
  553. f"Could not read rebase editor script log file {editor_log_path}: {log_e}"
  554. )
  555. # Clean up the temporary directory and its contents
  556. if temp_dir and os.path.exists(temp_dir):
  557. try:
  558. if os.path.exists(editor_log_path):
  559. os.remove(editor_log_path)
  560. if os.path.exists(editor_script_path):
  561. os.remove(editor_script_path)
  562. os.rmdir(temp_dir)
  563. logging.debug(f"Cleaned up temporary directory: {temp_dir}")
  564. except OSError as e:
  565. logging.warning(
  566. f"Could not completely remove temporary directory {temp_dir}: {e}"
  567. )
  568. # --- AI Interaction ---
  569. def generate_reword_suggestion_prompt(commit_range, merge_base, commits_data, diff):
  570. """
  571. Creates a prompt asking the AI to identify commits needing rewording
  572. and to generate the full new commit message for each.
  573. """
  574. # Format commit list for the prompt using only short hash and subject
  575. commit_list_str = (
  576. "\n".join([f"- {c['short_hash']} {c['subject']}" for c in commits_data])
  577. if commits_data
  578. else "No commits in range."
  579. )
  580. prompt = f"""
  581. You are an expert Git assistant specializing in commit message conventions. Your task is to analyze the provided Git commit history within the range `{commit_range}` and identify commits whose messages should be improved using `reword` during an interactive rebase (`git rebase -i {merge_base}`).
  582. **Goal:** For each commit needing improvement, generate a **complete, new commit message** (subject and body) that adheres strictly to standard Git conventions.
  583. **Git Commit Message Conventions to Adhere To:**
  584. 1. **Subject Line:** Concise, imperative summary (max 50 chars). Capitalized. No trailing period. Use types like `feat:`, `fix:`, `refactor:`, `perf:`, `test:`, `build:`, `ci:`, `docs:`, `style:`, `chore:`. Example: `feat: Add user authentication endpoint`
  585. 2. **Blank Line:** Single blank line between subject and body.
  586. 3. **Body:** Explain 'what' and 'why' (motivation, approach, contrast with previous behavior). Wrap lines at 72 chars. Omit body ONLY for truly trivial changes where the subject is self-explanatory. Example:
  587. ```
  588. refactor: Improve database query performance
  589. The previous implementation used multiple sequential queries
  590. to fetch related data, leading to N+1 problems under load.
  591. This change refactors the data access layer to use a single
  592. JOIN query, significantly reducing database roundtrips and
  593. improving response time for the user profile page.
  594. ```
  595. **Provided Context:**
  596. 1. **Commit Range:** `{commit_range}`
  597. 2. **Merge Base Hash:** `{merge_base}`
  598. 3. **Commits in Range (Oldest First - Short Hash & Subject):**
  599. ```
  600. {commit_list_str}
  601. ```
  602. 4. **Combined Diff for the Range (`git diff --patch-with-stat {commit_range}`):**
  603. ```diff
  604. {diff if diff else "No differences found or unable to get diff."}
  605. ```
  606. **Instructions:**
  607. 1. Analyze the commits listed above, focusing on their subjects and likely content based on the diff.
  608. 2. Identify commits whose messages are unclear, too long, lack a type prefix, are poorly formatted, or don't adequately explain the change.
  609. 3. For **each** commit you identify for rewording, output a block EXACTLY in the following format:
  610. ```text
  611. REWORD: <short_hash_to_reword>
  612. NEW_MESSAGE:
  613. <Generated Subject Line Adhering to Conventions>
  614. <Generated Body Line 1 Adhering to Conventions>
  615. <Generated Body Line 2 Adhering to Conventions>
  616. ...
  617. <Generated Body Last Line Adhering to Conventions>
  618. END_MESSAGE
  619. ```
  620. * Replace `<short_hash_to_reword>` with the short hash from the commit list.
  621. * Replace `<Generated Subject Line...>` with the new subject line you generate.
  622. * Replace `<Generated Body Line...>` with the lines of the new body you generate (if a body is needed). Ensure a blank line between subject and body, and wrap body lines at 72 characters. If no body is needed, omit the body lines but keep the blank line after the Subject.
  623. * The `END_MESSAGE` line marks the end of the message for one commit.
  624. 4. Provide *only* blocks in the specified `REWORD:...END_MESSAGE` format. Do not include explanations, introductory text, or any other formatting. If no rewording is suggested, output nothing.
  625. Now, analyze the provided context and generate the reword suggestions with complete new messages.
  626. """
  627. return prompt
  628. def parse_reword_suggestions(ai_response_text, commits_data):
  629. """Parses AI response for REWORD:/NEW_MESSAGE:/END_MESSAGE blocks."""
  630. reword_plan = {} # Use dict: {short_hash: new_message_string}
  631. commit_hashes = {c["short_hash"] for c in commits_data} # Set of valid short hashes
  632. # Regex to find blocks
  633. pattern = re.compile(
  634. r"REWORD:\s*(\w+)\s*NEW_MESSAGE:\s*(.*?)\s*END_MESSAGE",
  635. re.DOTALL | re.IGNORECASE,
  636. )
  637. matches = pattern.findall(ai_response_text)
  638. for match in matches:
  639. reword_hash = match[0].strip()
  640. new_message = match[1].strip() # Includes Subject: and body
  641. if reword_hash in commit_hashes:
  642. reword_plan[reword_hash] = new_message
  643. logging.debug(
  644. f"Parsed reword suggestion for {reword_hash}:\n{new_message[:100]}..."
  645. )
  646. else:
  647. logging.warning(
  648. f"Ignoring invalid reword suggestion (hash {reword_hash} not in range)."
  649. )
  650. return reword_plan
  651. # --- Automatic Rebase Logic ---
  652. def create_rebase_sequence_editor_script(script_path, reword_plan):
  653. """Creates the python script for GIT_SEQUENCE_EDITOR (changes pick to reword)."""
  654. hashes_to_reword = set(reword_plan.keys())
  655. script_content = f"""#!/usr/bin/env python3
  656. import sys
  657. import logging
  658. import re
  659. import os
  660. logging.basicConfig(level=logging.WARN, format="%(levelname)s: %(message)s")
  661. todo_file_path = sys.argv[1]
  662. logging.info(f"GIT_SEQUENCE_EDITOR script started for: {{todo_file_path}}")
  663. hashes_to_reword = {hashes_to_reword!r}
  664. logging.info(f"Applying rewording for hashes: {{hashes_to_reword}}")
  665. new_lines = []
  666. try:
  667. with open(todo_file_path, 'r', encoding='utf-8') as f:
  668. lines = f.readlines()
  669. for line in lines:
  670. stripped_line = line.strip()
  671. if not stripped_line or stripped_line.startswith('#'):
  672. new_lines.append(line)
  673. continue
  674. match = re.match(r"^(\w+)\s+([0-9a-fA-F]+)(.*)", stripped_line)
  675. if match:
  676. action = match.group(1).lower()
  677. commit_hash = match.group(2)
  678. rest_of_line = match.group(3)
  679. if commit_hash in hashes_to_reword and action == 'pick':
  680. logging.info(f"Changing 'pick {{commit_hash}}' to 'reword {{commit_hash}}'")
  681. new_line = f'r {{commit_hash}}{{rest_of_line}}\\n' # Use 'r' for reword
  682. new_lines.append(new_line)
  683. else:
  684. new_lines.append(line)
  685. else:
  686. logging.warning(f"Could not parse todo line: {{stripped_line}}")
  687. new_lines.append(line)
  688. logging.info(f"Writing {{len(new_lines)}} lines back to {{todo_file_path}}")
  689. with open(todo_file_path, 'w', encoding='utf-8') as f:
  690. f.writelines(new_lines)
  691. logging.info("GIT_SEQUENCE_EDITOR script finished successfully.")
  692. sys.exit(0)
  693. except Exception as e:
  694. logging.error(f"Error in GIT_SEQUENCE_EDITOR script: {{e}}", exc_info=True)
  695. sys.exit(1)
  696. """
  697. try:
  698. with open(script_path, "w", encoding="utf-8") as f:
  699. f.write(script_content)
  700. os.chmod(script_path, 0o755)
  701. logging.info(f"Created GIT_SEQUENCE_EDITOR script: {script_path}")
  702. return True
  703. except Exception as e:
  704. logging.error(f"Failed to create GIT_SEQUENCE_EDITOR script: {e}")
  705. return False
  706. def create_rebase_commit_editor_script(script_path):
  707. """Creates the python script for GIT_EDITOR (provides new commit message)."""
  708. # Note: reword_plan_json is a JSON string containing the {hash: new_message} mapping
  709. script_content = f"""#!/usr/bin/env python3
  710. import sys
  711. import logging
  712. import re
  713. import os
  714. import subprocess
  715. import json
  716. logging.basicConfig(level=logging.WARN, format="%(levelname)s: %(message)s")
  717. commit_msg_file_path = sys.argv[1]
  718. logging.info(f"GIT_EDITOR script started for commit message file: {{commit_msg_file_path}}")
  719. # The reword plan (hash -> new_message) is passed via environment variable as JSON
  720. reword_plan_json = os.environ.get('GIT_REWORD_PLAN')
  721. if not reword_plan_json:
  722. logging.error("GIT_REWORD_PLAN environment variable not set.")
  723. sys.exit(1)
  724. try:
  725. reword_plan = json.loads(reword_plan_json)
  726. logging.info(f"Loaded reword plan for {{len(reword_plan)}} commits.")
  727. except json.JSONDecodeError as e:
  728. logging.error(f"Failed to decode GIT_REWORD_PLAN JSON: {{e}}")
  729. sys.exit(1)
  730. # --- How to identify the current commit being reworded? ---
  731. # This is the tricky part. Git doesn't directly tell the editor which commit
  732. # it's editing during a reword.
  733. # Approach 1: Read the *original* message from the file Git provides.
  734. # Extract the original hash (if possible, maybe from a trailer?). Unreliable.
  735. # Approach 2: Rely on the *order*. Requires knowing the rebase todo list order. Fragile.
  736. # Approach 3: Use `git rev-parse HEAD`? Might work if HEAD points to the commit being edited. Needs testing.
  737. # Approach 4: Pass the *current* target hash via another env var set by the main script
  738. # before calling rebase? Seems overly complex.
  739. # --- Let's try Approach 3 (Check HEAD) ---
  740. try:
  741. # Use subprocess to run git command to get the full hash of HEAD
  742. result = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output=True, text=True, check=True, encoding='utf-8')
  743. current_full_hash = result.stdout.strip()
  744. logging.info(f"Current HEAD full hash: {{current_full_hash}}")
  745. # Find the corresponding short hash in our plan (keys are short hashes)
  746. current_short_hash = None
  747. for short_h in reword_plan.keys():
  748. # Use git rev-parse to check if short_h resolves to current_full_hash
  749. # This handles potential ambiguity if multiple commits have the same short hash prefix
  750. try:
  751. # Verify that the short_h from the plan resolves to a commit object
  752. # and get its full hash. Simply pass the short hash to verify.
  753. logging.info(f"Verifying short hash {{short_h}} against HEAD {{current_full_hash}}...")
  754. verify_result = subprocess.run(['git', 'rev-parse', '--verify', short_h], capture_output=True, text=True, check=True, encoding='utf-8')
  755. verified_full_hash = verify_result.stdout.strip()
  756. if verified_full_hash == current_full_hash:
  757. current_short_hash = short_h
  758. logging.info(f"Matched HEAD {{current_full_hash}} to short hash {{current_short_hash}} in plan.")
  759. break
  760. except subprocess.CalledProcessError:
  761. logging.debug(f"Short hash {{short_h}} does not resolve to HEAD.")
  762. continue # Try next short hash in plan
  763. if current_short_hash is None:
  764. sys.exit(0) # Exit successfully to avoid blocking rebase, but log warning
  765. elif current_short_hash and current_short_hash in reword_plan:
  766. new_message = reword_plan[current_short_hash]
  767. logging.info(f"Found new message for commit {{current_short_hash}}.")
  768. # Remove the "Subject: " prefix as Git adds that structure
  769. new_message_content = re.sub(r"^[Ss]ubject:\s*", "", new_message, count=1)
  770. logging.info(f"Writing new message to {{commit_msg_file_path}}: {{new_message_content[:100]}}...")
  771. with open(commit_msg_file_path, 'w', encoding='utf-8') as f:
  772. f.write(new_message_content)
  773. logging.info("GIT_EDITOR script finished successfully for reword.")
  774. sys.exit(0)
  775. else:
  776. logging.warning(f"Could not find a matching commit hash in the reword plan for current HEAD {{current_full_hash}} (Short hash: {{current_short_hash}}).")
  777. # Keep the original message provided by Git? Or fail? Let's keep original for safety.
  778. logging.warning("Keeping the original commit message.")
  779. sys.exit(0) # Exit successfully to avoid blocking rebase, but log warning
  780. except subprocess.CalledProcessError as e:
  781. logging.error(f"Failed to run git rev-parse HEAD: {{e}}")
  782. sys.exit(1) # Fail editor script
  783. except Exception as e:
  784. logging.error(f"Error in GIT_EDITOR script: {{e}}", exc_info=True)
  785. sys.exit(1) # Exit with error code
  786. """
  787. try:
  788. with open(script_path, "w", encoding="utf-8") as f:
  789. f.write(script_content)
  790. os.chmod(script_path, 0o755)
  791. logging.info(f"Created GIT_EDITOR script: {script_path}")
  792. return True
  793. except Exception as e:
  794. logging.error(f"Failed to create GIT_EDITOR script: {e}")
  795. return False
  796. def attempt_auto_reword(merge_base, reword_plan):
  797. """Attempts to perform the rebase automatically applying rewording."""
  798. if not reword_plan:
  799. logging.info("No reword suggestions provided by AI. Skipping auto-rebase.")
  800. return True
  801. temp_dir = tempfile.mkdtemp(prefix="git_reword_")
  802. seq_editor_script_path = os.path.join(temp_dir, "rebase_sequence_editor.py")
  803. commit_editor_script_path = os.path.join(temp_dir, "rebase_commit_editor.py")
  804. logging.debug(f"Temporary directory: {temp_dir}")
  805. try:
  806. # Create the sequence editor script (changes pick -> reword)
  807. if not create_rebase_sequence_editor_script(
  808. seq_editor_script_path, reword_plan
  809. ):
  810. return False
  811. # Create the commit editor script (provides new message)
  812. # Pass the reword plan as a JSON string via environment variable
  813. reword_plan_json = json.dumps(reword_plan)
  814. if not create_rebase_commit_editor_script(commit_editor_script_path):
  815. return False
  816. # Prepare environment for the git command
  817. rebase_env = os.environ.copy()
  818. rebase_env["GIT_SEQUENCE_EDITOR"] = seq_editor_script_path
  819. rebase_env["GIT_EDITOR"] = commit_editor_script_path
  820. # Pass the plan to the commit editor script via env var
  821. rebase_env["GIT_REWORD_PLAN"] = reword_plan_json
  822. logging.debug(f"GIT_REWORD_PLAN: {reword_plan_json}")
  823. print("\nAttempting automatic rebase with suggested rewording...")
  824. logging.info(f"Running: git rebase -i {merge_base}")
  825. rebase_result = run_git_command(
  826. ["rebase", "-i", merge_base],
  827. check=False,
  828. capture_output=False,
  829. env=rebase_env,
  830. )
  831. if rebase_result is not None:
  832. print("✅ Automatic reword rebase completed successfully.")
  833. logging.info("Automatic reword rebase seems successful.")
  834. return True
  835. else:
  836. print("\n❌ Automatic reword rebase failed.")
  837. print(
  838. " This could be due to merge conflicts, script errors, or other rebase issues."
  839. )
  840. logging.warning("Automatic reword rebase failed. Aborting...")
  841. print(" Attempting to abort the failed rebase (`git rebase --abort`)...")
  842. abort_result = run_git_command(
  843. ["rebase", "--abort"], check=False, capture_output=False
  844. )
  845. if abort_result is not None:
  846. print(
  847. " Rebase aborted successfully. Your branch is back to its original state."
  848. )
  849. logging.info("Failed rebase aborted successfully.")
  850. else:
  851. print(" ⚠️ Failed to automatically abort the rebase.")
  852. print(" Please run `git rebase --abort` manually to clean up.")
  853. logging.error("Failed to automatically abort the rebase.")
  854. return False
  855. except Exception as e:
  856. logging.error(
  857. f"An unexpected error occurred during auto-reword attempt: {e}",
  858. exc_info=True,
  859. )
  860. print("\n❌ An unexpected error occurred during the automatic reword attempt.")
  861. print(
  862. " You may need to manually check your Git status and potentially run `git rebase --abort`."
  863. )
  864. return False
  865. finally:
  866. # Clean up the temporary directory
  867. if temp_dir and os.path.exists(temp_dir):
  868. try:
  869. import shutil
  870. shutil.rmtree(temp_dir)
  871. logging.debug(f"Cleaned up temporary directory: {temp_dir}")
  872. except OSError as e:
  873. logging.warning(f"Could not remove temporary directory {temp_dir}: {e}")
  874. # --- Main Execution ---
  875. def rebase(args):
  876. if not check_git_repository():
  877. logging.error("This script must be run from within a Git repository.")
  878. sys.exit(1)
  879. current_branch = get_current_branch()
  880. if not current_branch:
  881. logging.error("Could not determine the current Git branch.")
  882. sys.exit(1)
  883. logging.info(f"Current branch: {current_branch}")
  884. upstream_ref = args.upstream_ref
  885. logging.info(f"Comparing against reference: {upstream_ref}")
  886. # --- Gather Initial Git Context ---
  887. print("\nGathering initial Git context...")
  888. commit_range, merge_base = get_commit_range(upstream_ref, current_branch)
  889. if not commit_range:
  890. sys.exit(1) # Error message already printed by get_commit_range
  891. logging.info(f"Analyzing commit range: {commit_range} (Merge Base: {merge_base})")
  892. commits = get_commits_in_range(commit_range)
  893. if not commits:
  894. print(
  895. f"\n✅ No commits found between '{merge_base}' ({upstream_ref}) and '{current_branch}'. Nothing to rebase."
  896. )
  897. sys.exit(0)
  898. # --- Safety: Create Backup Branch (only if commits exist) ---
  899. backup_branch = create_backup_branch(current_branch)
  900. if not backup_branch:
  901. try:
  902. confirm = input(
  903. "⚠️ Failed to create backup branch. Continue without backup? (yes/no): "
  904. ).lower()
  905. except EOFError:
  906. logging.warning("Input stream closed. Aborting.")
  907. confirm = "no"
  908. if confirm != "yes":
  909. logging.info("Aborting.")
  910. sys.exit(1)
  911. else:
  912. logging.warning("Proceeding without a backup branch. Be careful!")
  913. else:
  914. print("-" * 40)
  915. print(f"✅ Backup branch created: {backup_branch}")
  916. print(" If anything goes wrong, you can restore using:")
  917. print(f" git checkout {current_branch}")
  918. print(f" git reset --hard {backup_branch}")
  919. print("-" * 40)
  920. # --- Gather Remaining Git Context ---
  921. print("\nGathering detailed Git context for AI...")
  922. # We already have commits, commit_range, merge_base from the initial check
  923. file_structure, changed_files_list = get_changed_files_in_range(commit_range)
  924. diff = get_diff_in_range(commit_range)
  925. if not diff and not changed_files_list:
  926. logging.warning(
  927. f"No file changes or diff found between '{merge_base}' and '{current_branch}',"
  928. )
  929. logging.warning("even though commits exist. AI suggestions might be limited.")
  930. # Don't exit automatically, let AI try
  931. # --- Interact with AI ---
  932. print("\nGenerating prompt for AI fixup suggestions...")
  933. initial_prompt = generate_fixup_suggestion_prompt(
  934. commit_range, merge_base, commits, file_structure, diff
  935. )
  936. logging.debug("\n--- Initial AI Prompt Snippet ---")
  937. logging.debug(initial_prompt[:1000] + "...")
  938. logging.debug("--- End Prompt Snippet ---\n")
  939. print(f"Sending request to Gemini AI ({MODEL_NAME})...")
  940. ai_response_text = ""
  941. fixup_suggestions_text = "" # Store the raw suggestions for later display if needed
  942. try:
  943. convo = model.start_chat(history=[])
  944. response = convo.send_message(initial_prompt)
  945. ai_response_text = response.text
  946. # Loop for file requests
  947. while "REQUEST_FILES:" in ai_response_text.upper():
  948. logging.info("AI requested additional file content.")
  949. additional_context, original_request = request_files_from_user(
  950. ai_response_text, commits
  951. )
  952. if additional_context:
  953. logging.info("Sending fetched file content back to AI...")
  954. follow_up_prompt = f"""
  955. Okay, here is the content of the files you requested:
  956. {additional_context}
  957. Please use this new information to refine your **fixup suggestions** based on the original request and context. Provide the final list of `FIXUP: ...` lines now. Remember to *only* suggest fixup actions and output *only* `FIXUP:` lines. Do not ask for more files.
  958. """
  959. logging.debug("\n--- Follow-up AI Prompt Snippet ---")
  960. logging.debug(follow_up_prompt[:500] + "...")
  961. logging.debug("--- End Follow-up Snippet ---\n")
  962. response = convo.send_message(follow_up_prompt)
  963. ai_response_text = response.text
  964. else:
  965. logging.info(
  966. "Proceeding without providing files as requested by AI or user."
  967. )
  968. no_files_prompt = f"""
  969. I cannot provide the content for the files you requested ({original_request}).
  970. Please proceed with generating the **fixup suggestions** based *only* on the initial context (commit list, file structure, diff) I provided earlier. Make your best suggestions without the file content. Provide the final list of `FIXUP: ...` lines now. Remember to *only* suggest fixup actions.
  971. """
  972. logging.debug("\n--- No-Files AI Prompt ---")
  973. logging.debug(no_files_prompt)
  974. logging.debug("--- End No-Files Prompt ---\n")
  975. response = convo.send_message(no_files_prompt)
  976. ai_response_text = response.text
  977. break
  978. # Store the final AI response containing suggestions
  979. fixup_suggestions_text = ai_response_text.strip()
  980. # Parse the suggestions
  981. fixup_plan = parse_fixup_suggestions(fixup_suggestions_text, commits)
  982. if not fixup_plan:
  983. print("\n💡 AI did not suggest any specific fixup operations.")
  984. else:
  985. print("\n💡 --- AI Fixup Suggestions --- 💡")
  986. # Print the parsed plan for clarity
  987. for i, pair in enumerate(fixup_plan):
  988. print(
  989. f" {i + 1}. Fixup commit `{pair['fixup']}` into `{pair['target']}`"
  990. )
  991. print("💡 --- End AI Suggestions --- 💡")
  992. # --- Attempt Automatic Rebase or Show Instructions ---
  993. # --- Logic Change ---
  994. if not args.instruct: # Default behavior: attempt auto-fixup
  995. if fixup_plan:
  996. success = attempt_auto_fixup(merge_base, fixup_plan)
  997. if not success:
  998. # Failure message already printed by attempt_auto_fixup
  999. print("\n" + "=" * 60)
  1000. print("🛠️ MANUAL REBASE REQUIRED 🛠️")
  1001. print("=" * 60)
  1002. print(
  1003. "The automatic fixup rebase failed (likely due to conflicts)."
  1004. )
  1005. print("Please perform the rebase manually:")
  1006. print(f" 1. Run: `git rebase -i {merge_base}`")
  1007. print(
  1008. " 2. In the editor, change 'pick' to 'f' (or 'fixup') for the commits"
  1009. )
  1010. print(
  1011. " suggested by the AI above (and any other changes you want)."
  1012. )
  1013. print(" Original AI suggestions:")
  1014. print(" ```text")
  1015. # Print raw suggestions which might be easier to copy/paste
  1016. print(
  1017. fixup_suggestions_text
  1018. if fixup_suggestions_text
  1019. else " (No specific fixup lines found in AI response)"
  1020. )
  1021. print(" ```")
  1022. print(" 3. Save the editor and resolve any conflicts Git reports.")
  1023. print(
  1024. " Use `git status`, edit files, `git add <files>`, `git rebase --continue`."
  1025. )
  1026. if backup_branch:
  1027. print(f" 4. Remember backup branch: {backup_branch}")
  1028. print("=" * 60)
  1029. sys.exit(1) # Exit with error status after failure
  1030. else:
  1031. # Auto fixup succeeded
  1032. print("\nBranch history has been modified by automatic fixups.")
  1033. if backup_branch:
  1034. print(
  1035. f"Backup branch '{backup_branch}' still exists if needed."
  1036. )
  1037. else:
  1038. print("\nNo automatic rebase attempted as AI suggested no fixups.")
  1039. elif fixup_plan: # --instruct flag was used AND suggestions exist
  1040. print("\n" + "=" * 60)
  1041. print("📝 MANUAL REBASE INSTRUCTIONS (--instruct used) 📝")
  1042. print("=" * 60)
  1043. print("AI suggested the fixups listed above.")
  1044. print("To apply them (or other changes):")
  1045. print(f" 1. Run: `git rebase -i {merge_base}`")
  1046. print(" 2. Edit the 'pick' lines in the editor based on the suggestions")
  1047. print(" (changing 'pick' to 'f' or 'fixup').")
  1048. print(" 3. Save the editor and follow Git's instructions.")
  1049. if backup_branch:
  1050. print(f" 4. Remember backup branch: {backup_branch}")
  1051. print("=" * 60)
  1052. # If --instruct and no fixup_plan, nothing specific needs to be printed here
  1053. except Exception as e:
  1054. logging.error(f"\nAn unexpected error occurred: {e}", exc_info=True)
  1055. # Attempt to print feedback if available
  1056. try:
  1057. if response and hasattr(response, "prompt_feedback"):
  1058. logging.error(f"AI Prompt Feedback: {response.prompt_feedback}")
  1059. if response and hasattr(response, "candidates"):
  1060. for candidate in response.candidates:
  1061. logging.error(
  1062. f"AI Candidate Finish Reason: {candidate.finish_reason}"
  1063. )
  1064. if hasattr(candidate, "safety_ratings"):
  1065. logging.error(f"AI Safety Ratings: {candidate.safety_ratings}")
  1066. except Exception as feedback_e:
  1067. logging.error(
  1068. f"Could not retrieve detailed feedback from AI response: {feedback_e}"
  1069. )
  1070. print("\n❌ An unexpected error occurred during the process.")
  1071. print(" Please check the logs and your Git status.")
  1072. print(" You may need to run `git rebase --abort` manually.")
  1073. def reword(args):
  1074. """Main function to orchestrate Git analysis and AI interaction."""
  1075. if not check_git_repository():
  1076. logging.error("This script must be run from within a Git repository.")
  1077. sys.exit(1)
  1078. current_branch = get_current_branch()
  1079. if not current_branch:
  1080. logging.error("Could not determine the current Git branch.")
  1081. sys.exit(1)
  1082. logging.info(f"Current branch: {current_branch}")
  1083. upstream_ref = args.upstream_ref
  1084. logging.info(f"Comparing against reference: {upstream_ref}")
  1085. # --- Safety: Create Backup Branch ---
  1086. backup_branch = create_backup_branch(current_branch)
  1087. if not backup_branch:
  1088. try:
  1089. confirm = input(
  1090. "⚠️ Failed to create backup branch. Continue without backup? (yes/no): "
  1091. ).lower()
  1092. except EOFError:
  1093. confirm = "no"
  1094. if confirm != "yes":
  1095. logging.info("Aborting.")
  1096. sys.exit(1)
  1097. else:
  1098. logging.warning("Proceeding without a backup branch. Be careful!")
  1099. else:
  1100. print("-" * 40)
  1101. print(f"✅ Backup branch created: {backup_branch}")
  1102. print(
  1103. f" Restore with: git checkout {current_branch} && git reset --hard {backup_branch}"
  1104. )
  1105. print("-" * 40)
  1106. # --- Gather Git Context ---
  1107. print("\nGathering Git context...")
  1108. commit_range, merge_base = get_commit_range(upstream_ref, current_branch)
  1109. if not commit_range:
  1110. sys.exit(1)
  1111. logging.info(f"Analyzing commit range: {commit_range} (Merge Base: {merge_base})")
  1112. commits_data = get_commits_data_in_range(commit_range)
  1113. if not commits_data:
  1114. logging.info(
  1115. f"No commits found between '{merge_base}' and '{current_branch}'. Nothing to do."
  1116. )
  1117. sys.exit(0)
  1118. diff = get_diff_in_range(commit_range) # Diff might help AI judge messages
  1119. # --- Interact with AI ---
  1120. print("\nGenerating prompt for AI reword suggestions...")
  1121. initial_prompt = generate_reword_suggestion_prompt(
  1122. commit_range, merge_base, commits_data, diff
  1123. )
  1124. logging.debug("\n--- Initial AI Prompt Snippet ---")
  1125. logging.debug(initial_prompt[:1000] + "...")
  1126. logging.debug("--- End Prompt Snippet ---\n")
  1127. print(f"Sending request to Gemini AI ({MODEL_NAME})...")
  1128. ai_response_text = ""
  1129. reword_suggestions_text = "" # Store raw AI suggestions
  1130. try:
  1131. # For reword, file content is less likely needed, but keep structure just in case
  1132. convo = model.start_chat(history=[])
  1133. response = convo.send_message(initial_prompt)
  1134. ai_response_text = response.text
  1135. # Store the final AI response containing suggestions
  1136. reword_suggestions_text = ai_response_text.strip()
  1137. # Parse the suggestions
  1138. reword_plan = parse_reword_suggestions(reword_suggestions_text, commits_data)
  1139. if not reword_plan:
  1140. print("\n💡 AI did not suggest any specific reword operations.")
  1141. else:
  1142. print("\n💡 --- AI Reword Suggestions --- 💡")
  1143. for i, (hash_key, msg) in enumerate(reword_plan.items()):
  1144. print(f" {i + 1}. Reword commit `{hash_key}` with new message:")
  1145. # Indent the message for readability
  1146. indented_msg = " " + msg.replace("\n", "\n ")
  1147. print(indented_msg)
  1148. print("-" * 20) # Separator
  1149. print("💡 --- End AI Suggestions --- 💡")
  1150. # --- Attempt Automatic Rebase or Show Instructions ---
  1151. if not args.instruct: # Default behavior: attempt auto-reword
  1152. if reword_plan:
  1153. success = attempt_auto_reword(merge_base, reword_plan)
  1154. if not success:
  1155. # Failure message already printed by attempt_auto_reword
  1156. print("\n" + "=" * 60)
  1157. print("🛠️ MANUAL REBASE REQUIRED 🛠️")
  1158. print("=" * 60)
  1159. print("The automatic reword rebase failed.")
  1160. print("Please perform the rebase manually:")
  1161. print(f" 1. Run: `git rebase -i {merge_base}`")
  1162. print(
  1163. " 2. In the editor, change 'pick' to 'r' (or 'reword') for the commits"
  1164. )
  1165. print(" suggested by the AI above.")
  1166. print(
  1167. " 3. Save the editor. Git will stop at each commit marked for reword."
  1168. )
  1169. print(
  1170. " 4. Manually replace the old commit message with the AI-suggested one:"
  1171. )
  1172. print(" ```text")
  1173. # Print raw suggestions which might be easier to copy/paste
  1174. print(
  1175. reword_suggestions_text
  1176. if reword_suggestions_text
  1177. else " (No specific reword suggestions found in AI response)"
  1178. )
  1179. print(" ```")
  1180. print(
  1181. " 5. Save the message editor and continue the rebase (`git rebase --continue`)."
  1182. )
  1183. if backup_branch:
  1184. print(f" 6. Remember backup branch: {backup_branch}")
  1185. print("=" * 60)
  1186. sys.exit(1) # Exit with error status after failure
  1187. else:
  1188. # Auto reword succeeded
  1189. print("\nBranch history has been modified by automatic rewording.")
  1190. if backup_branch:
  1191. print(
  1192. f"Backup branch '{backup_branch}' still exists if needed."
  1193. )
  1194. else:
  1195. print("\nNo automatic rebase attempted as AI suggested no rewording.")
  1196. elif reword_plan: # --instruct flag was used AND suggestions exist
  1197. print("\n" + "=" * 60)
  1198. print("📝 MANUAL REBASE INSTRUCTIONS (--instruct used) 📝")
  1199. print("=" * 60)
  1200. print("AI suggested the rewording listed above.")
  1201. print("To apply them manually:")
  1202. print(f" 1. Run: `git rebase -i {merge_base}`")
  1203. print(
  1204. " 2. Edit the 'pick' lines in the editor, changing 'pick' to 'r' (or 'reword')"
  1205. )
  1206. print(" for the commits listed above.")
  1207. print(
  1208. " 3. Save the editor. Git will stop at each commit marked for reword."
  1209. )
  1210. print(
  1211. " 4. Manually replace the old commit message with the corresponding AI-suggested message."
  1212. )
  1213. print(
  1214. " 5. Save the message editor and continue the rebase (`git rebase --continue`)."
  1215. )
  1216. if backup_branch:
  1217. print(f" 6. Remember backup branch: {backup_branch}")
  1218. print("=" * 60)
  1219. except Exception as e:
  1220. logging.error(f"\nAn unexpected error occurred: {e}", exc_info=True)
  1221. try: # Log AI feedback if possible
  1222. if response and hasattr(response, "prompt_feedback"):
  1223. logging.error(f"AI Prompt Feedback: {response.prompt_feedback}")
  1224. # ... (rest of feedback logging) ...
  1225. except Exception as feedback_e:
  1226. logging.error(
  1227. f"Could not retrieve detailed feedback from AI response: {feedback_e}"
  1228. )
  1229. print("\n❌ An unexpected error occurred during the process.")
  1230. print(" Please check the logs and your Git status.")
  1231. print(" You may need to run `git rebase --abort` manually.")
  1232. def check_git_status():
  1233. """Checks if the Git working directory is clean."""
  1234. status_output = run_git_command(
  1235. ["status", "--porcelain"], check=True, capture_output=True
  1236. )
  1237. if status_output is None:
  1238. # Error running command, already logged by run_git_command
  1239. return False # Assume dirty or error state
  1240. if status_output:
  1241. logging.warning("Git working directory is not clean.")
  1242. print(
  1243. "⚠️ Your Git working directory has uncommitted changes or untracked files:"
  1244. )
  1245. print(status_output)
  1246. print("Please commit or stash your changes before running this tool.")
  1247. return False
  1248. logging.info("Git working directory is clean.")
  1249. return True
  1250. def main():
  1251. """Main function to orchestrate Git analysis and AI interaction."""
  1252. parser = argparse.ArgumentParser(
  1253. description="Uses Gemini AI to suggest and automatically attempt Git 'fixup' and 'reword' operations.",
  1254. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  1255. )
  1256. parser.add_argument(
  1257. "upstream_ref",
  1258. nargs="?",
  1259. default="upstream/main",
  1260. help="The upstream reference point or commit hash to compare against "
  1261. "(e.g., 'origin/main', 'upstream/develop', specific_commit_hash). "
  1262. "Ensure this reference exists and is fetched.",
  1263. )
  1264. # --- Argument Change ---
  1265. parser.add_argument(
  1266. "--instruct",
  1267. action="store_true",
  1268. help="Only show AI suggestions and instructions; disable automatic fixup attempt.",
  1269. )
  1270. parser.add_argument(
  1271. "-v", "--verbose", action="store_true", help="Enable verbose debug logging."
  1272. )
  1273. parser.add_argument(
  1274. "--delete-backups",
  1275. action="store_true",
  1276. help="Delete all backup branches created by this tool for the current branch and exit.",
  1277. )
  1278. args = parser.parse_args()
  1279. if args.verbose:
  1280. logging.getLogger().setLevel(logging.DEBUG)
  1281. logging.debug("Verbose logging enabled.")
  1282. # --- Initial Checks ---
  1283. if not check_git_repository():
  1284. logging.error("This script must be run from within a Git repository.")
  1285. sys.exit(1)
  1286. if not check_git_status():
  1287. sys.exit(1) # Exit if working directory is not clean
  1288. # Handle --delete-backups flag first
  1289. if args.delete_backups:
  1290. current_branch = get_current_branch()
  1291. if not current_branch:
  1292. logging.error("Could not determine the current Git branch.")
  1293. sys.exit(1)
  1294. backup_pattern = f"{current_branch}-backup-*"
  1295. logging.info(f"Searching for backup branches matching: {backup_pattern}")
  1296. # List backup branches
  1297. list_command = ["branch", "--list", backup_pattern]
  1298. backup_branches_output = run_git_command(
  1299. list_command, check=True, capture_output=True
  1300. )
  1301. if backup_branches_output:
  1302. # Branches are listed one per line, potentially with leading whitespace/asterisk
  1303. branches_to_delete = [
  1304. b.strip().lstrip("* ")
  1305. for b in backup_branches_output.splitlines()
  1306. if b.strip()
  1307. ]
  1308. if branches_to_delete:
  1309. print(f"Found backup branches for '{current_branch}':")
  1310. for branch in branches_to_delete:
  1311. print(f" - {branch}")
  1312. delete_command = ["branch", "-D"] + branches_to_delete
  1313. print(
  1314. f"Attempting to delete {len(branches_to_delete)} backup branch(es)..."
  1315. )
  1316. delete_output = run_git_command(
  1317. delete_command, check=False, capture_output=True
  1318. ) # Use check=False to see output even on error
  1319. if (
  1320. delete_output is not None
  1321. ): # run_git_command returns None on CalledProcessError
  1322. # Print the output from the delete command (shows which branches were deleted)
  1323. print("--- Deletion Output ---")
  1324. print(delete_output if delete_output else "(No output)")
  1325. print("-----------------------")
  1326. print("✅ Backup branches deleted successfully.")
  1327. sys.exit(0)
  1328. else:
  1329. # Error occurred, run_git_command already logged details
  1330. print("❌ Failed to delete backup branches. Check logs above.")
  1331. sys.exit(1)
  1332. else:
  1333. print(f"No backup branches matching '{backup_pattern}' found.")
  1334. sys.exit(0)
  1335. else:
  1336. # Handle case where listing command succeeds but finds nothing
  1337. print(f"No backup branches matching '{backup_pattern}' found.")
  1338. sys.exit(0)
  1339. # Proceed with rebase/reword if --delete-backups was not used
  1340. rebase(args)
  1341. reword(args)
  1342. if __name__ == "__main__":
  1343. main()