diff --git a/pkg/commands/git_commands/branch.go b/pkg/commands/git_commands/branch.go index f4c491d63..76b5727c7 100644 --- a/pkg/commands/git_commands/branch.go +++ b/pkg/commands/git_commands/branch.go @@ -116,6 +116,22 @@ func (self *BranchCommands) CurrentBranchName() (string, error) { return strings.TrimSpace(output), nil } +// Gets the full ref name of the previously checked out branch. Can return an empty string (but no +// error) e.g. when the previously checked out thing was a detached head. +func (self *BranchCommands) PreviousRef() (string, error) { + cmdArgs := NewGitCmd("rev-parse"). + Arg("--symbolic-full-name"). + Arg("@{-1}"). + ToArgv() + + output, err := self.cmd.New(cmdArgs).DontLog().RunWithOutput() + if err != nil { + return "", err + } + + return strings.TrimSpace(output), nil +} + // LocalDelete delete branch locally func (self *BranchCommands) LocalDelete(branches []string, force bool) error { cmdArgs := NewGitCmd("branch"). diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index ed2b01509..1fdc75652 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -490,7 +490,7 @@ func (self *BranchesController) forceCheckout() error { func (self *BranchesController) checkoutPreviousBranch() error { self.c.LogAction(self.c.Tr.Actions.CheckoutBranch) - return self.c.Helpers().Refs.CheckoutRef("-", types.CheckoutRefOptions{}) + return self.c.Helpers().Refs.CheckoutPreviousRef() } func (self *BranchesController) checkoutByName() error { diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index d5140bb1e..cfb9d3bab 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -163,6 +163,15 @@ func (self *RefsHelper) CheckoutRemoteBranch(fullBranchName string, localBranchN }) } +func (self *RefsHelper) CheckoutPreviousRef() error { + previousRef, err := self.c.Git().Branch.PreviousRef() + if err == nil && strings.HasPrefix(previousRef, "refs/heads/") { + return self.CheckoutRef(strings.TrimPrefix(previousRef, "refs/heads/"), types.CheckoutRefOptions{}) + } + + return self.CheckoutRef("-", types.CheckoutRefOptions{}) +} + func (self *RefsHelper) GetCheckedOutRef() *models.Branch { if len(self.c.Model().Branches) == 0 { return nil