Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

githooks - Determine If Any File Changed In Directory For Latest Git Commit

I'm writing a post-commit hook for git. I would like to know if the latest commit changed any of the files in a particular directory. If there were any changes I can then proceed and call some expensive code, otherwise I can just skip it.

So, far I'm getting the short hash like so:

# get last commit hash prepended with @ (i.e. @8a323d0)
function parse_git_hash() {
  git rev-parse --short HEAD 2> /dev/null | sed "s/(.*)/@1/"
}

Now, I need to determine if there were any changes to the specified directory. But I'm not sure how to go about that. I've looked at and played with git-log and git-show but without success so far.

So, I need to do something like this.

if [directory-changed()] {
  echo "start expensive operation"
}

This actually gets me part way there: Actually it grabs the last commit not the one specified.

git log  -U a79851b -1 my/directory/path

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get the added, modified, deleted and renamed files in the latest commit with:

git diff --name-only --diff-filter=AMDR --cached @~..@

To get the changes affecting a specific directory, filter the output using grep. For example:

changes() {
  git diff --name-only --diff-filter=AMDR --cached @~..@
}

if changes | grep -q dirname {
  echo "start expensive operation"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...