hugo-theme-relearn/.githooks/post-commit.py

57 lines
2.3 KiB
Python
Raw Normal View History

2024-10-06 19:55:55 +00:00
#!/usr/bin/env python3
# This script appends the current commit hash to the version information in
# `layouts/partials/version.txt`
#
# Call this script from your ".git/hooks/post-commit" file like this (supporting
# Linux, Windows and MacOS)
# #!/bin/sh
# python3 .githooks/post-commit.py
from datetime import datetime
2024-10-14 18:18:36 +00:00
import os
2024-10-06 19:55:55 +00:00
import re
import subprocess
def main():
2024-10-14 18:18:36 +00:00
script_name = "POST-COMMIT"
script_dir = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_dir, "hooks.log")
2024-10-06 19:55:55 +00:00
time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
2024-10-14 18:18:36 +00:00
repo_root = subprocess.check_output(['git', 'rev-parse', '--show-toplevel'], universal_newlines=True).strip()
repo_name = os.path.basename(repo_root)
2024-10-06 19:55:55 +00:00
file_path = 'layouts/partials/version.txt'
with open(file_path, 'r+') as f:
version = f.read().strip()
new_version = ''
match = re.match(r'(\d+\.\d+\.\d+)(?:\+([^+]+))?', version)
if match:
semver = match.group(1)
old_hash = match.group(2)
new_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD~1']).decode('utf-8').strip()
2024-10-14 18:18:36 +00:00
print(f'{time}: {repo_name} - {script_name} - old hash {old_hash} - new hash {new_hash}', file=open(log_file, "a"))
print(f'{script_name} - old hash {old_hash} - new hash {new_hash}')
2024-10-06 19:55:55 +00:00
if old_hash != new_hash:
new_version = f'{semver}+{new_hash}'
f.seek(0)
f.write(new_version)
f.truncate()
f.close()
subprocess.check_call(['git', 'add', file_path])
subprocess.check_call(['git', 'commit', '--amend', '--no-edit'])
else:
2024-10-14 18:18:36 +00:00
print(f'{time}: {repo_name} - {script_name} - No change in hash, file {file_path} not updated', file=open(log_file, "a"))
print(f'{script_name} - No change in hash, file {file_path} not updated')
2024-10-06 19:55:55 +00:00
exit(0)
else:
2024-10-14 18:18:36 +00:00
print(f'{time}: {repo_name} - {script_name} - Invalid version format in {file_path}', file=open(log_file, "a"))
print(f'{script_name} - Invalid version format in {file_path}')
2024-10-06 19:55:55 +00:00
exit(1)
2024-10-14 18:18:36 +00:00
print(f'{time}: {repo_name} - {script_name} - New version {new_version} was written to {file_path}', file=open(log_file, "a"))
2024-10-06 19:55:55 +00:00
exit(0)
if __name__ == '__main__':
main()