Git: ability to stage a certain file content witho

2019-05-11 02:11发布

I want to modify the index of one (text) file without having to change the working tree file state. Is this possible?

标签: git stage
3条回答
beautiful°
2楼-- · 2019-05-11 02:59

yes, you can use the --work-tree option on the git level of any (this is not actually true. It should work on any but there are edge cases) command:

git show HEAD:path/to/your/file.txt > /some/other/place/file.txt
# modify the file in /some/other/place/file.txt
git --work-tree=/some/other/place add /some/other/place/file.txt
查看更多
做自己的国王
3楼-- · 2019-05-11 03:06

Yes, you can explicitly stage a blob at a particular path with git update-index.

git update-index --cacheinfo 100644 <sha1-of-blob> path/in/repo

You will also need to use --add if the path is a branch new file.

If the file that you want to stage is a blob that doesn't yet exist in the git repository then you can store a new blob in the git repository with git hash-object, e.g.:

blobid=$(command_that_creates_output | git hash-object -w --stdin)

or

blobid=$(git hash-object -w /path/not/necessarily/in/repository)

You can then stage the blob as above.

git update-index --cacheinfo 100644 blobid path/in/repo
查看更多
叼着烟拽天下
4楼-- · 2019-05-11 03:07

Another take on "changing file in index without altering working dir" is to apply a patch to index only. This is often the way GUI git clients stage only selected lines from a given file.

You start out by (if you want) clearing out the changes from index for that file:

git reset path/to/file

Then extracting the full patch for it

git diff path/to/file > /path/to/tmpfile

Edit the patch file to include only the changes you want to apply, and apply just the edited patch:

git apply --cached /path/to/tmpfile

See:

git help apply
查看更多
登录 后发表回答