【问题标题】:Git commit with pre-commit hook, why it get different results?带有预提交钩子的 Git 提交,为什么会得到不同的结果?
【发布时间】:2021-04-21 20:15:03
【问题描述】:

我有一个预提交挂钩来运行一个 python 脚本,该脚本将修改暂存文件并在脚本末尾使用 git add . 重新添加这些文件。

预提交如下所示:

#!/bin/sh
python2.7 .git/hooks/editfile.py

python 脚本如下所示:

import os
import mmap
import sys
import subprocess

def getmodifiedfiles():
  files = []
  args = ['git', 'diff', 'HEAD', '--name-only', '-r', '--diff-filter=M']
  with open(os.devnull, 'w') as b:
     files = subprocess.check_output(args, stderr=b).splitlines()

  files = [i for i in files if os.path.isfile(i)]
  return files

def updaterevision(line):
    strVer = line.split("$Revision: ")[1].split()[0]
    version = [x for x in strVer.split('.')]
    ver = [int(i) for i in version]

    if ver[1] == 99:
      ver[0] += 1
      ver[1] = 0
    else:
      ver[1] += 1

    strVer = "%d.%02d" % (ver[0], ver[1])
    return str.replace(line, line.split("$Revision: ")[1].split()[0], strVer)

def main(args):
  filelist = getmodifiedfiles()  
  
  for file in filelist :
    lines = open(file).readlines()

    i = 0
    for line in lines:
        if '$Revision:' in line:
          lines[idx] = updaterevision(line)
        
        i += 1

  with open(file, 'w') as r:
    r.writelines(lines)          

  args = ['git', 'add', '.']
  subprocess.call(args)
  
if __name__ == '__main__':
    main(sys.argv)

git commit -m "msg" 命令按预期工作,当 git status 我得到以下结果:

On branch master
Your branch is ahead of 'origin/master' by 1 commit.

nothing to commit (working directory clean)

但如果使用git commit <filename>git commit -m "msg" <filename> 提交,我会得到以下我不想要的结果:

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

   modified:   filename.py

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:   filename.py

有什么不同?我不想让用户只使用第一个命令来提交。有什么想法吗?

【问题讨论】:

  • 你能提供你的钩子脚本吗?这很重要。
  • 脱离@iBug 所说的,你能提供完整的脚本吗?
  • 我很犹豫是否将其作为副本关闭,但请参阅this question

标签: git git-commit pre-commit-hook


【解决方案1】:

不幸的是,使用你的文件重写预提交钩子,你唯一能做的就是远离git commit &lt;files...&gt;,只使用git-add-then-git-commit

也就是说,你并没有完全失去希望。由于您的钩子脚本旨在重写文件(设置“版本信息”),因此使用过滤器是一个更好的主意。

查看这个答案:https://stackoverflow.com/a/17360528/5958455

基本上,您将脚本设置为“干净过滤器”,以便在匹配文件暂存时应用它。幸运的是,包括您的 git commit &lt;file...&gt; 用例。

【讨论】:

  • 我试过 git config --global filter.updateHeader.clean editfile.py,然后我得到这个错误:cannot fork to run external filter 'editfile.py' and external filter 'editfile.py' failed .我应该把editfile.py放在哪里?
  • @hexacool 路径应该相对于“项目根目录”,即.git 目录所在的位置。如果不确定,请使用绝对路径。
  • 我将脚本文件放在项目根目录下它不起作用。尝试绝对路径,它显示致命:无法执行:/home/username/projectname/editfile.py':运行脚本时权限被拒绝。
  • @hexacool 显然你忘了chmod 755 或类似的。
猜你喜欢
  • 2013-12-15
  • 2019-02-15
  • 1970-01-01
  • 2021-03-01
  • 2019-07-12
  • 2015-01-13
  • 2018-05-21
  • 1970-01-01
相关资源
最近更新 更多