2021年8月31日

何?もう8月終わりなの?

ながらくsvnを使っていたので、どうしてもci, stといったコマンドを使いたがっていたが、ちゃんとcommit、statusを入力するようにした。さらに、checkoutのかわりにswitchを使うように練習中。学生さんに変な癖つけるわけにはいかないしね。

Git 内部探訪。git init 直後は、.git/HEADは`

ref: refs/heads/main

とmain(master)ブランチを指している。しかし、init直後は.git/refs/headsは空っぽ。この状態でgit logを叩くと、

$ git log 
fatal: your current branch 'main' does not have any commits yet

つまり、「HEADが指すブランチが存在しなければ、コミットが無い」と判断する。また、この時点ではindexも存在しない。

git addするとindexが作られる。

git commitしてはじめて.git/refs/heads/mainが作成される。

さて、git logが「歴史があるかどうか」は「対応するブランチに対応するファイルがあるかどうか」で判断しているので、それを削除すれば歴史が無いと判断する。

git switch -c hoge

これで.git/refs/heads/hogeが作られ、.git/HEADがそこを指す。

ここで、hogeブランチファイルの名前を変えてしまおう。

mv .git/refs/heads/hoge .git/refs/heads/hoge.org 

これで、HEADは.git/refs/heads/hogeを指しているが、そのファイルは存在しない、という状態になった。この状態でgit logを叩くと、

$ git log
fatal: your current branch 'hoge' does not have any commits yet

と「歴史が無いよ」と言われる。しかし、.git/indexは存在するので、git diffは使える。

$ echo "hogehoge" >> hello.txt
$ git diff
diff --git a/hello.txt b/hello.txt
index e965047..0e05194 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1,2 @@
 Hello
+hogehoge

indexも消してしまおう。

rm .git/index

これはgit init直後の状態となるので、git diffが何も表示しなくなり、git statushello.txtをUntracked filesと認識する。

$ git diff
$ git status
On branch hoge

No commits yet

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

nothing added to commit but untracked files present (use "git add" to track)

なるほどね。