File: fish.go

package info (click to toggle)
gum 0.17.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 668 kB
  • sloc: sh: 232; ruby: 24; makefile: 17; javascript: 9; python: 4
file content (93 lines) | stat: -rw-r--r-- 1,977 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package completion

import (
	"fmt"
	"io"
	"strings"

	"github.com/alecthomas/kong"
)

// Fish is a fish shell completion generator.
type Fish struct{}

// Run generates fish completion script.
func (f Fish) Run(ctx *kong.Context) error {
	var buf strings.Builder
	buf.WriteString(`# Fish shell completion for gum
# Generated by gum completion

# disable file completion unless explicitly enabled
complete -c gum -f

`)
	node := ctx.Model.Node
	f.gen(&buf, node)
	_, err := fmt.Fprint(ctx.Stdout, buf.String())
	if err != nil {
		return fmt.Errorf("unable to generate fish completion: %w", err)
	}
	return nil
}

func (f Fish) gen(buf io.StringWriter, cmd *kong.Node) {
	root := cmd
	for root.Parent != nil {
		root = root.Parent
	}
	rootName := root.Name
	if cmd.Parent == nil {
		_, _ = buf.WriteString(fmt.Sprintf("# %s\n", rootName))
	} else {
		_, _ = buf.WriteString(fmt.Sprintf("# %s\n", cmd.Path()))
		_, _ = buf.WriteString(
			fmt.Sprintf("complete -c %s -f -n '__fish_use_subcommand' -a %s -d '%s'\n",
				rootName,
				cmd.Name,
				cmd.Help,
			),
		)
	}

	for _, f := range cmd.Flags {
		if f.Hidden {
			continue
		}
		if cmd.Parent == nil {
			_, _ = buf.WriteString(
				fmt.Sprintf("complete -c %s -f",
					rootName,
				),
			)
		} else {
			_, _ = buf.WriteString(
				fmt.Sprintf("complete -c %s -f -n '__fish_seen_subcommand_from %s'",
					rootName,
					cmd.Name,
				),
			)
		}
		if !f.IsBool() {
			enums := flagPossibleValues(f)
			if len(enums) > 0 {
				_, _ = buf.WriteString(fmt.Sprintf(" -xa '%s'", strings.Join(enums, " ")))
			} else {
				_, _ = buf.WriteString(" -x")
			}
		}
		if f.Short != 0 {
			_, _ = buf.WriteString(fmt.Sprintf(" -s %c", f.Short))
		}
		_, _ = buf.WriteString(fmt.Sprintf(" -l %s", f.Name))
		_, _ = buf.WriteString(fmt.Sprintf(" -d \"%s\"", f.Help))
		_, _ = buf.WriteString("\n")
	}
	_, _ = buf.WriteString("\n")

	for _, c := range cmd.Children {
		if c == nil || c.Hidden {
			continue
		}
		f.gen(buf, c)
	}
}