Record file copy operation with Git Ask Question

Record file copy operation with Git Ask Question

When I move a file in git using git-mv the status shows that the file has been renamed and even if I alter some portions it still considers to be almost the same thing (which is good because it lets me follow the history of it).

When I copy a file the original file has some history I'd like to associate with the new copy.

I have tried moving the file then trying to re-checkout in the original location - once moved git won't let me checkout the original location.

I have tried doing a filesystem copy and then adding the file - git lists it as a new file.

Is there any way to make git record a file copy operation in a similar way to how it records a file rename/move where the history can be traced back to the original file?

ベストアンサー1

If for some reason (e.g. using gitk) you cannot turn on copy detection as in Jakub Narębski's answer, you can force Git to detect the history of the copied file in three commits:

  • Instead of copying, switch to a new branch and move the file to its new location there.
  • Re-add the original file there.
  • Merge the new branch to the original branch with the no-fast-forward option --no-ff.

Credits to Raymond Chen以下は彼の手順です。ファイルの名前が でOriginalFileName.cpp、複製に という名前を付けたいとしますDuplicateFileName.cpp

fileOriginal=OriginalFileName.cpp
fileDuplicate=DuplicateFileName.cpp
branchName=duplicate-OriginalFileName

echo "$fileOriginal, $fileDuplicate, $branchName" # review of defined names

git checkout -b $branchName # create and switch to branch

git mv $fileOriginal $fileDuplicate # make the duplicate
git commit -m "Duplicate $fileOriginal to $fileDuplicate"

git checkout HEAD~ $fileOriginal # bring back the original
git commit -m "Restore duplicated $fileOriginal"

git checkout - # switch back to source branch
git merge --no-ff $branchName -m "Merge branch $branchName" # merge dup into source branch

これはWindowsでは次のように実行できます。Gitバッシュ


2020-05-19: 上記のソリューションには、元のファイルのログを変更せず、マージの競合を起こさず、短くなるという利点があります。以前のソリューションには 4 つのコミットがありました。

  • コピーする代わりに、新しいブランチに切り替えて動くファイルを新しい場所に移動します。
  • 元のブランチに切り替えて、ファイルの名前を変更します。
  • 新しいブランチを元のブランチにマージし、両方のファイルを保持することで些細な競合を解決します。
  • 別のコミットで元のファイル名を復元します。

(解答はhttps://stackoverflow.com/a/44036771/1389680.

おすすめ記事