Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

man: added ActionSections #2525

Merged
merged 1 commit into from
Sep 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions pkg/actions/tools/man/section.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package man

import (
"regexp"
"strings"

"github.com/carapace-sh/carapace"
)

// ActionSections completes sections of given manpage (or all if empty).
//
// 1 (General commands)
// 2 (System calls)
func ActionSections(manpage string) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
a := carapace.ActionValuesDescribed(
"1", "General commands",
"2", "System calls",
"3", "Library functions",
"4", "Special files",
"5", "File formats and conventions",
"6", "Games and screensavers",
"7", "Miscellaneous",
"8", "System administration commands and daemons",
)

if manpage != "" {
output, err := c.Command("man", "-f", manpage).Output()
if err != nil {
return carapace.ActionMessage(err.Error())
}

r := regexp.MustCompile(`^` + regexp.QuoteMeta(manpage) + ` \((?P<section>[^]]+)\).*$`)
sections := make([]string, 0)
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if matches := r.FindStringSubmatch(line); matches != nil {
sections = append(sections, matches[1][:1]) // only use first character
}
}
a = a.Retain(sections...)
}
return a
})
}