Git はじめました(ステージの取り消し、ファイルの削除と移動、ログの閲覧、コミットのやり直し)

ステージされたファイルの取り消し

git status で確認してみると以下のような状況になっている。これは add されている hello.py をさらに手元で修正しているためである。いったんステージしたファイルを元に戻すには、git reset HEAD を使う。

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#	modified:   hello.py
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#	modified:   hello.py
...
$ git reset HEAD hello.py
Unstaged changes after reset:
M	hello.py
$ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#	modified:   hello.py
...
no changes added to commit (use "git add" and/or "git commit -a")

** ファイルの削除

ファイルを Git から削除するには、git rm <file> でステージされたファイルを削除し、コミットする。このとき、手元のファイルとステージされたファイルに差分があるとエラーになるので、コミットするかもしくは手元のファイルを削除してから実行する
>||
$ rm hello.py
$ git rm hello.py
rm 'hello.py'
$ git commit -m 'delete hello.py'
[master 763004b] delete hello.py
 1 files changed, 0 insertions(+), 1 deletions(-)
 delete mode 100644 hello.py

ファイルの移動

Git には mv コマンドがあり、リポジトリのファイル名を変更できる。

$ git mv README README.txt
oiwatatsuya01@ubuntu101:~/workspace/src/sampleproject$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#	renamed:    README -> README.txt
...

ちなみに、この操作は次のコマンドを実行しているのと同じ意味となる。

$ mv README.txt README
$ git rm README.txt
$ git add README

ログの閲覧

ログの閲覧は git log コマンドを使う。

$ git log
commit 763004b4e1b0d85633a1d03cdafcb04c3339cf16
Author: Tatsuya Oiwa <example@gmail.com>

    delete hello.py
...

commit 78f74b581a1568da78c9adaa959f434bc27ae6aa
Author: Tatsuya Oiwa <example@gmail.com>

    initial project version

format オプションは強力で、独自のログ出力フォーマットを指定することができる。

$ git log --pretty=format:"%h - %an, %ar : %s"
2ad5293 - Tatsuya Oiwa, 10 minutes ago : delete hello.py file
e77894a - Tatsuya Oiwa, 30 minutes ago : second commit
78f74b5 - Tatsuya Oiwa, 48 minutes ago : initial project version

他にもさまざまなオプションが用意されている。詳しくは公式ドキュメントで。

コミットのやり直し

「コミットを早まりすぎて追加すべきファイルを忘れてしまった」ときや「コミットメッセージが変になってしまった」ときなどは、--amend オプションでコミットをやり直せる。

$ git commit -m 'Move README'
$ echo "print 'Hello'" > hello.py
$ git add hello.py
$ git commit --amend -m 'Move README, add hello.py'
[master c3b9852] Move README, add hello.py
 2 files changed, 1 insertions(+), 0 deletions(-)
 rename README => README.txt (100%)
 create mode 100644 hello.py
$ git log
commit c3b985260df108c01a49a936c012c9c4c2d9bcf0
Author: Tatsuya Oiwa <example@gmail.com>

    Move README, add hello.py

commit 763004b4e1b0d85633a1d03cdafcb04c3339cf16
Author: Tatsuya Oiwa <example@gmail.com>

    delete hello.py

Git は基本的にすべての操作を「やり直せる」ようになっている。もし期待と違った動作をしてしまった場合でも落ち着いて対応方法を調べるようにしたい。