Skip to content

Instantly share code, notes, and snippets.

@brandonbloom
Created December 3, 2024 22:39
Show Gist options
  • Save brandonbloom/580a983b4a56871767ec610b6d7ed571 to your computer and use it in GitHub Desktop.
Save brandonbloom/580a983b4a56871767ec610b6d7ed571 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import sys
import subprocess
import os
import json
import argparse
from datetime import datetime
import anthropic
def get_blame_info(file_path, line_number):
"""Get git blame info for a specific line."""
try:
blame_output = subprocess.check_output(
['git', 'blame', '-l', '-L', f'{line_number},{line_number}', file_path],
stderr=subprocess.STDOUT,
universal_newlines=True
)
# Parse the blame output
commit_hash = blame_output.split()[0]
author = subprocess.check_output(
['git', 'show', '-s', '--format=%an', commit_hash],
universal_newlines=True
).strip()
date = subprocess.check_output(
['git', 'show', '-s', '--format=%ai', commit_hash],
universal_newlines=True
).strip()
return {
'author': author,
'date': date,
'commit': commit_hash
}
except subprocess.CalledProcessError:
return None
def get_line_content(file_path, line_number):
"""Get the content of a specific line from a file."""
with open(file_path, 'r') as f:
lines = f.readlines()
if 1 <= line_number <= len(lines):
return lines[line_number - 1].strip()
return None
def generate_snarky_comment(code_info):
"""Generate a prompt for the LLM to create a snarky comment."""
return f"""Given this code context, generate a sarcastic, witty comment about it:
Code: {code_info['line_content']}
Written by: {code_info['author']}
Date: {code_info['date']}
Some context to consider for snark:
- If the code is ancient (> 1 year old)
- If it's a one-line change
- If it's overly complex or overly simple
- If it uses outdated practices
- If it's poorly formatted or has weird spacing
Please keep the tone playful and fun rather than mean-spirited."""
def call_llm_api(prompt):
"""Call Claude API to generate a snarky comment."""
# Get API key from environment variable
api_key = os.getenv('ANTHROPIC_API_KEY')
if not api_key:
raise ValueError("Please set the ANTHROPIC_API_KEY environment variable")
# Initialize the client
client = anthropic.Client(api_key = api_key)
# Make the API call
try:
response = client.messages.create(
model="claude-3-haiku-20240307", # Using Haiku for faster responses
max_tokens=150,
temperature=0.9, # Higher temperature for more creative responses
system="You are a witty code reviewer who makes playful, snarky comments about code. Keep responses short, fun, and not mean-spirited.",
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text.strip()
except Exception as e:
return f"Error generating comment: {str(e)}"
def main():
parser = argparse.ArgumentParser(description='Generate snarky comments about your code based on git blame')
parser.add_argument('file', help='File to analyze')
parser.add_argument('line_number', type=int, help='Line number to analyze')
args = parser.parse_args()
if not os.path.isfile(args.file):
print(f"Error: File '{args.file}' not found")
sys.exit(1)
blame_info = get_blame_info(args.file, args.line_number)
if not blame_info:
print("Error: Couldn't get git blame info. Are you in a git repository?")
sys.exit(1)
line_content = get_line_content(args.file, args.line_number)
if not line_content:
print("Error: Couldn't read the specified line")
sys.exit(1)
code_info = {
'line_content': line_content,
'author': blame_info['author'],
'date': blame_info['date'],
'commit': blame_info['commit']
}
prompt = generate_snarky_comment(code_info)
snarky_comment = call_llm_api(prompt)
print("\n๐Ÿ” Git Diss Analysis:")
print(f"Line {args.line_number}: {line_content}")
print(f"Author: {blame_info['author']}")
print(f"Date: {blame_info['date']}")
print("\n๐Ÿ˜ Snarky Comment:")
print(snarky_comment)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment