Skip to content

Commit

Permalink
git: switch - list remote branch names
Browse files Browse the repository at this point in the history
  • Loading branch information
rsteube committed Feb 6, 2024
1 parent 7103508 commit 8aecd6d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
5 changes: 4 additions & 1 deletion completers/git_completer/cmd/switch.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ func init() {
})

carapace.Gen(switchCmd).PositionalCompletion(
git.ActionRefs(git.RefOption{LocalBranches: true}),
carapace.Batch(
git.ActionRemoteBranchNames(""),
git.ActionRefs(git.RefOption{LocalBranches: true}),
).ToA(),
)

carapace.Gen(switchCmd).DashAnyCompletion(
Expand Down
29 changes: 27 additions & 2 deletions pkg/actions/tools/git/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ func ActionLocalBranches() carapace.Action {

// ActionRemoteBranches completes remote branches
//
// master (last commit msg)
// another (last commit msg)
// origin/master (last commit msg)
// upstream/another (last commit msg)
func ActionRemoteBranches(remote string) carapace.Action {
return carapace.ActionExecCommand("git", "branch", "--remote", "--format", "%(refname:short)\n%(subject)")(func(output []byte) carapace.Action {
lines := strings.Split(string(output), "\n")
Expand All @@ -49,3 +49,28 @@ func ActionRemoteBranches(remote string) carapace.Action {
return carapace.ActionValuesDescribed(vals...).Style(styles.Git.Branch)
}).Tag("remote branches")
}

// ActionRemoteBranchNames is like ActionRemoteBranches but skips the remote prefix
//
// master (last commit msg)
// another (last commit msg)
func ActionRemoteBranchNames(remote string) carapace.Action {
return carapace.ActionExecCommand("git", "branch", "--remote", "--format", "%(refname:short)\n%(subject)")(func(output []byte) carapace.Action {
lines := strings.Split(string(output), "\n")

prefix := ""
if remote != "" {
prefix = remote + "/"
}

vals := make([]string, 0)
for index, line := range lines[:len(lines)-1] {
if index%2 == 0 && strings.HasPrefix(line, prefix) {
if _, branch, ok := strings.Cut(line, "/"); ok {
vals = append(vals, branch, lines[index+1])
}
}
}
return carapace.ActionValuesDescribed(vals...).Style(styles.Git.Branch)
}).Tag("remote branch names")
}

0 comments on commit 8aecd6d

Please sign in to comment.