Skip to content

Instantly share code, notes, and snippets.

@gwpl
Last active February 21, 2025 18:53
Show Gist options
  • Save gwpl/6f2c8f2574db6df770c51795d02cd458 to your computer and use it in GitHub Desktop.
Save gwpl/6f2c8f2574db6df770c51795d02cd458 to your computer and use it in GitHub Desktop.
A Python script to monitor Git commits and execute a specified command upon detecting changes.
#!/usr/bin/env python3
# TL;DR- Put it in PATH and `chmod +x` and enjoy `on_git_commit_change.py -c -- command to run every time I make new commit`
# https://gist.github.com/gwpl/6f2c8f2574db6df770c51795d02cd458
import argparse
import subprocess
import time
import sys
def parse_arguments():
parser = argparse.ArgumentParser(description="Monitor Git commit changes and execute a command.")
parser.add_argument('-f', '--frequency', type=float, default=0.5, help='Frequency of checking for new commits in seconds.')
parser.add_argument('-s', '--silent', action='store_true', help='Run in silent mode.')
parser.add_argument('command', nargs=argparse.REMAINDER, help='Command to execute on new commit.')
parser.add_argument('-a', '--after-change', action='store_true', help='Execute command only after observing a change.')
parser.add_argument('-c', '--clear', action='store_true', help='Clear the terminal before logging new commit.')
return parser.parse_args()
def log_info(message, silent):
if not silent:
print(f"INFO: {message}", file=sys.stderr)
def get_current_commit():
return subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode('utf-8')
def main():
args = parse_arguments()
if not args.command:
print("No command provided to execute on commit change.", file=sys.stderr)
sys.exit(1)
current_commit = None
if args.after_change:
# If the after-change flag is set, initialize current_commit to the current HEAD
current_commit = get_current_commit()
log_info(f"Current commit: {current_commit}", args.silent)
while True:
new_commit = get_current_commit()
if new_commit != current_commit:
if args.clear:
subprocess.run(['clear'])
log_info(f"New commit detected: {new_commit}", args.silent)
# Run the git log command to show the latest commit details
subprocess.run(['git', 'log', '-1', '--pretty=oneline'])
current_commit = new_commit
subprocess.run(args.command[1:])
time.sleep(args.frequency)
if __name__ == "__main__":
main()

TL;DR- Put it in PATH and chmod +x and enjoy on_git_commit_change.py -c -- command to run every time I make new commit

This script is a Python utility designed to monitor changes in a Git repository and execute a specified command whenever a new commit is detected. Here's a brief breakdown of its functionality:

  • Argument Parsing: The script uses the argparse library to handle command-line arguments. These include:

    • -f or --frequency: Sets the time (in seconds) between each check for new commits.
    • -s or --silent: If specified, suppresses logging output.
    • -a or --after-change: Runs the command only after a change is detected, by initialising the current commit.
    • -c or --clear: Clears the terminal before logging information about a new commit.
    • command: The command to be executed when a new commit is detected.
  • Commit Monitoring: It continuously monitors the latest commit in the current Git repository using the git rev-parse HEAD command to get the latest commit hash.

  • Logging: It logs information to the stderr unless the silent mode is activated.

  • Execution Trigger: Upon detecting a new commit (i.e., a change in the commit hash), it conditionally clears the terminal, logs the new commit, and executes the specified command.

  • Loop: The script runs indefinitely, checking for new commits at intervals specified by the frequency argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment