#!/usr/bin/env python3 """git save — AI 一鍵存檔:暫存所有變更,用 Claude 生成 commit message,自動 commit。""" import subprocess import json import urllib.request import os import sys MODEL = "claude-sonnet-5" def git(*args): result = subprocess.run(["git"] + list(args), capture_output=True, text=True) return result.stdout.strip(), result.returncode def main(): diff_before, _ = git("diff", "--cached") if not diff_before: git("add", "-A") diff, _ = git("diff", "--cached") if not diff: print("沒有任何變更需要 commit。") return if len(diff) > 10000: diff = diff[:10000] + "\n\n... (diff truncated)" api_key = os.environ.get("ANTHROPIC_API_KEY") if not api_key: print("錯誤:請設定環境變數 ANTHROPIC_API_KEY") print(" export ANTHROPIC_API_KEY=sk-ant-...") sys.exit(1) print("正在用 AI 生成 commit message...") body = json.dumps({ "model": MODEL, "max_tokens": 256, "messages": [{ "role": "user", "content": ( "Based on the following git diff, write a concise commit message. " "Use conventional commit format (e.g. feat:, fix:, docs:, refactor:). " "One line only. Output ONLY the commit message, nothing else.\n\n" + diff ), }], }).encode() req = urllib.request.Request( "https://api.anthropic.com/v1/messages", data=body, headers={ "Content-Type": "application/json", "x-api-key": api_key, "anthropic-version": "2023-06-01", }, ) try: with urllib.request.urlopen(req) as resp: data = json.loads(resp.read()) msg = data["content"][0]["text"].strip().strip('"') except urllib.error.HTTPError as e: error_body = e.read().decode() print(f"API 錯誤 ({e.code}): {error_body}") sys.exit(1) except Exception as e: print(f"錯誤:{e}") sys.exit(1) _, code = git("commit", "-m", msg) if code == 0: print(f"✓ 已存檔:{msg}") else: print("commit 失敗,請檢查 git 狀態。") sys.exit(1) if __name__ == "__main__": main()