これは何?
自分がgitであれをやりたい...と思ってググったコマンド一覧を備忘録として残した記事
ブランチ操作
今のブランチをmainに追従させる
$ git rebase -i origin/main
手元のブランチのHEAD, index, ワーキングツリーをremoteの状態で上書きする(手元のブランチの状態をリモートと同じ状態に戻す)
$ git reset --hard origin/main
コミット
直前のコミットに変更を追加する
$ git commit --amend --no-edit
1つ前のコミットに、特定の変更を追加できる。
add している状態で実行すれば、addされているものが追加されるし、
$ git commit --amend --no-edit <file>
とすれば、 を追加できる。
PR作成前の見直しで少しだけ修正が出てきた場合などに、知ってからはとてもよく使っている。
fixup!コメント付きでコミットする
$ git commit --fixup=@
このコマンドを実行すると、addしたものがfixup!
コメント付けでコミットされる。
この状態で git rebase -i origin/main
などを実行すると、最初から fixup 対象として扱われるので、fixupしたいコミットの次に並び替えるなどをしてfixupが実行できる。
用途としては、
- 直前のコミットに組み込みたい場合
git commit --amend --no-edit
- それ以前のコミットに組み込みたい場合
git commit --fixup=@
した後に git rebase -i origin/main
として使う。
コミットの修正
コミットした順序を入れ替える
$ git rebase -i @~5
並び替えて :wq
複数のコミットメッセージをまとめて修正する
$ git rebase -i @~5
編集したいコミットのpickをrにして:wq
個別に修正する
過去のコミットを分割する その1
分割したいcommitのidを <commit_id>
とする
$ git rebase -i <commit_id>~
edit <commit_id>
にして :wq
で、修正対象のコミットまでHEADを戻す。
この時点では、作業ディレクトリは差分無しの状態だが、
$ git reset @~
をすると、分割したいコミットの差分対象のファイルがunstagingな状態に戻るので、個別にaddやcommitする。
分割コミットが終わったら
$ git rebase --continue
で完了。
過去のコミットを分割する その2
下記コマンドなどで分割したい対象のコミットを e
して :wq
。
$ git rebase -i origin/main
すると、分割対象のコミットまでHEADが戻る。
この時点では、作業ディレクトリは差分無しの状態だが、
$ git reset @~
をすると、分割したいコミットの差分対象のファイルがunstagingな状態に戻るので、個別にaddやcommitする。
分割コミットが終わったら
$ git rebase --continue
で完了。
今のブランチのコミットをすべてコミットし直す
プルリクエストを作る際などに、コミットを綺麗に作り直したいケース。
コミットし直したいブランチをfeatureブランチとする。
まずmainブランチとの差分をすべてreset --softする
$ git reset --soft origin/main
すると、以下のようにfeatureブランチで加えたファイル差分がstageに上がったものの未コミットの状態に戻る。
一度すべてunstageに戻す。
$ git status
On branch feature
Your branch is behind 'origin/feature' by 4 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: ...
modified: ...
modified: ...
modified: ...
$ git restore --staged ./
すべてのファイルをunstageな状態に戻せば、そのブランチで行われたファイル差分はあるもののコミットはされていない状態に戻るので、改めて好きな粒度でコミットをしていけばOK.
$ git status
On branch feature
Your branch is behind 'origin/feature' by 4 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
new file: ...
modified: ...
modified: ...
modified: ...
$ git commit --message "..."
すべてコミットし直せたら、force pushする
$ git push --force
マージ
別ブランチのコミットの(無編集での)取り込み
dependabotのPRをまとめて取り込みたい時などに使う。
git merge --no-edit origin/branch-name
設定変更
単語単位でdiffを表示する
通常は行単位でしかdiffが表示されないが、単語単位でdiffを表示するには、.gitconfigにこう書く。
[pager]
log = diff-highlight | less
show = diff-highlight | less
diff = diff-highlight | less
lessのようにpager無しで標準出力したい場合には、 | less
を外せばよい
git/contrib/diff-highlight at master · git/git · GitHub
.gitconfigにこう書く。
[pager]
branch = false