交互式添加:不添加具有特定模式的行

时间:2014-07-14 09:57:17

标签: git automation git-add

我目前正在开展一项大型遗留项目,该项目经历了相当多的重构 你可以猜到这也意味着很多删除等等。

目前我已删除已成为obsolet的特定功能,因此我希望保留与删除此功能相关的更改。虽然我这样做,但我注意到一些代码可以删除,因为它没有被使用(例如未使用的类字段等)。

现在我还不想删除这些东西,因为当我想要删除该功能时,我将不得不审查每个类,以保持我的提交集中。所以我使用了一些像评论(// @REMOVE)这样的TODO标记了不必要的代码,以便我可以在以后删除它。

现在出现了一个问题:是否可以自动化交互式添加以忽略仅包含此TODO注释的添加行,换句话说,哪些符合特定模式?我知道我可以在交互式添加的同时搜索模式但如果我不需要手动执行它会很棒。

非常感谢提前!


注意我知道Eclipse例如标记了未使用的字段等,但由于这些字段总是有一个setter并且注释为注入(它是JSF项目),所以这赢了&#39帮助我。


ANSWER

感谢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

1 个答案:

答案 0 :(得分:1)

您可以使用git-hooks

我已经在python上编写了简单的钩子来解决你的问题。

Hook on gist

#!/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

相关问题