[英]How do I copy a version of a single file from one Git branch to another?
我有两个完全合并在一起的分支。
但是,合并完成后,我意识到合并弄乱了一个文件(其他人做了自动格式化,gah),并且在另一个分支中更改为新版本会更容易,并且然后在将它带入我的分支后重新插入我的一行更改。
那么在 Git 中最简单的方法是什么?
从您希望文件结束的分支运行它:
git checkout otherbranch myfile.txt
一般公式:
git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>
一些注释(来自评论):
myfile.txt
和mydir
替代:
git show commit_id:path/to/file > path/to/file
我在类似的搜索中结束了这个问题。 就我而言,我希望将另一个分支中的文件提取到与文件原始位置不同的当前工作目录中。 回答:
git show TREEISH:path/to/file > path/to/local/file
我会使用git restore
(从 Git 2.23 开始可用):
git restore --source otherbranch path/to/myfile.txt
为什么它比其他选择更好?
git checkout otherbranch -- path/to/myfile.txt
- 它将文件复制到工作目录,也复制到暂存区(类似于手动复制此文件并在其上执行git add
)。 git restore
不会触及暂存区(除非通过--staged
选项告诉它)。
git show otherbranch:path/to/myfile.txt > path/to/myfile.txt
使用标准的 shell 重定向。 如果您使用 PowerShell,那么文本编码可能会出现问题,或者如果它是binary ,您可能会得到损坏的文件。 使用git restore
更改文件全部由git
可执行文件完成。
另一个优点是您可以使用以下命令还原整个文件夹:
git restore --source otherbranch path/to
或者使用git restore --overlay --source otherbranch path/to
如果你想避免删除文件。 例如,如果otherbranch
上的文件少于当前工作目录中的文件(并且这些文件被跟踪),而没有--overlay
选项,则git restore
将删除它们。 但是,这是很好的默认行为,您很可能希望目录的状态为“同一个像otherbranch
”,而不是“在同样喜欢otherbranch
但与其他文件从我目前的分支”。
使用结帐命令:
git diff --stat "$branch"
git checkout --merge "$branch" "$file"
git diff --stat "$branch"
确保您在需要文件副本的分支中。
例如:我想要master中的子分支文件,所以你需要checkout或者应该在master git checkout master
现在从子分支中单独检查您想要的特定文件到master ,
git checkout sub_branch file_path/my_file.ext
这里sub_branch
意味着您拥有该文件的位置,后跟您需要复制的文件名。
按照madlep 的回答,您也可以使用目录 blob 从另一个分支复制一个目录。
git checkout other-branch app/**
至于 OP 的问题,如果您只更改了其中的一个文件,这将正常工作。
请注意,在接受的答案,第一个选项阶段,从另一个分支整个文件(如git add ...
已执行),而第二个选项只是导致复制该文件,但没有舞台的变化(就好像您刚刚手动编辑了文件并且存在明显差异)。
更改阶段(例如git add filename)
:
$ git checkout directory/somefile.php feature-B
$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: directory/somefile.php
未完成的更改(未上演或提交):
$ git show feature-B:directory/somefile.php > directory/somefile.php
$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: directory/somefile.php
no changes added to commit (use "git add" and/or "git commit -a")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.