1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-04-25 12:24:47 +02:00

fix: fix ambiguous branch name

test: add an integration test for checkout branch by name

fix: fix full ref name of detached head

refactor: refactor current branch loader

chore: use field name explicitly
This commit is contained in:
Ryooooooga 2022-10-16 21:31:42 +09:00 committed by Jesse Duffield
parent b33ec5a050
commit 52a2e4c1dc
39 changed files with 150 additions and 43 deletions

View File

@ -119,9 +119,9 @@ func NewGitCommandAux(
patchCommands := git_commands.NewPatchCommands(gitCommon, rebaseCommands, commitCommands, statusCommands, stashCommands, patchManager) patchCommands := git_commands.NewPatchCommands(gitCommon, rebaseCommands, commitCommands, statusCommands, stashCommands, patchManager)
bisectCommands := git_commands.NewBisectCommands(gitCommon) bisectCommands := git_commands.NewBisectCommands(gitCommon)
branchLoader := git_commands.NewBranchLoader(cmn, branchCommands.GetRawBranches, branchCommands.CurrentBranchName, configCommands) branchLoader := git_commands.NewBranchLoader(cmn, branchCommands.GetRawBranches, branchCommands.CurrentBranchInfo, configCommands)
commitFileLoader := git_commands.NewCommitFileLoader(cmn, cmd) commitFileLoader := git_commands.NewCommitFileLoader(cmn, cmd)
commitLoader := git_commands.NewCommitLoader(cmn, cmd, dotGitDir, branchCommands.CurrentBranchName, statusCommands.RebaseMode) commitLoader := git_commands.NewCommitLoader(cmn, cmd, dotGitDir, branchCommands.CurrentBranchInfo, statusCommands.RebaseMode)
reflogCommitLoader := git_commands.NewReflogCommitLoader(cmn, cmd) reflogCommitLoader := git_commands.NewReflogCommitLoader(cmn, cmd)
remoteLoader := git_commands.NewRemoteLoader(cmn, cmd, repo.Remotes) remoteLoader := git_commands.NewRemoteLoader(cmn, cmd, repo.Remotes)
stashLoader := git_commands.NewStashLoader(cmn, cmd) stashLoader := git_commands.NewStashLoader(cmn, cmd)

View File

@ -30,18 +30,20 @@ func (self *BranchCommands) New(name string, base string) error {
return self.cmd.New(fmt.Sprintf("git checkout -b %s %s", self.cmd.Quote(name), self.cmd.Quote(base))).Run() return self.cmd.New(fmt.Sprintf("git checkout -b %s %s", self.cmd.Quote(name), self.cmd.Quote(base))).Run()
} }
// CurrentBranchName get the current branch name and displayname. // CurrentBranchInfo get the current branch information.
// the first returned string is the name and the second is the displayname func (self *BranchCommands) CurrentBranchInfo() (BranchInfo, error) {
// e.g. name is 123asdf and displayname is '(HEAD detached at 123asdf)'
func (self *BranchCommands) CurrentBranchName() (string, string, error) {
branchName, err := self.cmd.New("git symbolic-ref --short HEAD").DontLog().RunWithOutput() branchName, err := self.cmd.New("git symbolic-ref --short HEAD").DontLog().RunWithOutput()
if err == nil && branchName != "HEAD\n" { if err == nil && branchName != "HEAD\n" {
trimmedBranchName := strings.TrimSpace(branchName) trimmedBranchName := strings.TrimSpace(branchName)
return trimmedBranchName, trimmedBranchName, nil return BranchInfo{
RefName: trimmedBranchName,
DisplayName: trimmedBranchName,
DetachedHead: false,
}, nil
} }
output, err := self.cmd.New("git branch --contains").DontLog().RunWithOutput() output, err := self.cmd.New("git branch --contains").DontLog().RunWithOutput()
if err != nil { if err != nil {
return "", "", err return BranchInfo{}, err
} }
for _, line := range utils.SplitLines(output) { for _, line := range utils.SplitLines(output) {
re := regexp.MustCompile(CurrentBranchNameRegex) re := regexp.MustCompile(CurrentBranchNameRegex)
@ -49,10 +51,18 @@ func (self *BranchCommands) CurrentBranchName() (string, string, error) {
if len(match) > 0 { if len(match) > 0 {
branchName = match[1] branchName = match[1]
displayBranchName := match[0][2:] displayBranchName := match[0][2:]
return branchName, displayBranchName, nil return BranchInfo{
RefName: branchName,
DisplayName: displayBranchName,
DetachedHead: true,
}, nil
} }
} }
return "HEAD", "HEAD", nil return BranchInfo{
RefName: "HEAD",
DisplayName: "HEAD",
DetachedHead: true,
}, nil
} }
// Delete delete branch // Delete delete branch

View File

@ -27,24 +27,30 @@ type BranchLoaderConfigCommands interface {
Branches() (map[string]*config.Branch, error) Branches() (map[string]*config.Branch, error)
} }
type BranchInfo struct {
RefName string
DisplayName string // e.g. '(HEAD detached at 123asdf)'
DetachedHead bool
}
// BranchLoader returns a list of Branch objects for the current repo // BranchLoader returns a list of Branch objects for the current repo
type BranchLoader struct { type BranchLoader struct {
*common.Common *common.Common
getRawBranches func() (string, error) getRawBranches func() (string, error)
getCurrentBranchName func() (string, string, error) getCurrentBranchInfo func() (BranchInfo, error)
config BranchLoaderConfigCommands config BranchLoaderConfigCommands
} }
func NewBranchLoader( func NewBranchLoader(
cmn *common.Common, cmn *common.Common,
getRawBranches func() (string, error), getRawBranches func() (string, error),
getCurrentBranchName func() (string, string, error), getCurrentBranchInfo func() (BranchInfo, error),
config BranchLoaderConfigCommands, config BranchLoaderConfigCommands,
) *BranchLoader { ) *BranchLoader {
return &BranchLoader{ return &BranchLoader{
Common: cmn, Common: cmn,
getRawBranches: getRawBranches, getRawBranches: getRawBranches,
getCurrentBranchName: getCurrentBranchName, getCurrentBranchInfo: getCurrentBranchInfo,
config: config, config: config,
} }
} }
@ -84,11 +90,11 @@ outer:
} }
} }
if !foundHead { if !foundHead {
currentBranchName, currentBranchDisplayName, err := self.getCurrentBranchName() info, err := self.getCurrentBranchInfo()
if err != nil { if err != nil {
return nil, err return nil, err
} }
branches = slices.Prepend(branches, &models.Branch{Name: currentBranchName, DisplayName: currentBranchDisplayName, Head: true, Recency: " *"}) branches = slices.Prepend(branches, &models.Branch{Name: info.RefName, DisplayName: info.DisplayName, Head: true, DetachedHead: info.DetachedHead, Recency: " *"})
} }
configBranches, err := self.config.Branches() configBranches, err := self.config.Branches()

View File

@ -53,10 +53,10 @@ func TestBranchGetCommitDifferences(t *testing.T) {
func TestBranchNewBranch(t *testing.T) { func TestBranchNewBranch(t *testing.T) {
runner := oscommands.NewFakeRunner(t). runner := oscommands.NewFakeRunner(t).
Expect(`git checkout -b "test" "master"`, "", nil) Expect(`git checkout -b "test" "refs/heads/master"`, "", nil)
instance := buildBranchCommands(commonDeps{runner: runner}) instance := buildBranchCommands(commonDeps{runner: runner})
assert.NoError(t, instance.New("test", "master")) assert.NoError(t, instance.New("test", "refs/heads/master"))
runner.CheckForMissingCalls() runner.CheckForMissingCalls()
} }
@ -162,32 +162,34 @@ func TestBranchGetAllBranchGraph(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
} }
func TestBranchCurrentBranchName(t *testing.T) { func TestBranchCurrentBranchInfo(t *testing.T) {
type scenario struct { type scenario struct {
testName string testName string
runner *oscommands.FakeCmdObjRunner runner *oscommands.FakeCmdObjRunner
test func(string, string, error) test func(BranchInfo, error)
} }
scenarios := []scenario{ scenarios := []scenario{
{ {
"says we are on the master branch if we are", "says we are on the master branch if we are",
oscommands.NewFakeRunner(t).Expect(`git symbolic-ref --short HEAD`, "master", nil), oscommands.NewFakeRunner(t).Expect(`git symbolic-ref --short HEAD`, "master", nil),
func(name string, displayname string, err error) { func(info BranchInfo, err error) {
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, "master", name) assert.EqualValues(t, "master", info.RefName)
assert.EqualValues(t, "master", displayname) assert.EqualValues(t, "master", info.DisplayName)
assert.False(t, info.DetachedHead)
}, },
}, },
{ {
"falls back to git `git branch --contains` if symbolic-ref fails", "falls back to git `git branch --contains` if symbolic-ref fails",
oscommands.NewFakeRunner(t). oscommands.NewFakeRunner(t).
Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")). Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")).
Expect(`git branch --contains`, "* master", nil), Expect(`git branch --contains`, "* (HEAD detached at 8982166a)", nil),
func(name string, displayname string, err error) { func(info BranchInfo, err error) {
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, "master", name) assert.EqualValues(t, "8982166a", info.RefName)
assert.EqualValues(t, "master", displayname) assert.EqualValues(t, "(HEAD detached at 8982166a)", info.DisplayName)
assert.True(t, info.DetachedHead)
}, },
}, },
{ {
@ -195,10 +197,11 @@ func TestBranchCurrentBranchName(t *testing.T) {
oscommands.NewFakeRunner(t). oscommands.NewFakeRunner(t).
Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")). Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")).
Expect(`git branch --contains`, "* (HEAD detached at 123abcd)", nil), Expect(`git branch --contains`, "* (HEAD detached at 123abcd)", nil),
func(name string, displayname string, err error) { func(info BranchInfo, err error) {
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, "123abcd", name) assert.EqualValues(t, "123abcd", info.RefName)
assert.EqualValues(t, "(HEAD detached at 123abcd)", displayname) assert.EqualValues(t, "(HEAD detached at 123abcd)", info.DisplayName)
assert.True(t, info.DetachedHead)
}, },
}, },
{ {
@ -206,10 +209,11 @@ func TestBranchCurrentBranchName(t *testing.T) {
oscommands.NewFakeRunner(t). oscommands.NewFakeRunner(t).
Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")). Expect(`git symbolic-ref --short HEAD`, "", errors.New("error")).
Expect(`git branch --contains`, "", errors.New("error")), Expect(`git branch --contains`, "", errors.New("error")),
func(name string, displayname string, err error) { func(info BranchInfo, err error) {
assert.Error(t, err) assert.Error(t, err)
assert.EqualValues(t, "", name) assert.EqualValues(t, "", info.RefName)
assert.EqualValues(t, "", displayname) assert.EqualValues(t, "", info.DisplayName)
assert.False(t, info.DetachedHead)
}, },
}, },
} }
@ -218,7 +222,7 @@ func TestBranchCurrentBranchName(t *testing.T) {
s := s s := s
t.Run(s.testName, func(t *testing.T) { t.Run(s.testName, func(t *testing.T) {
instance := buildBranchCommands(commonDeps{runner: s.runner}) instance := buildBranchCommands(commonDeps{runner: s.runner})
s.test(instance.CurrentBranchName()) s.test(instance.CurrentBranchInfo())
s.runner.CheckForMissingCalls() s.runner.CheckForMissingCalls()
}) })
} }

View File

@ -29,7 +29,7 @@ type CommitLoader struct {
*common.Common *common.Common
cmd oscommands.ICmdObjBuilder cmd oscommands.ICmdObjBuilder
getCurrentBranchName func() (string, string, error) getCurrentBranchInfo func() (BranchInfo, error)
getRebaseMode func() (enums.RebaseMode, error) getRebaseMode func() (enums.RebaseMode, error)
readFile func(filename string) ([]byte, error) readFile func(filename string) ([]byte, error)
walkFiles func(root string, fn filepath.WalkFunc) error walkFiles func(root string, fn filepath.WalkFunc) error
@ -41,13 +41,13 @@ func NewCommitLoader(
cmn *common.Common, cmn *common.Common,
cmd oscommands.ICmdObjBuilder, cmd oscommands.ICmdObjBuilder,
dotGitDir string, dotGitDir string,
getCurrentBranchName func() (string, string, error), getCurrentBranchInfo func() (BranchInfo, error),
getRebaseMode func() (enums.RebaseMode, error), getRebaseMode func() (enums.RebaseMode, error),
) *CommitLoader { ) *CommitLoader {
return &CommitLoader{ return &CommitLoader{
Common: cmn, Common: cmn,
cmd: cmd, cmd: cmd,
getCurrentBranchName: getCurrentBranchName, getCurrentBranchInfo: getCurrentBranchInfo,
getRebaseMode: getRebaseMode, getRebaseMode: getRebaseMode,
readFile: os.ReadFile, readFile: os.ReadFile,
walkFiles: filepath.Walk, walkFiles: filepath.Walk,
@ -371,13 +371,13 @@ func (self *CommitLoader) setCommitMergedStatuses(refName string, commits []*mod
} }
func (self *CommitLoader) getMergeBase(refName string) (string, error) { func (self *CommitLoader) getMergeBase(refName string) (string, error) {
currentBranch, _, err := self.getCurrentBranchName() info, err := self.getCurrentBranchInfo()
if err != nil { if err != nil {
return "", err return "", err
} }
baseBranch := "master" baseBranch := "master"
if strings.HasPrefix(currentBranch, "feature/") { if strings.HasPrefix(info.RefName, "feature/") {
baseBranch = "develop" baseBranch = "develop"
} }

View File

@ -182,8 +182,8 @@ func TestGetCommits(t *testing.T) {
builder := &CommitLoader{ builder := &CommitLoader{
Common: utils.NewDummyCommon(), Common: utils.NewDummyCommon(),
cmd: oscommands.NewDummyCmdObjBuilder(scenario.runner), cmd: oscommands.NewDummyCmdObjBuilder(scenario.runner),
getCurrentBranchName: func() (string, string, error) { getCurrentBranchInfo: func() (BranchInfo, error) {
return scenario.currentBranchName, scenario.currentBranchName, nil return BranchInfo{RefName: scenario.currentBranchName, DisplayName: scenario.currentBranchName, DetachedHead: false}, nil
}, },
getRebaseMode: func() (enums.RebaseMode, error) { return scenario.rebaseMode, nil }, getRebaseMode: func() (enums.RebaseMode, error) { return scenario.rebaseMode, nil },
dotGitDir: ".git", dotGitDir: ".git",

View File

@ -11,6 +11,7 @@ type Branch struct {
Pullables string Pullables string
UpstreamGone bool UpstreamGone bool
Head bool Head bool
DetachedHead bool
// if we have a named remote locally this will be the name of that remote e.g. // if we have a named remote locally this will be the name of that remote e.g.
// 'origin' or 'tiwood'. If we don't have the remote locally it'll look like // 'origin' or 'tiwood'. If we don't have the remote locally it'll look like
// 'git@github.com:tiwood/lazygit.git' // 'git@github.com:tiwood/lazygit.git'
@ -19,6 +20,9 @@ type Branch struct {
} }
func (b *Branch) FullRefName() string { func (b *Branch) FullRefName() string {
if b.DetachedHead {
return b.Name
}
return "refs/heads/" + b.Name return "refs/heads/" + b.Name
} }

View File

@ -255,7 +255,7 @@ func (self *BranchesController) createNewBranchWithName(newBranchName string) er
return nil return nil
} }
if err := self.git.Branch.New(newBranchName, branch.Name); err != nil { if err := self.git.Branch.New(newBranchName, branch.FullRefName()); err != nil {
return self.c.Error(err) return self.c.Error(err)
} }
@ -411,7 +411,7 @@ func (self *BranchesController) rename(branch *models.Branch) error {
} }
func (self *BranchesController) newBranch(selectedBranch *models.Branch) error { func (self *BranchesController) newBranch(selectedBranch *models.Branch) error {
return self.helpers.Refs.NewBranch(selectedBranch.RefName(), selectedBranch.RefName(), "") return self.helpers.Refs.NewBranch(selectedBranch.FullRefName(), selectedBranch.RefName(), "")
} }
func (self *BranchesController) createPullRequestMenu(selectedBranch *models.Branch, checkedOutBranch *models.Branch) error { func (self *BranchesController) createPullRequestMenu(selectedBranch *models.Branch, checkedOutBranch *models.Branch) error {

View File

@ -29,7 +29,7 @@ var remoteIcons = []remoteIcon{
} }
func IconForBranch(branch *models.Branch) string { func IconForBranch(branch *models.Branch) string {
if branch.DisplayName != "" { if branch.DetachedHead {
return DETACHED_HEAD_ICON return DETACHED_HEAD_ICON
} }
return BRANCH_ICON return BRANCH_ICON

View File

@ -0,0 +1,39 @@
package branch
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var CheckoutByName = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Try to checkout branch by name. Verify that it also works on the branch with the special name @.",
ExtraCmdArgs: "",
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.
CreateNCommits(3).
NewBranch("@").
Checkout("master").
EmptyCommit("blah")
},
Run: func(shell *Shell, input *Input, assert *Assert, keys config.KeybindingConfig) {
input.SwitchToBranchesWindow()
assert.CurrentViewName("localBranches")
assert.MatchSelectedLine(Contains("master"))
input.NextItem()
assert.MatchSelectedLine(Contains("@"))
input.PressKeys(keys.Branches.CheckoutBranchByName)
assert.InPrompt()
assert.MatchCurrentViewTitle(Equals("Branch name:"))
input.Type("new-branch")
input.Confirm()
assert.InAlert()
assert.MatchCurrentViewContent(Equals("Branch not found. Create a new branch named new-branch?"))
input.Confirm()
assert.CurrentViewName("localBranches")
assert.MatchSelectedLine(Contains("new-branch"))
},
})

View File

@ -26,6 +26,7 @@ import (
var tests = []*components.IntegrationTest{ var tests = []*components.IntegrationTest{
bisect.Basic, bisect.Basic,
bisect.FromOtherBranch, bisect.FromOtherBranch,
branch.CheckoutByName,
branch.Delete, branch.Delete,
branch.Rebase, branch.Rebase,
branch.RebaseAndDrop, branch.RebaseAndDrop,

View File

@ -0,0 +1 @@
ref: refs/heads/new-branch

View File

@ -0,0 +1,12 @@
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[user]
email = CI@example.com
name = CI
[commit]
gpgSign = false

View File

@ -0,0 +1 @@
Unnamed repository; edit this file 'description' to name the repository.

View File

@ -0,0 +1,7 @@
0000000000000000000000000000000000000000 95efd4ea6ed74b904cd8eeeaa6245ec462372f67 CI <CI@example.com> 1665924398 +0900 commit (initial): commit 01
95efd4ea6ed74b904cd8eeeaa6245ec462372f67 cfc66e0e89b1dc11a927cc453dbee025ff03cf83 CI <CI@example.com> 1665924398 +0900 commit: commit 02
cfc66e0e89b1dc11a927cc453dbee025ff03cf83 6d69ac71e12a83769fca195d0a714435e1f4661a CI <CI@example.com> 1665924398 +0900 commit: commit 03
6d69ac71e12a83769fca195d0a714435e1f4661a 6d69ac71e12a83769fca195d0a714435e1f4661a CI <CI@example.com> 1665924398 +0900 checkout: moving from master to @
6d69ac71e12a83769fca195d0a714435e1f4661a 6d69ac71e12a83769fca195d0a714435e1f4661a CI <CI@example.com> 1665924398 +0900 checkout: moving from @ to master
6d69ac71e12a83769fca195d0a714435e1f4661a 18565748bda3ca01a67a92f340705af5a11384ae CI <CI@example.com> 1665924398 +0900 commit: blah
18565748bda3ca01a67a92f340705af5a11384ae 6d69ac71e12a83769fca195d0a714435e1f4661a CI <CI@example.com> 1665924403 +0900 checkout: moving from master to new-branch

View File

@ -0,0 +1 @@
0000000000000000000000000000000000000000 6d69ac71e12a83769fca195d0a714435e1f4661a CI <CI@example.com> 1665924398 +0900 branch: Created from HEAD

View File

@ -0,0 +1,4 @@
0000000000000000000000000000000000000000 95efd4ea6ed74b904cd8eeeaa6245ec462372f67 CI <CI@example.com> 1665924398 +0900 commit (initial): commit 01
95efd4ea6ed74b904cd8eeeaa6245ec462372f67 cfc66e0e89b1dc11a927cc453dbee025ff03cf83 CI <CI@example.com> 1665924398 +0900 commit: commit 02
cfc66e0e89b1dc11a927cc453dbee025ff03cf83 6d69ac71e12a83769fca195d0a714435e1f4661a CI <CI@example.com> 1665924398 +0900 commit: commit 03
6d69ac71e12a83769fca195d0a714435e1f4661a 18565748bda3ca01a67a92f340705af5a11384ae CI <CI@example.com> 1665924398 +0900 commit: blah

View File

@ -0,0 +1 @@
0000000000000000000000000000000000000000 6d69ac71e12a83769fca195d0a714435e1f4661a CI <CI@example.com> 1665924403 +0900 branch: Created from refs/heads/@

View File

@ -0,0 +1,3 @@
x�ÎM
Â0@a×9Eö‚dò3Í€ˆÐU�1I&ThL)<¾=‚Û�·x¹·ö.ãÑ‚%A 1Û”‚pñ`<q”êŒC#§Y«v>ä=4$ÎXŽnBª™�B1<�÷.T�¬ø3Ö~èyÑ÷yyÊ—Û¾É-÷öЀÈzGQ_ £N=§†ü™«´ñª~\
9f

View File

@ -0,0 +1,3 @@
x�Î=
1@aëœbzAfògD„­öÉd‚‚q—%‚Çw `ûøŠ'Kï�Äñ06UÐX µ�Ä–4WOè9'mŽ ]DÝ›%µfÍ›¾H“5q¡*D™íYÄW‹*ÚÐ:iÉ™ü÷eƒi†Ë4ßô“ûúÔ“,ý
c`ë'8"#š½îSCÿä?èÌ;û

View File

@ -0,0 +1,3 @@
x�ÎA
1 @Q×=Eö‚´™4mAD˜•ÇHÛë C�ï,<€ÛÏ[ü²ôþàƦ
b±Pž8s¬-ØèœGŒXšÉErÈHÊ)›U6} H^[%Ö('K¥FUa$¯…§€�ƒ‘÷¸/Ì78Ï·«~¤¯O=•¥_À1û„4¥G›¬5{ݧ†þÉ,š/×[;ª

View File

@ -0,0 +1 @@
6d69ac71e12a83769fca195d0a714435e1f4661a

View File

@ -0,0 +1 @@
18565748bda3ca01a67a92f340705af5a11384ae

View File

@ -0,0 +1 @@
6d69ac71e12a83769fca195d0a714435e1f4661a

View File

@ -0,0 +1 @@
file01 content

View File

@ -0,0 +1 @@
file02 content

View File

@ -0,0 +1 @@
file03 content