测试预提交挂钩中将要提交的内容 [英] Testing what is about to be committed in a pre-commit hook

查看:88
本文介绍了测试预提交挂钩中将要提交的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个问题,Internet上到处都是不正确和不理想的答案.这很不幸,因为您会认为这是您想做的普通事情.

The internet is absolutely littered with incorrect and non-ideal answers to this question. This is unfortunate because you would think this would be a common thing you would want to do.

问题:运行pre-commit挂钩时,存储库可能不干净.因此,如果您天真地运行测试,它们将不会与您提交的内容相抵触,而是会碰到工作树中的任何污垢.

The problem: When a pre-commit hook runs, the repository might not be clean. So if you naively run your tests, they will not be against what you're committing, but whatever dirt happens to be in your working tree.

显而易见的事情是在pre-commit的开始处是git stash --keep-index --include-untracked,在出口处是git pop.这样,您就可以针对我们想要的(纯)索引进行测试.

The obvious thing to do is to git stash --keep-index --include-untracked at the start of the pre-commit and git pop at the exit. That way you are testing against the (pure) index, which is what we want.

不幸的是,如果使用git add --patch,这会生成合并冲突标记(特别是如果编辑块),因为在提交后stash@{0}的内容可能与工作树不匹配.

Unfortunately, this generates merge conflict markers if you use git add --patch, (especially if you edit hunks), since the contents of stash@{0} might not match up against the work tree after commit.

另一种常见的解决方案是克隆存储库并在新的临时存储库中运行测试.有两个问题:一个是我们尚未提交,因此我们无法轻松地以即将提交的状态获取存储库的副本(我敢肯定有一种方法可以做到这一点. ,但我对此不感兴趣,因为:).其次,我的测试可能对当前工作目录的位置敏感.例如,由于本地环境配置.

Another common solution is to clone the repository and run the tests in a new temporary one. There are two issues with that: One is that we haven't committed yet, so we can't easily get a copy of the repository in the state we're about to commit (I'm sure there is a way of doing that, but I'm not interested because:). Secondly, my tests might be sensitive to the location of the current working directory. For example because of local environment configuration.

因此:如何在不引入合并冲突标记且不修改提交后HEAD的情况下,将工作树恢复到git stash --keep-index --include-untracked之前的状态?

So: How can I restore my work-tree to whatever state it was in before the git stash --keep-index --include-untracked, without introducing merge conflict markers, and without modifying the post-commit HEAD?

推荐答案

git write-tree pre-commit挂钩中很有用.它将一棵树写入索引的存储库中(如果最终完成提交,则该树将被重用.)

git write-tree is useful in pre-commit hooks. It writes a tree into the repo of the index (this tree will be reused if and when the commit is finalised.)

将树写入存储库后,可以使用git archive | tar -x将树写入临时目录.

Once the tree is written to the repo, you can use git archive | tar -x to write the tree to a temporary directory.

例如:

#!/bin/bash

TMPDIR=$(mktemp -d)
TREE=$(git write-tree)
git archive $TREE | tar -x -C $TMPDIR

# Run tests in $TMPDIR

RESULT=$?
rm -rf "$TMPDIR"
exit $RESULT

这篇关于测试预提交挂钩中将要提交的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆