Reputation: 557
I'm a bit confused about how to implement git hooks correctly, and I cannot figure out how to access any type of information that I need from within my script. I have very little experience scripting/using Python.
I simply want to access the filenames of the files (and later also the contents of the file) about to be committed in a pre-commit hook, so that I can check if they match a naming convention. I've seen posts such as this one Git server hook: get contents of files being pushed?, where the poster mentions how he got a list of the files by calling git diff --cached --name-status --diff-filter=AM
.
I'm sorry if this is a stupid question, but how do I call this line from within my script and set it equal to something? I recognize that line as a Git command but I'm confused how that translates into coding it. What does it look like in python?
Here's all I currently have for a template for my pre-commit. It simply does a test print and its in Python.
#!/usr/bin/env python
import sys
print("\nError details\n")
Upvotes: 0
Views: 182
Reputation: 16361
git diff-index --name-status HEAD | grep '^[MA]'
That's the most reliable way I know. It prints out the names with an M or A prefix, followed by some whitespace, followed by the name, to indicate whether or not the file was "modified" or "added."
There is some extra magic, though. I would recommend:
git stash --keep-index
git diff-index --name-status HEAD | grep '^[MA]'
git reset --hard
git stash pop --quiet --index
This will give you the list of names in your staging area (by stashing any changes since your last git add
command) and restore your workspace back immediately afterward. Since your staging area, and not your workspace, is what you're about to commit, this is probably what you want.
I have a program that does all this at https://github.com/elfsternberg/pre-commit-stash
It's written in Hy, a dialect of Python that most people barely know about or can even read. Hy does come with a hy2py transpiler, though, so if you really need it, this script will show you how it's done.
Upvotes: 2