簡體   English   中英

如何將單個文件的版本從一個 Git 分支復制到另一個?

[英]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.txtmydir
  • 通配符不起作用,但相對路徑起作用
  • 可以指定多個路徑

替代:

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"
  1. 確保您在需要文件副本的分支中。

    例如:我想要master中的子分支文件,所以你需要checkout或者應該在master git checkout master

  2. 現在從子分支中單獨檢查您想要的特定文件到master

     git checkout sub_branch file_path/my_file.ext

    這里sub_branch意味着您擁有該文件的位置,后跟您需要復制的文件名。

按照madlep 的回答,您也可以使用目錄 blob 從另一個分支復制一個目錄。

git checkout other-branch app/**

至於 OP 的問題,如果您只更改了其中的一個文件,這將正常工作。

請注意,在接受的答案,第一個選項階段,從另一個分支整個文件(如git add ...已執行),而第二個選項只是導致復制該文件,但沒有舞台的變化(就好像您剛剛手動編輯了文件並且存在明顯差異)。

Git從另一個分支復制文件而不暫存

更改階段(例如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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM