Git:能够在不接触工作树的情况下暂存特定文件内容

发布于 2024-12-22 01:25:31 字数 41 浏览 4 评论 0原文

我想修改一个(文本)文件的索引,而不必更改工作树文件状态。这可能吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

柳絮泡泡 2024-12-29 01:25:31

“更改索引中的文件而不更改工作目录”的另一种做法是仅对索引应用补丁。这通常是 GUI git 客户端仅暂存给定文件中选定行的方式。

首先(如果需要)清除该文件索引中的更改:

git reset path/to/file

然后提取其完整补丁

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

编辑补丁文件以仅包含您要应用的更改,然后仅应用编辑的补丁:

git apply --cached /path/to/tmpfile

请参阅:

git help apply

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
つ低調成傷 2024-12-29 01:25:31

是的,您可以在任何命令的 git 级别上使用 --work-tree 选项(这实际上不是真的。它应该适用于任何命令,但有边缘情况):

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

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
ぽ尐不点ル 2024-12-29 01:25:31

是的,您可以使用 git update-index 在特定路径显式暂存 blob。

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

如果路径是分支新文件,您还需要使用 --add

如果您要暂存的文件是 git 存储库中尚不存在的 blob,那么您可以使用 git hash-object 在 git 存储库中存储一个新的 blob,例如:

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

或者

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

您可以然后按上面的方法暂存 blob。

git update-index --cacheinfo 100644 blobid path/in/repo

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文