在Git中提交之前临时清除未跟踪的文件

Ash*_*Ash 5 git testing commit pre-commit

每当我提交时,我担心我可能会错过依赖关系,并且我正在寻找最简单的方法来隔离测试git树,以确保git索引(“暂存”)中的内容实际上可以编译/运行他们自己的。

我的代码依赖关系存在于我执行“ git add”的文件系统中,因此简单的编译和运行测试无法保证如果将树(或暂存区)检出到干净的文件系统上,则我签入的内容不会编译/运行。

我可以有一个连续的构建,可以在提交后进行检查,但是我不希望在以后不得不修补的历史记录中没有任何错误的提交。因此,我想要一种创建隔离环境的方法,该环境包括树的检出以及索引/临时区域。

我考虑过的一件事是两次使用git stash,即:

  1. 调用“ git stash”将文件保存在索引中
  2. 以某种方式获取未跟踪文件的列表,“ git add”所有这些文件,保存新的存储
  3. 删除所有以前未跟踪的文件
  4. 恢复原始存储
  5. 现在,我应该拥有一个干净的环境,该环境只有已签入的代码以及可以编译和测试的登台区域中的代码。
  6. 完成后,我将还原未跟踪文件的存储,然后对其进行取消跟踪,以使我保持原先的位置。

(这些未跟踪的文件可能有用,但不一定要我检查到存储库中的内容-例如eclipse项目)。

不过,我有一种过度设计一个简单问题的感觉。

bst*_*rre 3

安装这个脚本(或者类似的东西——我的也被盗了)作为预提交钩子。它将索引复制到临时工作目录并在那里运行构建。它会捕获您错过的文件。

我知道至少还有一两个其他问题可以解决这个确切的问题——测试/验证索引而不是预提交挂钩中的工作目录——但我现在似乎找不到它们。

(为了完整起见,我在我的存储库中将此脚本作为 .git-hooks/pre-commit/test-the-index ;那里还有几个其他脚本。请参阅下面我使用的 .git/挂钩/预提交。)

#!/bin/sh
#
# Via: http://github.com/jwiegley/git-scripts/blob/master/pre-commit.sh
#

if [ ! $(git rev-parse --symbolic-full-name HEAD) = refs/heads/master ]; then
    exit 0
fi

# These are the locations I keep my temporary source and build trees in
TMPDIR=$HOME/code/myproject-pre-commit
MIRROR=$HOME/code/myproject-pre-commit-mirror

# Exit with status 1 if any command below fails
set -e

# Checkout a copy of the current index into MIRROR
git checkout-index --prefix=$MIRROR/ -af

# Remove files from MIRROR which are no longer present in the index
git diff-index --cached --name-only --diff-filter=D -z HEAD | \
    (cd $MIRROR && xargs -0 rm -f --)

# Copy only _changed files_ from MIRROR to TMPDIR, without copying timestamps.
# This includes copying over new files, and deleting removed ones.  This way,
# "make check" will only rebuild what is necessary to validate the commit.
rsync -rlpgoDOc --delete --exclude-from=.git-hooks/excludes $MIRROR/ $TMPDIR/

# Everything else happens in the temporary build tree
cd $TMPDIR

nosetests

exit 0
Run Code Online (Sandbox Code Playgroud)

这是我实际的 .git/hooks/pre-commit:

#!/bin/bash

set -e
for hook in $(find .git-hooks/pre-commit -perm /u+x,g+x,o+x -type f -not -name '*~' 2>/dev/null)
do
  echo "@@ Running hook: $(basename $hook)"
  $hook "$@"
done
Run Code Online (Sandbox Code Playgroud)