iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙄

When you want to return to a branch two steps ago

に公開6

The Problem

During my daily work, there were times when I wanted to go back to the branch I was working on two steps ago. For example:

  1. New development on branch A
  2. Find a bug
  3. Move to branch B and bring it up to date
  4. Create branch C for bug fixing from branch B
  5. Complete the bug fix
  6. Want to go back to branch A!

...is the kind of situation I mean.

What I Was Doing

I used to take the following measures:

  • Create a draft PR at the point of branch A. Then, when I want to go back, copy and paste the branch name from the GitHub PR page.
  • Search back through the terminal history.
  • Check three entries back with reflog.

I was using such tedious methods because I can't remember branch names...

As a Solution

  • To solve this problem, I created my own CLI tool.
  • It's a command that allows you to return to the branch you were on three steps ago by typing goback 3.
  • You can also check the history of branches you've moved through with goback -l.
    goback -l

https://github.com/siki-712/goback

Finally

  • Actually, if there is another easy way to go back two branches, please let me know...! Other than using a GUI.

Discussion

rakiraki

コードはちゃんと見てないのでアレですけど、たぶん欲しいのはこういうのかなと。

git name-rev --name-only --exclude=refs/tags/\* @{-3}

なので

git config alias.goback '!git checkout $(git name-rev --name-only --exclude=refs/tags/\* @{-${1:-1}}) #' 

のように書いておくと

git goback 3

で期待どおりの動きになるんじゃないかと思います。
(普段ブランチ移動するような作業してないので軽くしかテストしてないですけど。。。)

ちなみに参考にしたのはこれです。-l の動きはこの last で実現できるかと
https://stackoverflow.com/questions/64521588/git-get-history-of-branches-that-i-was-in

sikisiki

ありがとうございます!エイリアス作戦も考えたのですが、なんか折角ならCLIツールにしてしまえ〜と思って作りました!4つも5つも前にいたブランチには戻りたいな〜とか思わないので、本来ここまでする必要ないのですが

Yoichi NakayamaYoichi Nakayama

いくつ前かわかっててcheckoutするだけなら git checkout @{-2} でできると思います。
作られたツールで一覧を確認できるのは便利そうですね。

sikisiki

git checkout @{-2}

ありがとうございます!これで私の願いは叶えられそうですね! git switch - しか知らず、git switch -- こうしたいのに...と思ってました

一覧を確認できるのは便利そうですね。

自分で作っといてなんですが、使いどころかなり少なそうです😀

sikisiki

ちなみに - は @{-1} と同じ意味合いになってます。

記事拝見しました!勉強になりました!ありがとうございました!