pre-commit hook to update README
Published on .
For my test_drives repo, I wanted the README to contain a link and a description to the test drives. I accomplished this by creating .git/hooks/pre-commit
and adding the following. It’s a bit hacky and risks being duplicative of the file list, but I like it.
#!/usr/bin/env python3
import glob
import re
import subprocess
links = []
for path in glob.glob("*.py"):
with open(path, 'r') as f:
r = f.read()
desc = re.search(r"\n\"\"\"(.*)", r, re.MULTILINE).group(1)
links.append("[{name}]({name}) - {desc}".format(name=path, desc=desc))
links = "\n* ".join(links)
with open('README.md', 'r') as f:
r = f.read()
with open('README.md', 'w') as f:
f.write(re.sub(r"<!-- links -->\n(.*)\n<!-- /links -->", f'<!-- links -->\\n* {links}\\n<!-- /links -->', r, 0, re.MULTILINE | re.DOTALL))
subprocess.run(['git', 'add', 'README.md'], check=True)
Code language: Python (python)