简体   繁体   English

在 git 预提交挂钩中获取未暂存文件的列表

[英]Get the list of unstaged files in git pre-commit hook


I've spent a whole lot of time on stackoverflow/google trying to figure out a solution for this problem.我在 stackoverflow/google 上花了很多时间试图找出解决这个问题的方法。 May be the solution is simple and I am missing something.可能解决方案很简单,我遗漏了一些东西。

So I have a pre-commit hook(shell script) which runs few tests on committed files.所以我有一个预提交挂钩(shell 脚本),它对提交的文件运行一些测试。 If a committed file fails a test, it is removed from the stage.如果提交的文件未通过测试,它将从阶段中删除。 I want to printout all the unstated files from inside the script.我想从脚本中打印出所有未声明的文件。 Here's what I have tried so far from inside the script.到目前为止,这是我在脚本中尝试过的内容。

  1. git diff --name-only --diff-filter=M git diff --name-only --diff-filter=M
  2. git ls-files -m git ls-文件-m
  3. git diff --name-only git diff --name-only

All of them throw the same error as shown below:他们都抛出相同的错误,如下所示:

fatal: This operation must be run in a work tree致命:此操作必须在工作树中运行

PS I am running this inside.git folder(since hooks reside there) and hence the error. PS 我在 inside.git 文件夹中运行(因为挂钩驻留在该文件夹中),因此出现错误。

Any suggestions would be really helpful.任何建议都会很有帮助。

I asked a colleague of mine and he came up with a solution specifically for shell script. 我问了我的一位同事,他想出了一个专门针对shell脚本的解决方案。 Sometimes you just have to think simple! 有时,您只需要简单思考即可!

Just change the directory using " cd " and run the command once you are outside the .git folder. 只需使用“ cd ”更改目录,然后在.git文件夹之外运行命令。

add the following at the top of your script assuming your hook .git/hooks/假设你的钩子.git/hooks/在脚本的顶部添加以下内容

#! /bin/bash
here=`dirname "$0"`
cd "$here/../.."

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM