Skip to content

Commit

Permalink
ActionPathExecutables: added man descriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
rsteube committed Sep 26, 2022
1 parent 773984c commit 0a15137
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions pkg/actions/os/executable.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package os

import (
"os"
"regexp"
"strings"

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

Expand All @@ -16,22 +18,27 @@ import (
func ActionPathExecutables() carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
batch := carapace.Batch()
manDescriptions := manDescriptions(c)
dirs := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator))
for i := len(dirs) - 1; i >= 0; i-- {
batch = append(batch, actionDirectoryExecutables(dirs[i], c.CallbackValue))
batch = append(batch, actionDirectoryExecutables(dirs[i], c.CallbackValue, manDescriptions))
}
return batch.ToA()
})
}

func actionDirectoryExecutables(dir string, prefix string) carapace.Action {
func actionDirectoryExecutables(dir string, prefix string, manDescriptions map[string]string) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
if files, err := os.ReadDir(dir); err == nil {
vals := make([]string, 0)
for _, f := range files {
if strings.HasPrefix(f.Name(), prefix) {
if info, err := f.Info(); err == nil && !f.IsDir() && isExecAny(info.Mode()) {
vals = append(vals, f.Name(), completers.Description(f.Name()), style.ForPath(dir+"/"+f.Name()))
description := completers.Description(f.Name())
if description == "" {
description = manDescriptions[f.Name()]
}
vals = append(vals, f.Name(), description, style.ForPath(dir+"/"+f.Name()))
}
}
}
Expand All @@ -44,3 +51,19 @@ func actionDirectoryExecutables(dir string, prefix string) carapace.Action {
func isExecAny(mode os.FileMode) bool {
return mode&0111 != 0
}

func manDescriptions(c carapace.Context) (descriptions map[string]string) {
descriptions = make(map[string]string)
if !util.HasPathPrefix(c.CallbackValue) {
if output, err := c.Command("man", "--names-only", "-k", "^"+c.CallbackValue).Output(); err == nil {
lines := strings.Split(string(output), "\n")
r := regexp.MustCompile(`^(?P<name>[^ ]+) [^-]+- (?P<description>.*)$`)
for _, line := range lines {
if matches := r.FindStringSubmatch(line); len(matches) > 2 {
descriptions[matches[1]] = matches[2]
}
}
}
}
return
}

0 comments on commit 0a15137

Please sign in to comment.