3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[git] mvして更に変更してしまった状態で、mvだけコミットを分ける方法

Last updated at Posted at 2017-06-02

mvした後にうっかりコミットをし忘れてしまうことってありますよね。ここにも書いてあるように、mvした状態で一度renameコミットを作らないとあとで歴史を辿れない場合があります。

ここではmvしたあとに変更してしまった状態で、変更を失わずにrenameのコミットのみ作る方法を紹介します。

前提

$ ls
a
$ git status
On branch master
nothing to commit, working tree clean
$ mv a b
$ ls
b
$ echo "modified" >> b
$ git status
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        deleted:    a

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

        b

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

ファイルabにリネームし、更に変更をしています。

解決策1

$ git add b
$ git stash
$ git status
On branch master
nothing to commit, working tree clean
$ mv a b
$ git commit -m 'rename a to b'
$ git stash list
stash@{0}: WIP on master: 90d4e0c first
$ git checkout stash@{0} .
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   b

こんな感じです。

ちなみに普通にgit stash popしようとすると以下のようなエラーになります。

$ git stash pop
CONFLICT (rename/delete): b deleted in Stashed changes and renamed in Updated upstream. Version Updated upstream of b left in tree.
$ git status
On branch master
Unmerged paths:
  (use "git reset HEAD <file>..." to unstage)
  (use "git add <file>..." to mark resolution)

        added by us:     b

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

また、checkoutするのではなくてrm bした後にgit stash popしてもCONFLICTせずにmergeできます。(こちらの方法のほうがstash履歴が残らずきれいかもですね)

まとめ

  • リネームと変更のコミットを後から分けたければ、
    1. git stash
    2. mv
    3. commit
    4. checkout stash@{0} .

もっと良い方法があればおしえてください。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?