Git:stage只添加了一行文件

时间:2017-11-09 09:14:16

标签: git

我正在运行一个从文本文件(代表树)生成代码(字符串常量)的脚本。

运行脚本会删除代码库中其他地方使用的常量。

我想不提交已删除的行(因为它会破坏其他团队代码),而是将这些常量标记为已弃用。

有没有办法在我生成的文件中只添加“添加”行?

我可以用git add -p做到这一点,但由于我有几个文件,有很多变化,这有点单调乏味。

输入差异:

const string Namespace1::kProperty1 = "/namespace_1/property_1";
+ const string Namespace1::kProperty2 = "/namespace_1/property_2";

const string Namespace2::kProperty3 = "/namespace_2/property_3";
- const string Namespace2::kProperty2 = "/namespace_2/property_2";

预期提交差异:

const string Namespace1::kProperty1 = "/namespace_1/property_1";
+ const string Namespace1::kProperty2 = "/namespace_1/property_2";

const string Namespace2::kProperty3 = "/namespace_2/property_3";
const string Namespace2::kProperty2 = "/namespace_2/property_2";

1 个答案:

答案 0 :(得分:2)

没有一个工具可以做到这一点,但有些工具可以协同工作。

  • difflib包含在标准Python库中,并生成比diff命令更容易使用的输出。
  • git cat-file blob ...从Git数据库中检索内容,而不修改工作树。
  • 如果您没有使用像Bash这样的shell来执行<()进程替换,可以使用subprocess将其移动到Python中,或者使用临时文件。
  • git hash-object -t blob -w将对象写回Git数据库。
  • git update-index --cacheinfo 100644,...再次更新索引/阶段,而不会触及工作树。

这应该给git add -p操作提供类似的结果。

git update-index --cacheinfo 100644,$(python -c '
    import difflib, sys;
    sys.stdout.writelines(
        line[2:] for line in difflib.Differ().compare(
            open(sys.argv[1]).readlines(), open(sys.argv[2]).readlines())
        if line.startswith("  ") or line.startswith("+ "))' \
    <(git cat-file blob HEAD:filename) filename \
| git hash-object -t blob -w --stdin --path filename),filename
相关问题