繁体   English   中英

Git使用Intellij Idea预提交钩子行为

[英]Git pre-commit hook behavior with Intellij Idea

我有一个带有预提交git钩子的monorepo项目,该钩子会破坏package.json文件中的版本。 该挂钩使用以下脚本:

#!/usr/bin/env bash

set -e

# See if git detects any changes for the given directory
if [[ -z `git diff --cached --shortstat ./packages/$1` ]]; then
    VERSION=`node -p -e "require('./packages/$1/package.json').version"`
    echo "$1 has not changed, old version: $VERSION"
    exit 0
fi

VERSION=$(cd packages/$1 && npm version patch --no-git-tag-version)
# Add package.json to staged
git add packages/$1/package.json > /dev/null
echo "$1 has changed, new version: ${VERSION//v}"

我在backend包中更改了一个文件tsconfig.json ,并通过Idea UI提交了该文件,并选中了“运行git hooks选项”。 我仅在UI对话框中的文件上检查此内容,但是该钩子还应该增加package.json。 在Idea版本控制台中,我看到以下日志出现:

14:28:08.610: [myproject] git -c core.quotepath=false -c log.showSignature=false commit --only -F /private/var/folders/rf/mnfmp6xs2zjb50x0nqfrlftw0000gn/T/git-commit-msg-.txt -- packages/backend/tsconfig.json
[master c5ec828] Hooks test 24
 2 files changed, 2 insertions(+), 2 deletions(-)

运行git log -1 --stat表示package.json被钩子更改并被提交:

git log -1 --stat
commit c5ec8289afa8f15d7134b362992d4a91e31bda16 (HEAD -> master)
Author: doomsower <mail@gmail.com>
Date:   Tue Feb 13 14:28:08 2018 +0300

    Hooks test 24

 packages/backend/package.json  | 2 +-
 packages/backend/tsconfig.json | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

packages/backend/package.json版本被钩子撞了,是正确的。 但是,当我运行git status我看到以下内容:

On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   packages/backend/package.json

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   packages/backend/package.json

然后我运行git add packages/backend/package.json ,然后返回git status

On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

我不太了解这是怎么回事:

1)根据日志,Idea使用--only标志运行了git commit ,并且未在命令行中指定package.json ,但已git commit 这怎么可能?

2)好的,因此提交了2个文件,并且package.json版本号被修改。 在那个git工作树不干净之后,我怎么可能运行git add使其变得干净?

因此,我认为这是上述情况下事件的时间表:
1.您更改tsconfig.json并将其添加到git索引
2.然后,提交仅包含tsconfig.json的索引。 在提交运行之前,您的钩子将修改并将package.json添加到索引中。
3.然后提交索引,仅指定提交tsconfig.json 通常,这将使package.json处于暂存状态,但是(并且,为了全面披露,我在这里进行了有根据的猜测),因为它是添加到钩子中的,git已经对文件进行了一些提交处理
4.这样,您将提交新的package.json ,索引中的旧package.json和文件系统上的新package.json 因此,将其添加回索引将取消更改,因为它现在与提交的历史记录匹配-提供了干净的存储库。

解决此问题的方法是从预提交中删除添加,然后在提交后挂钩中运行提交,如下所示:
git add package.json
git commit --amend -C HEAD --no-verify
使用--no-verify防止钩子无限循环

暂无
暂无

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

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