-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit_commitai.py
More file actions
executable file
·1694 lines (1396 loc) · 60.1 KB
/
git_commitai.py
File metadata and controls
executable file
·1694 lines (1396 loc) · 60.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import os
import sys
import json
import subprocess
import shlex
import argparse
import time
import re
from datetime import datetime
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from typing import Dict, List, Optional, Tuple, Any, Union
# Version information
__version__ = "0.1.0"
# Global debug flag
DEBUG: bool = False
# Retry configuration constants
MAX_RETRIES: int = 3
RETRY_DELAY: int = 2 # seconds between retries
RETRY_BACKOFF: float = 1.5 # backoff multiplier for each retry
REQ_TIMEOUT: int = 300 # 5 minutes timeout for requests
def redact_secrets(message: Union[str, Any]) -> str:
"""Redact sensitive information from debug messages.
Args:
message: Message to redact (will be converted to string if not already)
Returns:
String with sensitive information redacted
"""
if not isinstance(message, str):
message = str(message)
# Patterns for common sensitive data
patterns: List[Tuple[str, Any]] = [
# API keys (various formats)
(r'\b[A-Za-z0-9]{32,}\b', lambda m: m.group()[:4] + '...' + m.group()[-4:] if len(m.group()) > 8 else 'REDACTED'),
# Bearer tokens in Authorization headers
(r'Bearer\s+[\w\-\.]+', 'Bearer [REDACTED]'),
# Basic auth credentials
(r'Basic\s+[\w\+/=]+', 'Basic [REDACTED]'),
# API keys in various formats (key=value, apikey:value, etc.)
(r'(api[_\-]?key|token|secret|password|auth|credential)["\']?\s*[:=]\s*["\']?[\w\-\.]+["\']?',
lambda m: m.group().split(':')[0].split('=')[0] + '=[REDACTED]'),
# Environment variable values for sensitive vars
(r'GIT_COMMIT_AI_KEY["\']?\s*[:=]\s*["\']?[\w\-\.]+["\']?', 'GIT_COMMIT_AI_KEY=[REDACTED]'),
# URLs with embedded credentials
(r'(https?://)([^:]+):([^@]+)@', r'\1[USER]:[PASS]@'),
# JSON values for sensitive keys
(r'"(api_key|apiKey|token|secret|password|auth|credential)"\s*:\s*"[^"]*"',
lambda m: f'"{m.group().split(":")[0].strip()[1:-1]}": "[REDACTED]"'),
# OAuth tokens
(r'oauth[_\-]?token["\']?\s*[:=]\s*["\']?[\w\-\.]+["\']?', 'oauth_token=[REDACTED]'),
# SSH keys (partial redaction)
(r'ssh-rsa\s+[\w\+/=]+', lambda m: 'ssh-rsa ' + m.group().split()[1][:10] + '...[REDACTED]'),
# Private keys
(r'-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----[\s\S]+?-----END\s+(RSA\s+)?PRIVATE\s+KEY-----',
'-----BEGIN PRIVATE KEY-----\n[REDACTED]\n-----END PRIVATE KEY-----'),
]
redacted: str = message
for pattern, replacement in patterns:
if callable(replacement):
redacted = re.sub(pattern, replacement, redacted, flags=re.IGNORECASE)
else:
redacted = re.sub(pattern, replacement, redacted, flags=re.IGNORECASE)
return redacted
def debug_log(message: str) -> None:
"""Log debug messages if debug mode is enabled, with secret redaction.
Args:
message: Debug message to log
"""
if DEBUG:
# Redact sensitive information before logging
safe_message: str = redact_secrets(message)
print(f"DEBUG: {safe_message}", file=sys.stderr)
def show_man_page() -> bool:
"""Try to show the man page, fall back to help text if not available.
Returns:
True if man page was shown, False otherwise
"""
try:
# Try to use man command to show the man page
result = subprocess.run(
["man", "git-commitai"],
check=False
)
if result.returncode == 0:
return True
except (subprocess.CalledProcessError, FileNotFoundError):
pass
# If man page is not available, return False to show argparse help
return False
def get_git_root() -> str:
"""Get the root directory of the git repository.
Returns:
Path to git repository root
"""
try:
return run_git(["rev-parse", "--show-toplevel"]).strip()
except (subprocess.CalledProcessError, Exception):
return os.getcwd()
def load_gitcommitai_config() -> Dict[str, Any]:
"""Load configuration from .gitcommitai file in the repository root.
The .gitcommitai file should contain a prompt template with placeholders:
- {CONTEXT} - User-provided context via -m flag
- {DIFF} - The git diff of changes
- {FILES} - The modified files with their content
- {GITMESSAGE} - Content from .gitmessage template if exists
- {AMEND_NOTE} - Note about amending if --amend is used
Also supports optional model configuration.
Returns:
Dictionary containing configuration (may be empty)
"""
debug_log("Looking for .gitcommitai configuration file")
config: Dict[str, Any] = {}
try:
git_root: str = get_git_root()
config_path: str = os.path.join(git_root, ".gitcommitai")
if not os.path.exists(config_path):
debug_log("No .gitcommitai file found")
return config
debug_log(f"Found .gitcommitai at: {config_path}")
with open(config_path, 'r') as f:
content: str = f.read()
# Check if it's JSON format (for backward compatibility)
content_stripped: str = content.strip()
if content_stripped.startswith('{'):
try:
json_config: Dict[str, Any] = json.loads(content)
# Extract only model and prompt from JSON
if 'model' in json_config:
config['model'] = json_config['model']
if 'prompt' in json_config:
config['prompt_template'] = json_config['prompt']
debug_log("Loaded .gitcommitai as JSON format")
return config
except json.JSONDecodeError:
debug_log("Failed to parse as JSON, treating as template")
# Check for model specification at the top of the file
lines: List[str] = content.split('\n')
template_lines: List[str] = []
for line in lines:
# Check for model specification (e.g., "model: gpt-4" or "model=gpt-4")
if line.strip().startswith('model:') or line.strip().startswith('model='):
model_value: str = line.split(':', 1)[1] if ':' in line else line.split('=', 1)[1]
config['model'] = model_value.strip()
debug_log(f"Found model specification: {config['model']}")
else:
template_lines.append(line)
# The rest is the prompt template
prompt_template: str = '\n'.join(template_lines).strip()
if prompt_template:
config['prompt_template'] = prompt_template
debug_log(f"Loaded prompt template ({len(prompt_template)} characters)")
except Exception as e: # Catch all exceptions
debug_log(f"Error loading .gitcommitai: {e}")
return config
def get_env_config(args: argparse.Namespace) -> Dict[str, Any]:
"""Get configuration from environment variables, .gitcommitai file, and command line args.
Args:
args: Parsed command line arguments
Returns:
Configuration dictionary with API settings and repo config
"""
debug_log("Loading environment configuration")
# Load from .gitcommitai file first
repo_config: Dict[str, Any] = load_gitcommitai_config()
# Build final config with precedence: CLI args > env vars > .gitcommitai > defaults
config: Dict[str, Any] = {
"api_key": (
args.api_key or
os.environ.get("GIT_COMMIT_AI_KEY")
),
"api_url": (
args.api_url or
os.environ.get("GIT_COMMIT_AI_URL", "https://openrouter.ai/api/v1/chat/completions")
),
"model": (
args.model or
os.environ.get("GIT_COMMIT_AI_MODEL") or
repo_config.get("model") or
"qwen/qwen3-coder"
),
}
# Add repository-specific configuration
config["repo_config"] = repo_config
# Log config with redacted sensitive values
debug_log(f"Config loaded - URL: {config['api_url']}, Model: {config['model']}, Key present: {bool(config['api_key'])}")
debug_log(f"Repository config keys: {list(repo_config.keys())}")
if not config["api_key"]:
print("Error: GIT_COMMIT_AI_KEY environment variable is not set")
print()
print("Please set up your API credentials:")
print(" export GIT_COMMIT_AI_KEY='your-api-key'")
print(
" export GIT_COMMIT_AI_URL='https://openrouter.ai/api/v1/chat/completions' # or your provider's URL"
)
print(" export GIT_COMMIT_AI_MODEL='qwen/qwen3-coder' # or your preferred model")
print()
print("For quick setup, run: curl -sSL https://raw.githubusercontent.com/semperai/git-commitai/master/install.sh | bash")
sys.exit(1)
return config
def run_git(args: List[str], check: bool = True) -> str:
"""Run git with a list of args safely (no shell). Returns stdout text.
Args:
args: List of git command arguments
check: Whether to raise exception on non-zero exit code
Returns:
Standard output from git command
Raises:
subprocess.CalledProcessError: If check=True and command fails
"""
debug_log(f"Running git command: git {' '.join(args)}")
try:
result = subprocess.run(
["git"] + args,
capture_output=True,
text=True,
check=check
)
debug_log(f"Git command successful, output length: {len(result.stdout)} chars")
return result.stdout
except subprocess.CalledProcessError as e:
debug_log(f"Git command failed with code {e.returncode}: {e.stderr}")
if check:
raise
return e.stdout if e.stdout else ""
def build_ai_prompt(repo_config: Dict[str, Any], args: argparse.Namespace) -> str:
"""Build the AI prompt, incorporating repository-specific customization.
Args:
repo_config: Repository-specific configuration
args: Parsed command line arguments
Returns:
Complete prompt string for AI
"""
# Check if repository has a custom prompt template
if repo_config.get('prompt_template'):
debug_log("Using custom prompt template from .gitcommitai")
# Read .gitmessage if it exists
gitmessage_content: str = read_gitmessage_template() or ""
# Prepare replacement values
replacements: Dict[str, str] = {
'CONTEXT': f"Additional context from user: {args.message}" if args.message else "",
'GITMESSAGE': gitmessage_content,
'AMEND_NOTE': "Note: You are amending the previous commit." if args.amend else "",
}
# Start with the template
base_prompt: str = repo_config['prompt_template']
# Replace placeholders - but don't add them yet for DIFF and FILES
# We'll add those at the end of the function
for key, value in replacements.items():
if key not in ['DIFF', 'FILES']:
placeholder: str = '{' + key + '}'
if placeholder in base_prompt:
base_prompt = base_prompt.replace(placeholder, value)
# Normalize excessive blank lines introduced by empty replacements
base_prompt = re.sub(r"\n{3,}", "\n\n", base_prompt).strip("\n")
else:
# Use default prompt
debug_log("Using default prompt")
base_prompt = """You are a git commit message generator that follows Git best practices strictly.
CRITICAL RULES YOU MUST FOLLOW:
1. STRUCTURE:
- If the change is simple and clear, use ONLY a subject line (single line commit)
- For complex changes that need explanation, use subject + blank line + body
- Never add a body unless it provides valuable context about WHY the change was made
2. SUBJECT LINE (FIRST LINE):
- Maximum 50 characters (aim for less when possible)
- Start with a capital letter
- NO period at the end
- Use imperative mood (e.g., "Add", "Fix", "Update", not "Added", "Fixes", "Updated")
- Be concise but descriptive
- Think: "If applied, this commit will [your subject line]"
3. BODY (ONLY if needed):
- Leave one blank line after the subject
- Wrap lines at 72 characters maximum
- Explain WHAT changed and WHY, not HOW (the code shows how)
- Focus on the motivation and context for the change
- Use bullet points with "-" for multiple items if needed
4. GOOD SUBJECT LINE EXAMPLES:
- "Add user authentication module"
- "Fix memory leak in data processor"
- "Update dependencies to latest versions"
- "Refactor database connection logic"
- "Remove deprecated API endpoints"
5. CODE ISSUE DETECTION:
After generating the message, check the code changes for potential issues.
If you detect any obvious problems, add warnings as Git-style comments after the commit message.
These warnings help the developer catch bugs before committing.
Look for these types of severe or critical issues:
- Hardcoded secrets
- Syntax errors or typos in variable names
- null/undefined reference errors
- Missing imports that will cause runtime errors
Format warnings like this:
# ⚠️ WARNING: [Brief description of issue]
# Found in: [filename]
# Details: [Specific concern]
6. OUTPUT FORMAT:
- Generate the commit message following ALL formatting rules correctly
- Add a blank line after the message
- If code issues detected, add warning comments
- NO explanations outside of warning comments
- NO markdown formatting
- NEVER warn about commit message formatting (you should generate it correctly)
Remember:
- Most commits only need a clear subject line
- You are responsible for generating a properly formatted message - don't warn about your own formatting
- Only warn about actual code issues that could cause problems"""
# Add .gitmessage template context if available and not already included via template
if not repo_config.get('prompt_template'):
gitmessage_template: Optional[str] = read_gitmessage_template()
if gitmessage_template:
base_prompt += f"""
PROJECT-SPECIFIC COMMIT TEMPLATE/GUIDELINES:
The following template or guidelines are configured for this project. Use this as additional context
to understand the project's commit message conventions, but still follow the Git best practices above:
{gitmessage_template}
"""
debug_log("Added .gitmessage template to prompt context")
# Add user context
if args.message:
base_prompt += f"\n\nAdditional context from user: {args.message}"
return base_prompt
def stage_all_tracked_files() -> bool:
"""Stage all tracked, modified files (equivalent to git add -u).
Returns:
True if successful, False otherwise
"""
debug_log("Staging all tracked files with 'git add -u'")
try:
# git add -u stages all tracked files that have been modified or deleted
# but does NOT add untracked files
subprocess.run(["git", "add", "-u"], check=True, capture_output=True)
debug_log("Successfully staged tracked files")
return True
except subprocess.CalledProcessError as e:
debug_log(f"Failed to stage tracked files: {e}")
print(f"Error: Failed to stage tracked files: {e}")
return False
def check_staged_changes(amend: bool = False, auto_stage: bool = False, allow_empty: bool = False) -> bool:
"""Check if there are staged changes and provide git-like output if not.
Args:
amend: Whether we're amending a commit
auto_stage: Whether to auto-stage tracked files
allow_empty: Whether to allow empty commits
Returns:
True if we can proceed with commit, False otherwise
"""
debug_log(f"Checking staged changes - amend: {amend}, auto_stage: {auto_stage}, allow_empty: {allow_empty}")
if auto_stage and not amend:
# First, check if there are any changes to stage
try:
# Check for modified tracked files
result = subprocess.run(["git", "diff", "--quiet"], capture_output=True)
if result.returncode != 0:
debug_log("Found unstaged changes, auto-staging them")
# There are unstaged changes in tracked files, stage them
if not stage_all_tracked_files():
return False
else:
debug_log("No unstaged changes to auto-stage")
# Continue to check if we now have staged changes
except subprocess.CalledProcessError:
pass
if amend:
# For --amend, we're modifying the last commit, so we don't need staged changes
# But we should check if there's a previous commit to amend
try:
run_git(["rev-parse", "HEAD"], check=True)
debug_log("Found previous commit to amend")
return True
except subprocess.CalledProcessError:
debug_log("No previous commit to amend")
print("fatal: You have nothing to amend.")
return False
# If --allow-empty is set, we can proceed even without staged changes
if allow_empty:
debug_log("Allow empty flag set, proceeding without staged changes")
return True
try:
result = subprocess.run(
["git", "diff", "--cached", "--quiet"], capture_output=True
)
if result.returncode == 0:
debug_log("No staged changes found")
# No staged changes - mimic git commit output
show_git_status()
return False
debug_log("Found staged changes")
return True
except subprocess.CalledProcessError:
return False
def show_git_status() -> None:
"""Show git status output similar to what 'git commit' shows."""
debug_log("Showing git status")
# Get branch name
try:
branch: str = run_git(["branch", "--show-current"]).strip()
if not branch: # detached HEAD state
branch = run_git(["rev-parse", "--short", "HEAD"]).strip()
print(f"HEAD detached at {branch}")
else:
print(f"On branch {branch}")
except:
print("On branch master")
# Check if this is initial commit
try:
run_git(["rev-parse", "HEAD"], check=True)
except:
print("\nInitial commit\n")
# Get untracked and modified files - don't strip to preserve all lines
try:
status_output: str = run_git(["status", "--porcelain"])
untracked: List[str] = []
modified: List[str] = []
deleted: List[str] = []
if status_output:
# Split on newlines but preserve empty strings to handle all lines
lines: List[str] = (
status_output.rstrip("\n").split("\n")
if status_output.rstrip("\n")
else []
)
for line in lines:
if not line:
continue
# Git status --porcelain format: XY filename
# X = staged status, Y = working tree status
if len(line) >= 3:
staged_status: str = line[0] if len(line) > 0 else " "
working_status: str = line[1] if len(line) > 1 else " "
filename: str = line[3:] if len(line) > 3 else ""
if not filename:
continue
if staged_status == "?" and working_status == "?":
untracked.append(filename)
elif working_status == "M": # Modified in working tree
modified.append(filename)
elif working_status == "D": # Deleted in working tree
deleted.append(filename)
# Show unstaged changes
changes_shown: bool = False
if modified or deleted:
print("Changes not staged for commit:")
print(' (use "git add <file>..." to update what will be committed)')
print(
' (use "git restore <file>..." to discard changes in working directory)'
)
for f in sorted(modified):
print(f"\tmodified: {f}")
for f in sorted(deleted):
print(f"\tdeleted: {f}")
changes_shown = True
# Show untracked files
if untracked:
if changes_shown:
print()
print("Untracked files:")
print(' (use "git add <file>..." to include in what will be committed)')
for f in sorted(untracked):
print(f"\t{f}")
changes_shown = True
# Final message
if not changes_shown:
print("nothing to commit, working tree clean")
else:
print()
if untracked and not modified and not deleted:
print(
'nothing added to commit but untracked files present (use "git add" to track)'
)
elif modified or deleted:
print(
'no changes added to commit (use "git add" and/or "git commit -a")'
)
except Exception as e:
debug_log(f"Error showing git status: {e}")
# Fallback to simple message if something goes wrong
print("No changes staged for commit")
def get_binary_file_info(filename: str, amend: bool = False) -> str:
"""Get information about a binary file.
Args:
filename: Path to the binary file
amend: Whether we're amending a commit
Returns:
Formatted information about the binary file
"""
debug_log(f"Getting binary file info for: {filename}")
info_parts: List[str] = []
# Get file extension
_, ext = os.path.splitext(filename)
if ext:
info_parts.append(f"File type: {ext}")
# Try to get file size from git
try:
size_output: str
if amend:
# Try to get size from index first, then HEAD
size_output = run_git(["cat-file", "-s", f":{filename}"], check=False)
if not size_output or "fatal:" in size_output:
size_output = run_git(["cat-file", "-s", f"HEAD:{filename}"], check=False)
else:
size_output = run_git(["cat-file", "-s", f":{filename}"], check=False)
if size_output and "fatal:" not in size_output:
size_bytes: int = int(size_output.strip())
size_str: str
# Format size nicely
if size_bytes < 1024:
size_str = f"{size_bytes} bytes"
elif size_bytes < 1024 * 1024:
size_str = f"{size_bytes / 1024:.1f} KB"
else:
size_str = f"{size_bytes / (1024 * 1024):.1f} MB"
info_parts.append(f"Size: {size_str}")
except:
pass
# Common binary file type descriptions
binary_descriptions: Dict[str, str] = {
".jpg": "JPEG image",
".jpeg": "JPEG image",
".png": "PNG image",
".gif": "GIF image",
".webp": "WebP image",
".svg": "SVG vector image",
".ico": "Icon file",
".pdf": "PDF document",
".zip": "ZIP archive",
".tar": "TAR archive",
".gz": "Gzip compressed file",
".exe": "Windows executable",
".dll": "Dynamic link library",
".so": "Shared object library",
".dylib": "Dynamic library (macOS)",
".mp3": "MP3 audio",
".mp4": "MP4 video",
".avi": "AVI video",
".mov": "QuickTime video",
".ttf": "TrueType font",
".woff": "Web font",
".woff2": "Web font 2.0",
".db": "Database file",
".sqlite": "SQLite database",
}
if ext.lower() in binary_descriptions:
info_parts.append(f"Description: {binary_descriptions[ext.lower()]}")
# Check if it's a new file or modified
try:
if amend:
# Check if file exists in parent commit
run_git(["cat-file", "-e", f"HEAD^:{filename}"], check=True)
info_parts.append("Status: Modified")
else:
# Check if file exists in HEAD
run_git(["cat-file", "-e", f"HEAD:{filename}"], check=True)
info_parts.append("Status: Modified")
except:
info_parts.append("Status: New file")
return (
"\n".join(info_parts)
if info_parts
else "Binary file (no additional information available)"
)
def get_staged_files(amend: bool = False, allow_empty: bool = False) -> str:
"""Get list of staged files with their staged contents.
Args:
amend: Whether we're amending a commit
allow_empty: Whether this is an empty commit
Returns:
Formatted string with file contents
"""
debug_log(f"Getting staged files - amend: {amend}, allow_empty: {allow_empty}")
files_output: str
if amend:
# For --amend, get files from the last commit plus any newly staged files
# First, get files from the last commit
last_commit_files: str = run_git(
["diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"]
).strip()
# Then, get any newly staged files
staged_files: str = run_git(["diff", "--cached", "--name-only"]).strip()
# Combine and deduplicate
all_filenames: set[str] = set()
if last_commit_files:
all_filenames.update(last_commit_files.split("\n"))
if staged_files:
all_filenames.update(staged_files.split("\n"))
files_output = "\n".join(sorted(all_filenames))
else:
files_output = run_git(["diff", "--cached", "--name-only"]).strip()
debug_log(f"Found {len(files_output.split()) if files_output else 0} staged files")
if not files_output:
if allow_empty:
return "# No files changed (empty commit)"
return ""
all_files: List[str] = []
for filename in files_output.split("\n"):
if filename:
try:
# Check if file is binary
is_binary_check: str
if amend:
# For amend, check if file exists in index first, then HEAD
is_binary_check = run_git(
["diff", "--cached", "--numstat", "--", filename], check=False
)
if not is_binary_check or "fatal:" in is_binary_check:
is_binary_check = run_git(
["diff", "HEAD^", "HEAD", "--numstat", "--", filename], check=False
)
else:
is_binary_check = run_git(
["diff", "--cached", "--numstat", "--", filename], check=False
)
# Git shows '-' for binary files in numstat
if is_binary_check and is_binary_check.strip().startswith("-"):
# It's a binary file
file_info: str = get_binary_file_info(filename, amend)
all_files.append(
f"{filename} (binary file)\n```\n{file_info}\n```\n"
)
else:
# It's a text file, get its content
staged_content: str
if amend:
# Try staged version first, then fall back to HEAD version
staged_content = run_git(
["show", f":{filename}"], check=False
)
if not staged_content or "fatal:" in staged_content:
# Fall back to HEAD version
staged_content = run_git(
["show", f"HEAD:{filename}"], check=False
)
staged_content = staged_content.strip()
else:
# Get the staged content of the file (what's in the index)
staged_content = run_git(
["show", f":{filename}"], check=False
).strip()
# Redact any secrets in file content before including in debug logs
debug_log(f"Processing file {filename} with content length: {len(staged_content)}")
if (
staged_content or staged_content == ""
): # Include empty files too
all_files.append(f"{filename}\n```\n{staged_content}\n```\n")
except Exception as e:
debug_log(f"Error processing file {filename}: {e}")
# File might be newly added or have other issues, skip it
continue
return "\n".join(all_files) if all_files else "# No files changed (empty commit)"
def get_git_diff(amend: bool = False, allow_empty: bool = False) -> str:
"""Get the git diff of staged changes, with binary file handling.
Args:
amend: Whether we're amending a commit
allow_empty: Whether this is an empty commit
Returns:
Formatted diff string
"""
debug_log(f"Getting git diff - amend: {amend}, allow_empty: {allow_empty}")
diff: str
if amend:
# For --amend, show the diff of the last commit plus any new staged changes
# Get the parent of HEAD (or use empty tree if it's the first commit)
try:
parent: str = run_git(["rev-parse", "HEAD^"]).strip()
# Diff from parent to current index (staged changes + last commit)
diff = run_git(["diff", f"{parent}..HEAD"]).strip()
# Also include any newly staged changes
staged_diff: str = run_git(["diff", "--cached"]).strip()
if staged_diff:
diff = (
f"{diff}\n\n# Additional staged changes:\n{staged_diff}"
if diff
else staged_diff
)
except:
# First commit, use empty tree
diff = run_git(["diff", "--cached"]).strip()
else:
diff = run_git(["diff", "--cached"]).strip()
debug_log(f"Diff size: {len(diff)} characters")
if not diff and allow_empty:
return "```\n# No changes (empty commit)\n```"
# Process the diff to add information about binary files
diff_lines: List[str] = diff.split("\n") if diff else []
processed_lines: List[str] = []
i: int = 0
while i < len(diff_lines):
line: str = diff_lines[i]
# Check for binary file indicators
if line.startswith("Binary files"):
# Extract filename from the binary files line
# Format: "Binary files a/path/file and b/path/file differ"
parts: List[str] = line.split(" ")
if len(parts) >= 4:
file_a: str = parts[2].lstrip("a/")
file_b: str = parts[4].lstrip("b/")
# Use the 'b/' version as it's the new version
filename: str = file_b if file_b != "/dev/null" else file_a
# Add enhanced binary file information
processed_lines.append(line)
processed_lines.append(f"# Binary file: {filename}")
# Try to get more info about the binary file
binary_info: str = get_binary_file_info(filename, amend)
for info_line in binary_info.split("\n"):
processed_lines.append(f"# {info_line}")
else:
processed_lines.append(line)
i += 1
processed_diff: str = "\n".join(processed_lines) if processed_lines else diff
return f"```\n{processed_diff}\n```"
def get_git_editor() -> str:
"""Get the configured git editor.
Returns:
Editor command string
"""
# Check environment variables first
editor: Optional[str] = os.environ.get("GIT_EDITOR")
if editor:
return editor
editor = os.environ.get("EDITOR")
if editor:
return editor
# Try git config
try:
editor = run_git(["config", "--get", "core.editor"], check=False).strip()
if editor:
return editor
except:
pass
# Default fallback
return "vi"
def get_current_branch() -> str:
"""Get current git branch name.
Returns:
Branch name or commit hash if detached
"""
try:
branch: str = run_git(["branch", "--show-current"]).strip()
if not branch: # detached HEAD state
return run_git(["rev-parse", "--short", "HEAD"]).strip()
return branch
except:
return "unknown"
def get_git_dir() -> str:
"""Get the .git directory path.
Returns:
Path to .git directory
"""
# This should never fail since we check in main(), but just in case
return run_git(["rev-parse", "--git-dir"]).strip()
def read_gitmessage_template() -> Optional[str]:
"""Read .gitmessage template file if it exists.
Returns:
Template content or None if not found
"""
debug_log("Checking for .gitmessage template file")
# 1. Check for .gitmessage in repository root (HIGHEST PRIORITY)
try:
git_root: str = get_git_root()
repo_gitmessage: str = os.path.join(git_root, ".gitmessage")
if os.path.isfile(repo_gitmessage):
debug_log(f"Found repository .gitmessage: {repo_gitmessage}")
try:
with open(repo_gitmessage, 'r') as f:
content: str = f.read()
debug_log("Successfully read repository .gitmessage template")
debug_log(f"Template content length: {len(content)} characters")
return content
except (IOError, OSError) as e:
debug_log(f"Failed to read repository template from {repo_gitmessage}: {e}")
except Exception as e:
debug_log(f"Error checking for repository .gitmessage: {e}")
# 2. Check git config for commit.template (SECOND PRIORITY)
try:
configured_template: str = run_git(["config", "--get", "commit.template"], check=False).strip()
if configured_template:
# Expand ~ to home directory if present
if configured_template.startswith("~"):
configured_template = os.path.expanduser(configured_template)
# If not absolute path, make it relative to git root
elif not os.path.isabs(configured_template):
try:
git_root = get_git_root()
configured_template = os.path.join(git_root, configured_template)
except Exception:
pass
if os.path.isfile(configured_template):
debug_log(f"Found configured template: {configured_template}")
try:
with open(configured_template, 'r') as f:
content = f.read()
debug_log(f"Successfully read configured template")
debug_log(f"Template content length: {len(content)} characters")
return content
except (IOError, OSError) as e:
debug_log(f"Failed to read configured template from {configured_template}: {e}")
except Exception as e:
debug_log(f"Error checking for configured template: {e}")
# 3. Check for global .gitmessage in home directory (LOWEST PRIORITY)
try:
home_gitmessage: str = os.path.expanduser("~/.gitmessage")
if os.path.isfile(home_gitmessage):
debug_log(f"Found home directory .gitmessage: {home_gitmessage}")
try:
with open(home_gitmessage, 'r') as f:
content = f.read()
debug_log("Successfully read home directory .gitmessage template")
debug_log(f"Template content length: {len(content)} characters")
return content
except (IOError, OSError) as e:
debug_log(f"Failed to read home template from {home_gitmessage}: {e}")
except Exception as e:
debug_log(f"Error checking for home .gitmessage: {e}")
debug_log("No .gitmessage template file found")
return None
def show_dry_run_summary(args: argparse.Namespace) -> None:
"""Show what would be committed in dry-run mode by delegating to git.
Args:
args: Parsed command line arguments
"""