eia-api-go/cmd/eia-client/internal/util/util_completion.go

53 lines
1.5 KiB
Go
Raw Normal View History

2024-11-26 15:54:55 +00:00
package util
import (
"slices"
"strings"
"github.com/spf13/cobra"
"gitea.libretechconsulting.com/50W/eia-api-go/pkg/eia"
)
2024-11-26 17:16:27 +00:00
// Given args of <route> <facet>, complete either the route arg or the
// facet arg, whichever is appropriate
func CompleteRouteOrFacet(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) < 1 {
return CompleteRoute(cmd, args, toComplete)
}
return CompleteFacet(cmd, args, toComplete)
}
func CompleteFacet(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
facets, err := GetFacets(cmd, args[0])
if err != nil {
Logger(cmd).Err(err).Send()
return nil, cobra.ShellCompDirectiveError
} else if facets.FacetOptions == nil || len(*facets.FacetOptions) < 1 {
Logger(cmd).Error().Str("route", args[0]).Msg("no facets found for route")
return nil, cobra.ShellCompDirectiveError
}
compFacets := make([]string, 0, len(*facets.FacetOptions))
for _, facet := range *facets.FacetOptions {
if strings.HasPrefix(facet, toComplete) {
compFacets = append(compFacets, facet)
}
}
return slices.Clip(compFacets), cobra.ShellCompDirectiveNoFileComp
}
func CompleteRoute(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
2024-11-26 15:54:55 +00:00
routes := eia.GetRoutes()
compRoutes := make([]string, 0, len(routes))
for _, r := range routes {
if strings.HasPrefix(r, toComplete) {
compRoutes = append(compRoutes, r)
}
}
return slices.Clip(compRoutes), cobra.ShellCompDirectiveNoFileComp
}