|
| 1 | +import subprocess |
| 2 | +import sys |
| 3 | +import os |
| 4 | +import tiktoken |
| 5 | + |
| 6 | +# Tokenizer function using OpenAI's tiktoken for LLMs (GPT-3/4) |
| 7 | +def count_tokens(text, model="gpt-4o"): |
| 8 | + encoding = tiktoken.encoding_for_model(model) |
| 9 | + return len(encoding.encode(text)) |
| 10 | + |
| 11 | +# Function to execute the git diff command and return the result |
| 12 | +def run_git_diff(commit1, commit2, diff_options): |
| 13 | + try: |
| 14 | + result = subprocess.run( |
| 15 | + ["git", "diff", commit1, commit2] + diff_options, |
| 16 | + capture_output=True, text=True, check=True, encoding='utf-8', errors='replace' |
| 17 | + ) |
| 18 | + return result.stdout |
| 19 | + except subprocess.CalledProcessError as e: |
| 20 | + print(f"Error running git diff: {e}") |
| 21 | + sys.exit(1) |
| 22 | + |
| 23 | +# Main function to generate the combined diff and calculate token count |
| 24 | +def main(commit1, commit2, output_file): |
| 25 | + # Run git diff with the first set of options |
| 26 | + diff1 = run_git_diff(commit1, commit2, ["-U100", "--ignore-all-space", "--", ":!*Test*"]) |
| 27 | + |
| 28 | + # Run git diff with the second set of options for test files |
| 29 | + diff2 = run_git_diff(commit1, commit2, ["-U20", "--ignore-all-space", "--", "*Test*"]) |
| 30 | + |
| 31 | + # Ensure both diffs are valid strings |
| 32 | + if diff1 is None: |
| 33 | + diff1 = "" |
| 34 | + if diff2 is None: |
| 35 | + diff2 = "" |
| 36 | + |
| 37 | + # Combine the two diffs |
| 38 | + combined_diff = diff1 + "\n" + diff2 |
| 39 | + |
| 40 | + # Write the combined diff to the output file |
| 41 | + with open(output_file, 'w', encoding='utf-8') as f: |
| 42 | + f.write(combined_diff) |
| 43 | + |
| 44 | + # Calculate token count using LLM tokenizer |
| 45 | + token_count = count_tokens(combined_diff) |
| 46 | + |
| 47 | + # Output results |
| 48 | + print(f"Combined diff written to {output_file}") |
| 49 | + print(f"Total number of tokens: {token_count}") |
| 50 | + |
| 51 | +# Entry point of the script |
| 52 | +if __name__ == "__main__": |
| 53 | + if len(sys.argv) != 4: |
| 54 | + print("Usage: python gitdiff4review.py <commit1> <commit2> <output_file>") |
| 55 | + sys.exit(1) |
| 56 | + |
| 57 | + commit1 = sys.argv[1] |
| 58 | + commit2 = sys.argv[2] |
| 59 | + output_file = sys.argv[3] |
| 60 | + |
| 61 | + # Make sure the output directory exists |
| 62 | + os.makedirs(os.path.dirname(output_file), exist_ok=True) |
| 63 | + |
| 64 | + main(commit1, commit2, output_file) |
0 commit comments