note-committer/main.py

103 lines
2.7 KiB
Python
Raw Permalink Normal View History

2024-09-26 05:09:21 +00:00
import os, logging
DEBUG = os.environ.get('DEBUG')
logging.basicConfig(
format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s',
level=logging.DEBUG if DEBUG else logging.INFO)
import requests
import subprocess
LLAMA_URL = 'http://10.55.0.105:11434/api/generate'
NOTES_DIR = '/home/tanner/notes-git/notes'
#NOTES_DIR = '/home/tanner/'
def llama(prompt):
data = dict(model='llama3.1', prompt=prompt, stream=False)
2024-09-26 17:50:03 +00:00
try:
r = requests.post(LLAMA_URL, json=data, timeout=10)
r.raise_for_status()
r = r.json()
return r['response']
except BaseException as e:
logging.error('Problem with llama: {} - {}'.format(e.__class__.__name__, str(e)))
return False
2024-09-26 05:09:21 +00:00
def git_diff():
result = subprocess.run(['git', 'diff', '--cached', '-U0'], stdout=subprocess.PIPE, cwd=NOTES_DIR)
diff = result.stdout.decode()
if diff:
logging.info('Analyzing diff:\n%s', diff)
return diff
def git_add():
result = subprocess.run(['git', 'add', '-A'], stdout=subprocess.PIPE, cwd=NOTES_DIR)
def git_commit(message):
result = subprocess.run(['git', 'commit', '-m', message], stdout=subprocess.PIPE, cwd=NOTES_DIR)
return result.stdout.decode()
def generate_message(diff):
prompt = '''
Write a ONE LINE git commit message for the following diff.
Respond with only the commit message.
Do not include quotes.
Do not include file extensions.
DO NOT just say "Update notes", "Add new notes", "Refactor notes", "Make documentation updates".
2024-09-26 05:09:21 +00:00
Tersely summarize how each note changed.
Write in imperitive tense.
\n\n==============\n\n'''
prompt += diff
message = llama(prompt)
2024-09-26 17:50:03 +00:00
if not message:
logging.info(' Failed to generate')
return False
2024-09-26 05:09:21 +00:00
logging.info('Generated message: %s', message)
if '.md' in message.lower():
logging.info(' Message contains .md extension, aborting')
return False
elif 'notes/' in message.lower():
logging.info(' Message contains notes directory, aborting')
return False
elif '\n' in message:
logging.info(' Message contains new lines, aborting')
return False
2024-09-26 05:09:21 +00:00
return message
def main():
git_add() # add so we can diff new files
diff = git_diff()
if not diff:
logging.info('No diff, exiting.')
exit(0)
for _ in range(5):
message = generate_message(diff)
if message:
break
else: # for loop never broke
logging.info('Unable to generate acceptable message, exiting.')
exit(1)
if DEBUG:
logging.info('Running in debug, not actually committing.')
else:
git_commit(message)
2024-09-26 05:09:21 +00:00
if __name__ == '__main__':
main()