LoginSignup
1
2

More than 5 years have passed since last update.

Gitの歴史修正、first commitすら書き換える

Posted at

最初のコミットと最後のコミットのみにする

Gitのコミット履歴を書き換えるには、git rebaseを使います。

ここで、最初のコミット以外、すべて無かったことにしてみます。

具体的には、以下の様なコマンドで完了します。

$ pwd [repo] #現在のディレクトリを分かりやすいように表示しています
reponame

# まずクローンを作り、最新の.gitを手に入れる
$ git clone https://git-host-site/user/repo.git repo.back [repo]

# 念のため.gitのバックアップを保存
$ mv .git ../.git.back [repo]

# 最新のリポジトリで歴史修正を行う
$ cd repo.back [repo]
$ git rebase -i --root [repo.back]
pick first commit #これ以外すべて削除
pick secound commit
pick 3
pick 4

# 保存すると、ファイルが最初のコミットの状態に戻る
# そこで、この.gitを手に入れる
$ mv .git ../ [repo.back]

$ cd ../ [repo]
$ git add -A
$ git commit -m "rebase"
$ git push -f

これで、リポジトリは、最初のコミットと最後のコミットのみになります。

最新のコミットのみにする

git rebase -iで編集出来る内容は、以下のようになっています。ここでは、コミットをまとめるsquashを使って最初のコミットを最新のコミットにしてみます。

#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell

上の状態にした後、つまり、最初と最後のコミットのみの状態にした後、squashを使います。

$ git rebase -i --root
pick first commit
pick rebase

#これを以下のようにして保存します。その後も内容が良ければ編集せずに終了します
pick first commit
squash rebase

#後はpushするだけです
$ git push -f

他にもシンプルな方法があれば教えて下さい。

参考

Git のさまざまなツール - 歴史の書き換え

1
2
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
1
2