はじめに

Gitで ファイルを移動したときに、特に何もせずにファイルを移動すると、
削除して新規ファイルとして作成したと認識されてしまうときがあった。
それを解決するできるらしい、git mv を実際に使用してみる。

環境

1
2
3
Windows 10 Professional
WSL2 (Ubuntu 22.04 LTS)
git version 2.34.1

実際に使ってみる

準備

適当なディレクトリを作成し、 index.php というファイルを作成してみる。 中身は、以下のような感じ

1
2
<?php
echo "Hello,World";

これを保存し、 git add, git commit でコミットまで実行する。

mvの場合

では、このブランチから作業ブランチを作成する。
git switch -c work-use-mvとして、切り替える。

新しくディレクトリを作成する。 (testフォルダ) そして、 mv コマンドで、 index.phptest/index2.php としてみる。

1
- test - index2.php

というような階層になる。

git statusを実行すると、

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
On branch work-use-mv
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        deleted:    index.php

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        test/

no changes added to commit (use "git add" and/or "git commit -a")

削除したファイルと新規作成したファイルという扱いになる。 さて、これを解消したい。 (※git add ., git commit でコミットまでしておく。)

git showをすると

1
2
3
4
5
6
7
8
Date:   Fri Jun 2 19:07:50 2023 +0900

    mv

diff --git a/index.php b/test/index2.php
similarity index 100%
rename from index.php
rename to test/index2.php

こちらはリネーム扱いになっているようだ。
類似度100%と書いている。

履歴を確認してみる

1
git log --summary --follow test/index2.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
commit 9d4babaf52e3ca36fea0151d10684869ddfa436c (HEAD -> work-use-mv)
Date:   Fri Jun 2 19:07:50 2023 +0900

    mv

 rename index.php => test/index2.php (100%)

commit 8ae58d6d4106f4b98715657013e3eef568375e4c (master)
Date:   Fri Jun 2 18:59:01 2023 +0900

    Initialize

 create mode 100644 index.php

git mvをする

一旦、 git switch masterをし、同じことを新しく作成する作業ブランチでも実施する。
git switch -c work-git-mvで作業ブランチに切り替える。

git statusを見てみると、

1
2
3
4
On branch work-git-mv
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        renamed:    index.php -> test/index2.php

今度は、リネームされた扱いになっているようだ。
(※git add ., git commit でコミットまでしておく。)

git show

1
2
3
4
5
6
7
8
9
Author: horiba <horiba@DESKTOP-M2SDB0M>
Date:   Fri Jun 2 19:14:42 2023 +0900

    gitmv

diff --git a/index.php b/test/index2.php
similarity index 100%
rename from index.php
rename to test/index2.php

リネームとなっている。

履歴を確認してみる。

1
git log --summary --follow test/index2.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
commit 5903d98677ed201d2349b6edffaa5e06d2e2b263 (HEAD -> work-git-mv)

Date:   Fri Jun 2 19:14:42 2023 +0900

    gitmv

 rename index.php => test/index2.php (100%)

commit 8ae58d6d4106f4b98715657013e3eef568375e4c (master)

Date:   Fri Jun 2 18:59:01 2023 +0900

    Initialize

 create mode 100644 index.php

良さそう。

参考

おわりに

mvでもリネーム扱いになっていることに驚き。
以前、プロジェクトの階層をまるごと下げたときはだめだったので、なにか問題があったのかな。
リネームとして検出できないときは、git mvを使ってみるのが良さそうだ。