-
-
Notifications
You must be signed in to change notification settings - Fork 107
/
rootShell.go
242 lines (215 loc) · 6.17 KB
/
rootShell.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package cmd
import (
"fmt"
"github.com/rs/zerolog/log"
"os"
"strings"
"github.com/c-bata/go-prompt"
"github.com/spf13/cobra"
)
// ShellCmd represents the base command when called without any subcommands
var ShellCmd = &cobra.Command{
Use: "bit",
Short: "Bit is a Git CLI that predicts what you want to do",
Long: `v0.6.14`,
Run: func(cmd *cobra.Command, args []string) {
completerSuggestionMap, bitCmdMap := CreateSuggestionMap(cmd)
resp := SuggestionPrompt("> bit ", shellCommandCompleter(completerSuggestionMap))
subCommand := resp
if subCommand == "" {
return
}
if strings.Index(resp, " ") > 0 {
subCommand = subCommand[0:strings.Index(resp, " ")]
}
parsedArgs, err := parseCommandLine(resp)
if err != nil {
log.Debug().Err(err)
return
}
if bitCmdMap[subCommand] == nil {
yes := GitCommandsPromptUsed(parsedArgs, completerSuggestionMap)
if yes {
return
}
RunGitCommandWithArgs(parsedArgs)
return
}
cmd.SetArgs(parsedArgs)
cmd.Execute()
},
}
func init() {
ShellCmd.PersistentFlags().Bool("debug", false, "Print debugging information")
}
func CreateSuggestionMap(cmd *cobra.Command) (map[string][]prompt.Suggest, map[string]*cobra.Command) {
_, bitCmdMap := AllBitSubCommands(cmd)
allBitCmds := AllBitAndGitSubCommands(cmd)
//commonCommands := CobraCommandToSuggestions(CommonCommandsList())
branchListSuggestions := BranchListSuggestions()
completerSuggestionMap := map[string][]prompt.Suggest{
"": {},
"shell": CobraCommandToSuggestions(allBitCmds),
"checkout": branchListSuggestions,
"switch": branchListSuggestions,
"co": branchListSuggestions,
"merge": branchListSuggestions,
"rebase": branchListSuggestions,
"log": branchListSuggestions,
"add": GitAddSuggestions(),
"release": {
{Text: "bump", Description: "Increment SemVer from tags and release"},
{Text: "<version>", Description: "Name of release version e.g. v0.1.2"},
},
"reset": GitResetSuggestions(),
//"_any": commonCommands,
}
return completerSuggestionMap, bitCmdMap
}
// Execute adds all child commands to the shell command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the ShellCmd.
func Execute() {
if err := ShellCmd.Execute(); err != nil {
log.Info().Err(err)
os.Exit(1)
}
}
func shellCommandCompleter(suggestionMap map[string][]prompt.Suggest) func(d prompt.Document) []prompt.Suggest {
return func(d prompt.Document) []prompt.Suggest {
return promptCompleter(suggestionMap, d.Text)
}
}
func branchCommandCompleter(suggestionMap map[string][]prompt.Suggest) func(d prompt.Document) []prompt.Suggest {
return func(d prompt.Document) []prompt.Suggest {
return promptCompleter(suggestionMap, "checkout "+d.Text)
}
}
func promptCompleter(suggestionMap map[string][]prompt.Suggest, text string) []prompt.Suggest {
var suggestions []prompt.Suggest
split := strings.Split(text, " ")
filterFlags := make([]string, 0, len(split))
for i, v := range split {
if !strings.HasPrefix(v, "-") || i == len(split)-1 {
filterFlags = append(filterFlags, v)
}
}
prev := filterFlags[0] // in git commit -m "hello" commit is prev
if len(prev) == len(text) {
suggestions = suggestionMap["shell"]
return prompt.FilterHasPrefix(suggestions, prev, true)
}
curr := filterFlags[1] // in git commit -m "hello" "hello" is curr
if strings.HasPrefix(curr, "--") {
suggestions = FlagSuggestionsForCommand(prev, "--")
} else if strings.HasPrefix(curr, "-") {
suggestions = FlagSuggestionsForCommand(prev, "-")
} else if suggestionMap[prev] != nil {
suggestions = suggestionMap[prev]
if isBranchCompletionCommand(prev) {
return prompt.FilterContains(suggestions, curr, true)
}
}
return prompt.FilterHasPrefix(suggestions, curr, true)
}
func RunGitCommandWithArgs(args []string) {
var err error
err = RunInTerminalWithColor("git", args)
if err != nil {
log.Debug().Msg("Command may not exist: " + err.Error())
}
return
}
func GitCommandsPromptUsed(args []string, suggestionMap map[string][]prompt.Suggest) bool {
sub := args[0]
// handle checkout,switch,co commands as checkout
// if "-b" flag is not provided and branch does not exist
// user would be prompted asking whether to create a branch or not
// expected usage format
// bit (checkout|switch|co) [-b] branch-name
if args[len(args)-1] == "--version" {
fmt.Println("bit version v0.6.14")
}
if isBranchCompletionCommand(sub) {
branchName := ""
if len(args) < 2 {
branchName = SuggestionPrompt("> bit "+sub+" ", branchCommandCompleter(suggestionMap))
} else {
branchName = strings.TrimSpace(args[len(args)-1])
}
if strings.HasPrefix(branchName, "origin/") {
branchName = branchName[7:]
}
args[len(args)-1] = branchName
var createBranch bool
if len(args) == 3 && args[len(args)-2] == "-b" {
createBranch = true
}
branchExists := checkoutBranch(branchName)
if branchExists {
refreshBranch()
return true
}
if !createBranch && !AskConfirm("Branch does not exist. Do you want to create it?") {
fmt.Printf("Cancelling...")
return true
}
RunInTerminalWithColor("git", []string{"checkout", "-b", branchName})
return true
}
return false
}
func parseCommandLine(command string) ([]string, error) {
var args []string
state := "start"
current := ""
quote := "\""
escapeNext := true
for i := 0; i < len(command); i++ {
c := command[i]
if state == "quotes" {
if string(c) != quote {
current += string(c)
} else {
args = append(args, current)
current = ""
state = "start"
}
continue
}
if escapeNext {
current += string(c)
escapeNext = false
continue
}
if c == '\\' {
escapeNext = true
continue
}
if c == '"' || c == '\'' {
state = "quotes"
quote = string(c)
continue
}
if state == "arg" {
if c == ' ' || c == '\t' {
args = append(args, current)
current = ""
state = "start"
} else {
current += string(c)
}
continue
}
if c != ' ' && c != '\t' {
state = "arg"
current += string(c)
}
}
if state == "quotes" {
return []string{}, fmt.Errorf("Unclosed quote in command line: %s", command)
}
if current != "" {
args = append(args, current)
}
return args, nil
}