LoginSignup
15
14

More than 5 years have passed since last update.

覚えた使えるGitトリック _Rebase

Last updated at Posted at 2016-03-29

2016年 初春。
アルコール漬けのチンピラからプログラマに転身した私が覚えたトリックを備忘録兼ねてまとめるTips_ git編


  • git rebase

3回失敗してようやく使えるようになったrebase。
ネットではよく、<歴史を書き換える>とか書いてあるけど、大丈夫。怖くない。
以下 俺の理解していることと使い方。

こんな時に使うイメージ

  1. 今、僕は、masterブランチから切り出したchildブランチ作業をしています。
  2. 三日経ちました。
  3. その間、masterでは時代が進んでいて、そこで開発されているロジックをchildブランチでも使いたいです。
  4. つまり、1の時代のmasterじゃなくて、今のmasterの子供になりたい。私は。 もちろんこの3日間の作業もそこに混ぜたい。
  5. そこでrebase。
  6. rebaseを唱えると、コミットログが下記のような感じになります。

master(childブランチ作った時のコミット) >>> master(3日分のコミット) >>> child(最初のコミット) >>>childe(最先端のコミット)←今ここ

7.これであたかも、現在のmasterから切り出されたchildブランチが最先端のコミットになるの。嬉しい。

使いかた

基本的な使い方は至って簡単。

child_branchに移動して
git rebase master

なんかconflictして失敗するんだけど。

上の例だと、3日も経っているうちに、masterにはいろんなファイルがコミットされていて、その中ではそりゃ同じファイルを更新したりもしている可能性が大いにあります。
すると、こんなエラーが出ちゃう。

child_branch
git rebase master                                                                                                                             

First, rewinding head to replay your work on top of it...
Applying: 画面作成
Applying: 画面項目追加
Using index info to reconstruct a base tree...
A   models/hoge/hoge.rb
Falling back to patching base and 3-way merge...
CONFLICT (modify/delete): models/hoge/hoge.rb
error: Failed to merge in the changes.
Patch failed at 0003 画面項目追加
The copy of the patch that failed is found in: .git/rebase-apply/patch

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

でも大丈夫。
下3行の英文に書いてある通り、conflictを解消して、git rebase --continue すればよろしい。

ここではmodels/hote/hoge.rbが競合してるっぽいので、エディタで競合を解決します。
その後は 必ずgit addした後で、 git rebase --continueを行えばOK
無事に親御さんが代わってくれます。
addするのを忘れてハマりました。

最後に

rebaseを行って、自分のコミットをpushするときは、-fメソッドをつけないとErrorになっちゃいます。
リモートとローカルの時間軸がずれているからです。

つまり、git rebase を行うときは

child_branch

git rebase maseter 

//conflictが起こる場合はconflictを解消した後に

git add . #addして
git push -f origin child //push  -f しましょう

コミットログを変えたものを強制的にリモートにpushするので、チームや複数人で開発している時はメンバーに一言お伺いをたてるとトラブルにならない気がするっていう話。

15
14
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
15
14