-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompletion.go
147 lines (122 loc) · 2.47 KB
/
completion.go
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package completion
import (
"fmt"
"io"
"os"
"path"
)
// ICommand return interface for choice shell
type ICommand interface {
Zsh() ICompletion
Bash() ICompletion
}
// ICompletion return interface for choice output
type ICompletion interface {
ToString() string
ToWriter(w io.Writer) error
ToFile(filename string) error
}
type completion struct {
string
}
func (cmd *command) Zsh() ICompletion {
return completion{zsh(cmd)}
}
func (cmd *command) Bash() ICompletion {
return completion{bash(cmd)}
}
func (c completion) ToString() string {
return c.string
}
func (c completion) ToWriter(w io.Writer) error {
_, err := fmt.Fprint(w, c.string)
return err
}
func (c completion) ToFile(filename string) error {
if err := os.MkdirAll(path.Dir(filename), 0755); err != nil {
return err
}
f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
return err
}
defer f.Close()
return c.ToWriter(f)
}
type command struct {
Name string
Description string
Alias Alias
Flags []flag
Arguments []string
SubCommands []*command
Parent *command
}
func (cmd command) HasAlias() bool {
return len(cmd.Alias) > 0
}
func (cmd command) HasFlags() bool {
return len(cmd.Flags) > 0
}
func (cmd command) HasArguments() bool {
return len(cmd.Arguments) > 0
}
func (cmd command) HasSubCommands() bool {
return len(cmd.SubCommands) > 0
}
func (cmd command) HasParent() bool {
return cmd.Parent != nil
}
func (cmd command) FullName() string {
var name string
if cmd.HasParent() {
var parent = cmd.Parent
for {
name = fmt.Sprintf("_%s%s", parent.Name, name)
if !parent.HasParent() {
break
}
parent = parent.Parent
}
}
return fmt.Sprintf("%s_%s", name, cmd.Name)
}
func (cmd command) Level() int {
var level = 1
if cmd.HasParent() {
var parent = cmd.Parent
for {
level++
if !parent.HasParent() {
break
}
parent = parent.Parent
}
}
return level
}
func (cmd command) ListSubCommands() []string {
var subCommands []string
if cmd.HasSubCommands() {
for _, c := range cmd.SubCommands {
subCommands = append(subCommands, c.Name)
}
}
return subCommands
}
type Alias []string
func (a Alias) Format(prefix string, suffix string) string {
var alias string
for _, v := range a {
alias += fmt.Sprintf("%s%s%s", prefix, v, suffix)
}
return alias
}
type flag struct {
Name string
Shorthand string
Description string
}
func (f flag) HasShorthand() bool {
return len(f.Shorthand) > 0
}