Skip to content

Commit

Permalink
Merge pull request #1541 from rsteube/git-checkout-files
Browse files Browse the repository at this point in the history
git: checkout - complete files
  • Loading branch information
rsteube authored Mar 8, 2023
2 parents 2d35ab2 + 5307163 commit 0b92a83
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
12 changes: 9 additions & 3 deletions completers/git_completer/cmd/checkout.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,16 @@ func init() {

carapace.Gen(checkoutCmd).PositionalAnyCompletion(
carapace.ActionCallback(func(c carapace.Context) carapace.Action {
if checkoutCmd.Flags().ArgsLenAtDash() != -1 {
return carapace.ActionFiles() // TODO files from branch?
return git.ActionRefChanges(c.Args[0]).Invoke(c).Filter(c.Args[1:]).ToA()
}),
)

carapace.Gen(checkoutCmd).DashAnyCompletion(
carapace.ActionCallback(func(c carapace.Context) carapace.Action {
if args := checkoutCmd.Flags().Args(); len(args[:checkoutCmd.ArgsLenAtDash()]) > 0 {
return git.ActionRefChanges(args[0]).Invoke(c).Filter(args[1:]).ToA()
}
return carapace.ActionValues()
return git.ActionChanges(git.ChangeOpts{}.Default()).Invoke(c).Filter(c.Args).ToA()
}),
)
}
34 changes: 34 additions & 0 deletions pkg/actions/tools/git/change.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strings"

"github.com/rsteube/carapace"
"github.com/rsteube/carapace-bin/pkg/util"
"github.com/rsteube/carapace/pkg/style"
)

Expand Down Expand Up @@ -56,3 +57,36 @@ func ActionChanges(opts ChangeOpts) carapace.Action {
})
})
}

// ActionRefChanges completes changes compared to given ref.
//
// go.mod
// cmd/carapace/main.go
func ActionRefChanges(ref string) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
return carapace.ActionExecCommand("git", "diff-tree", "--name-only", "--no-commit-id", "-r", ref)(func(output []byte) carapace.Action {
lines := strings.Split(string(output), "\n")

path, err := util.FindReverse(c.Dir, ".git")
if err != nil {
return carapace.ActionMessage(err.Error())
}
relativeRoot, err := filepath.Rel(c.Dir, filepath.Dir(path))
if err != nil {
return carapace.ActionMessage(err.Error())
}
if relativeRoot == "." {
relativeRoot = ""
} else {
relativeRoot += "/"
}

vals := make([]string, 0)
for _, line := range lines[:len(lines)-1] {
vals = append(vals, relativeRoot+line)
}

return carapace.ActionValues(vals...).StyleF(style.ForPathExt)
})
})
}

0 comments on commit 0b92a83

Please sign in to comment.