如何使用git仅仅部署一个新文件?

喜欢 git add –interactive 。 这是我日常工作stream程的一部分。

这个问题似乎不适用于未跟踪的文件。 我想要做的是跟踪一个新的文件,但只添加它的一部分,即这个新文件的一些部分尚未准备好上演。

例如,使用git add -i,我可以select修补程序选项,甚至编辑个别的区块,以便部署新的代码,而不需要debugging代码注释。 我喜欢这种方式工作,因为它明确了我目前正在进行的大型补丁的哪些地方仍然需要工作。

不幸的是,我似乎没有能够对未跟踪的文件做同样的事情。 要么我整个文件,或什么都没有。 我已经使用的解决方法是暂存,甚至提交一个新的文件,当它是空的,然后按照通常的方式分阶段进行更改。 但是这个解决scheme感觉像是一个肮脏的黑客,当我忘记了,或者改变了我的想法时,它就会造成比应该更多的麻烦。

所以问题是:如何仅阶段部分的新文件,以便这个新的文件被跟踪,但留下整个或部分的内容不分离?

哇,所有update-indexhash-object业务似乎过于复杂。 如何呢,而不是:

 git add -N new_file git add -i 

git help add

 -N, --intent-to-add Record only the fact that the path will be added later. An entry for the path is placed in the index with no content. This is useful for, among other things, showing the unstaged content of such files with git diff and committing them with git commit -a. 
 git update-index --add --cacheinfo 100644 $(git hash-object -w /dev/null) newfile git add --interactive newfile 

简单演示:

 mkdir /tmp/demo cd /tmp/demo git init . echo hello > newfile git update-index --add --cacheinfo 100644 $(git hash-object -w /dev/null) newfile 
  • 提示如果你确定你的git对象数据库中已经存在'空'blob,你可以改为硬编码e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 我不build议这样做
  • 提示如果你在Windows上,你可能只需要使用NUL:而不是/dev/null 否则,使用类似echo -n '' | git hash-object --stdin -w echo -n '' | git hash-object --stdin -w

现在,索引将包含newfile作为空blob,如果它尚不存在,则已将空blobinput到对象数据库中:

 $ find .git/objects/ -type f .git/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 $ git status # On branch master # # Initial commit # # Changes to be committed: # (use "git rm --cached <file>..." to unstage) # # new file: newfile # # Changed but not updated: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # modified: newfile # $ git diff diff --git a/newfile b/newfile index e69de29..ce01362 100644 --- a/newfile +++ b/newfile @@ -0,0 +1 @@ +hello 

这应该正是你想要的。 我也可以推荐vim fugitive插件进行非常智能的索引pipe理(请参阅Better git add -p? )

最简单的方法就是git gui 。 它与git捆绑在一起,应该可以在几乎所有git支持的平台上运行。

只要运行git gui ,就会打开一个gui,允许登台和暂停,甚至是单行跟踪和未跟踪的文件。

Git Gui截图

编辑:这似乎并没有工作。 我确定这是之前(在git 1.7.1)。 如果它不起作用,我build议按照上面所示build议/dev/null

 git update-index --add --cacheinfo 100644 $(git hash-object -w /dev/null) newfile 

如果你在Windows上(没有/dev/null ),那么你可以将它replace为一个空文件的path。

原始答案

你要

 git add -p # (or --patch) 

这为我添加了未跟踪的文件。 从手册页:

在索引和工作树之间交互select补丁块,并将其添加到索引。 这使用户有机会在将修改的内容添加到索引之前查看差异。

这有效地运行了添加交互,但绕过了初始命令菜单,并直接跳转到patch子命令。 有关详情,请参阅“交互模式”。