diff --git a/pkg/commands/git_commands/worktree.go b/pkg/commands/git_commands/worktree.go index 7f3dd8e01..101601afb 100644 --- a/pkg/commands/git_commands/worktree.go +++ b/pkg/commands/git_commands/worktree.go @@ -33,12 +33,16 @@ func (self *WorktreeCommands) Delete(worktreePath string, force bool) error { } func (self *WorktreeCommands) IsCurrentWorktree(w *models.Worktree) bool { + return IsCurrentWorktree(w) +} + +func IsCurrentWorktree(w *models.Worktree) bool { pwd, err := os.Getwd() if err != nil { log.Fatalln(err.Error()) } - return pwd == w.Path + return EqualPath(pwd, w.Path) } func (self *WorktreeCommands) IsWorktreePathMissing(w *models.Worktree) bool { @@ -50,3 +54,9 @@ func (self *WorktreeCommands) IsWorktreePathMissing(w *models.Worktree) bool { } return false } + +// checks if two paths are equal +// TODO: support relative paths +func EqualPath(a string, b string) bool { + return a == b +} diff --git a/pkg/commands/git_commands/worktree_loader.go b/pkg/commands/git_commands/worktree_loader.go index 070cdca73..23ccc39d8 100644 --- a/pkg/commands/git_commands/worktree_loader.go +++ b/pkg/commands/git_commands/worktree_loader.go @@ -1,6 +1,7 @@ package git_commands import ( + "os" "strings" "github.com/jesseduffield/lazygit/pkg/commands/models" @@ -34,22 +35,22 @@ func (self *WorktreeLoader) GetWorktrees() ([]*models.Worktree, error) { splitLines := strings.Split(worktreesOutput, "\x00") var worktrees []*models.Worktree - var currentWorktree *models.Worktree + var current *models.Worktree for _, splitLine := range splitLines { - if len(splitLine) == 0 && currentWorktree != nil { - worktrees = append(worktrees, currentWorktree) - currentWorktree = nil + if len(splitLine) == 0 && current != nil { + worktrees = append(worktrees, current) + current = nil continue } if strings.HasPrefix(splitLine, "worktree ") { path := strings.SplitN(splitLine, " ", 2)[1] - currentWorktree = &models.Worktree{ + current = &models.Worktree{ IsMain: len(worktrees) == 0, Path: path, } } else if strings.HasPrefix(splitLine, "branch ") { branch := strings.SplitN(splitLine, " ", 2)[1] - currentWorktree.Branch = strings.TrimPrefix(branch, "refs/heads/") + current.Branch = strings.TrimPrefix(branch, "refs/heads/") } } @@ -61,6 +62,20 @@ func (self *WorktreeLoader) GetWorktrees() ([]*models.Worktree, error) { worktree.NameField = names[index] } + pwd, err := os.Getwd() + if err != nil { + return nil, err + } + + // move current worktree to the top + for i, worktree := range worktrees { + if EqualPath(worktree.Path, pwd) { + worktrees = append(worktrees[:i], worktrees[i+1:]...) + worktrees = append([]*models.Worktree{worktree}, worktrees...) + break + } + } + return worktrees, nil }