我目前正在处理一个大的遗留项目,它经历了相当多的重构。
你可以猜到,这也意味着大量的删除等。
目前我正在删除一个已经过时的特定功能,所以我想保留与删除该功能相关的更改。当我这样做的时候,我注意到相当多的代码可以被删除,因为它没有被使用(例如未使用的类字段等)。
现在我还不想删除这些东西,因为当我想要提交删除该特性时,我将不得不检查每个类,以保持我的提交集中。所以我使用了一个小小的TODO注释(// @REMOVE
),它标记了不必要的代码,所以我可以在以后删除它。
现在的问题是:是否有可能自动交互式添加来忽略添加的行,只是由这个TODO注释组成,换句话说,匹配一个特定的模式?我知道我可以搜索模式,同时添加交互,但这将是伟大的,如果我不需要手动做它。
提前感谢!
注意我知道Eclipse会标记未使用的字段等,但由于这些字段总是有一个setter并且为注入做了注释(这是一个JSF项目),所以这对我没有帮助。
感谢RomanGotsiy的建议,我能够创建一个bash pre-commit
钩子,它完全符合我的要求。我认为他的回答是正确的,因为他给我指了正确的方向。
#!/bin/sh
#
# This pre-commit hook checks for the specified pattern and removes the matching lines from the index before commiting
# THe lines will still be included in the working tree
pattern="// @REMOVE"
function pre-commit-echo {
echo "PRE-COMMIT: $@"
}
for file in $(git diff --name-only --cached); do
# Skip if the file doesn't exist
[ -e "$file" ] || continue
index_content=$(git show :$file)
if echo "$index_content" | grep "$pattern" > /dev/null; then
pre-commit-echo "Remove lines containing "$pattern" from file "$file""
# Save working tree file content
file_content=$(cat "./$file")
# Remove the lines for the commit
{ echo "$index_content" | grep -v "$pattern"; } > "$file"
git add "$file"
# Reset the file to the old state
echo "$file_content" > "$file"
# Ensure commit isn't empty
if [ -z "$(git diff --name-only --cached)" ]; then
pre-commit-echo "Commit is empty. Abort." 1>&2
exit 1
fi
fi
done
exit 0
你可以使用git-hooks
我已经用python写了一个简单的钩子来解决你的问题。
抓住要点
#!/usr/bin/env python
import sys
import re
import os
import subprocess
OPEN_TAG = r"// @REMOVE"
END_TAG = r"// @"
def git(args):
args = ['git'] + args
git = subprocess.Popen(args, stdout = subprocess.PIPE)
details = git.stdout.read()
details = details.strip()
return details
if __name__ == '__main__':
staged_files = git(["diff", "--name-only", "--cached"])
print
print "PRE-COMMIT HOOK"
print "removing unnecessary code before commit"
for file in staged_files.split("n"):
file_contents = open(file).read()
# remove from file unnecessary code wrapped int OPEN_TAG and END_TAG
cleared_contents, replaces_count = re.subn(r"{}(.*?){}".format(OPEN_TAG, END_TAG), "", file_contents, flags=re.S)
open(file, 'w').write(cleared_contents)
# add cleared file to stage and as result to commit
git(["add", file])
# restore original file
open(file, 'w').write(file_contents)
print(" {}: removed {} chunks".format(file, replaces_count))
print "# done"
print
要启用此钩子,请将以下代码放入"。git/hooks/pre-commit",并允许这个文件执行(Linux上的$ chmod +x pre-commit
)