2022-09-02 02:58:36 +02:00
|
|
|
package git_commands
|
|
|
|
|
2022-09-11 07:36:47 +02:00
|
|
|
import (
|
2023-07-17 06:38:08 +02:00
|
|
|
"path/filepath"
|
2023-07-17 05:40:26 +02:00
|
|
|
|
|
|
|
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
2022-09-11 07:36:47 +02:00
|
|
|
)
|
|
|
|
|
2022-09-02 02:58:36 +02:00
|
|
|
type WorktreeCommands struct {
|
|
|
|
*GitCommon
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWorktreeCommands(gitCommon *GitCommon) *WorktreeCommands {
|
|
|
|
return &WorktreeCommands{
|
|
|
|
GitCommon: gitCommon,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-16 11:39:53 +02:00
|
|
|
type NewWorktreeOpts struct {
|
|
|
|
// required. The path of the new worktree.
|
|
|
|
Path string
|
|
|
|
// required. The base branch/ref.
|
|
|
|
Base string
|
2022-09-03 06:38:16 +02:00
|
|
|
|
2023-07-16 11:39:53 +02:00
|
|
|
// if true, ends up with a detached head
|
|
|
|
Detach bool
|
|
|
|
|
|
|
|
// optional. if empty, and if detach is false, we will checkout the base
|
|
|
|
Branch string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *WorktreeCommands) New(opts NewWorktreeOpts) error {
|
|
|
|
if opts.Detach && opts.Branch != "" {
|
|
|
|
panic("cannot specify branch when detaching")
|
|
|
|
}
|
|
|
|
|
|
|
|
cmdArgs := NewGitCmd("worktree").Arg("add").
|
|
|
|
ArgIf(opts.Detach, "--detach").
|
|
|
|
ArgIf(opts.Branch != "", "-b", opts.Branch).
|
|
|
|
Arg(opts.Path, opts.Base)
|
|
|
|
|
|
|
|
return self.cmd.New(cmdArgs.ToArgv()).Run()
|
2022-09-03 06:38:16 +02:00
|
|
|
}
|
|
|
|
|
2022-09-02 02:58:36 +02:00
|
|
|
func (self *WorktreeCommands) Delete(worktreePath string, force bool) error {
|
|
|
|
cmdArgs := NewGitCmd("worktree").Arg("remove").ArgIf(force, "-f").Arg(worktreePath).ToArgv()
|
|
|
|
|
|
|
|
return self.cmd.New(cmdArgs).Run()
|
|
|
|
}
|
2022-09-11 07:36:47 +02:00
|
|
|
|
2023-07-16 09:52:07 +02:00
|
|
|
func (self *WorktreeCommands) Detach(worktreePath string) error {
|
2023-07-24 07:29:23 +02:00
|
|
|
cmdArgs := NewGitCmd("checkout").Arg("--detach").GitDir(filepath.Join(worktreePath, ".git")).ToArgv()
|
2023-07-16 09:52:07 +02:00
|
|
|
|
2023-07-24 07:29:23 +02:00
|
|
|
return self.cmd.New(cmdArgs).Run()
|
2023-07-16 09:52:07 +02:00
|
|
|
}
|
|
|
|
|
2023-07-17 05:40:26 +02:00
|
|
|
func WorktreeForBranch(branch *models.Branch, worktrees []*models.Worktree) (*models.Worktree, bool) {
|
|
|
|
for _, worktree := range worktrees {
|
|
|
|
if worktree.Branch == branch.Name {
|
|
|
|
return worktree, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
func CheckedOutByOtherWorktree(branch *models.Branch, worktrees []*models.Worktree) bool {
|
|
|
|
worktree, ok := WorktreeForBranch(branch, worktrees)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-07-28 08:17:15 +02:00
|
|
|
return !worktree.IsCurrent
|
2023-07-17 05:40:26 +02:00
|
|
|
}
|