【发布时间】: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