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

时间:2018-02-13 11:58:32

标签: git shell intellij-idea githooks

我有一个带有pre-commit git hook的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}"

我在tsconfig.json包中更改了一个文件backend并通过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被hook更改并被提交:

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使用git commit标志运行--only并且未在命令行中指定package.json,但它已被提交。怎么可能?

2)好了,所以提交了2个文件,并提交了package.json版本号。怎么可能在那个git工作树不干净之后我必须运行git add才能让它干净?

1 个答案:

答案 0 :(得分:1)

所以我认为这是上述情况下事件的时间表:
 1.您更改tsconfig.json并将其添加到git索引
 2.然后,您提交仅具有tsconfig.json的索引。在提交运行之前,您的钩子会修改并将package.json添加到索引中  3.然后提交索引,仅指定提交tsconfig.json。通常情况下,这会让package.json处于暂停状态,但(并且完全披露,我在这里采取了有根据的猜测),因为它已添加到钩子git已经圆顶一些提交处理到文件。
4.这将为您提供新的package.json已提交,索引中的旧package.json以及文件系统上的新git add package.json。因此将其添加回索引取消更改,因为它现在匹配已提交的历史记录 - 提供一个干净的回购。

对此的修复是从预提交中删除添加,并在提交后挂钩中运行提交,如下所示:
git commit --amend -C HEAD --no-verify
--no-verify
使用for (i in 1:n){ Oi <- diag(,n)[,i] } 来防止无限循环的挂钩

相关问题