-
-
Notifications
You must be signed in to change notification settings - Fork 107
/
util.go
414 lines (374 loc) · 9.88 KB
/
util.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package cmd
import (
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/c-bata/go-prompt"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"os"
"os/exec"
"regexp"
"runtime"
"runtime/debug"
"strings"
)
func RunInTerminalWithColor(cmdName string, args []string) error {
dir, err := os.Getwd()
if err != nil {
return err
}
return RunInTerminalWithColorInDir(cmdName, dir, args)
}
func RunInTerminalWithColorInDir(cmdName string, dir string, args []string) error {
log.Debug().Msg(cmdName + " " + strings.Join(args, " "))
_, w, err := os.Pipe()
if err != nil {
panic(err)
}
cmd := exec.Command(cmdName, args...)
cmd.Dir = dir
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if runtime.GOOS != "windows" {
cmd.ExtraFiles = []*os.File{w}
}
err = cmd.Run()
log.Debug().Err(err)
return err
}
func AskConfirm(q string) bool {
ans := false
survey.AskOne(&survey.Confirm{
Message: q,
}, &ans)
return ans
}
func AskMultiLine(q string) string {
text := ""
prompt := &survey.Multiline{
Message: q,
}
survey.AskOne(prompt, &text)
return text
}
func BranchList() []Branch {
rawBranchData, err := branchListRaw()
if err != nil {
log.Debug().Err(err)
}
return toStructuredBranchList(rawBranchData)
}
func toStructuredBranchList(rawBranchData string) []Branch {
list := strings.Split(strings.TrimSpace(rawBranchData), "\n")
var branches []Branch
for _, line := range list {
// first character of each should start with ' which all commits have based on expected raw formatting
if !strings.HasPrefix(line, `'`) {
continue
}
cols := strings.Split(line[1:], "; ")
b := Branch{
Author: cols[1],
Name: cols[3],
RelativeDate: cols[4],
AbsoluteDate: cols[0],
}
if b.Name == "origin/master" || b.Name == "origin/HEAD" {
continue
}
branches = append(branches, b)
}
return branches
}
func GenBumpedSemVersion() string {
msg, err := exec.Command("/bin/sh", "-c", `git describe --tags --abbrev=0 | awk -F. '{$NF+=1; OFS="."; print $0}'`).CombinedOutput()
if err != nil {
log.Debug().Err(err)
}
out := string(msg)
return strings.TrimSpace(out)
}
func AddCommandToShellHistory(cmd string, args []string) {
// not possible??
msg, err := exec.Command("/bin/bash", "-c", "history").CombinedOutput()
if err != nil {
log.Debug().Err(err)
}
log.Debug().Msg(string(msg))
}
func BranchListSuggestions() []prompt.Suggest {
branches := BranchList()
var suggestions []prompt.Suggest
for _, branch := range branches {
suggestions = append(suggestions, prompt.Suggest{
Text: branch.Name,
Description: fmt.Sprintf("%s %s %s", branch.Author, branch.RelativeDate, branch.AbsoluteDate),
})
}
return suggestions
}
func GitAddSuggestions() []prompt.Suggest {
fileChanges := FileChangesList()
var suggestions []prompt.Suggest
suggestions = append(suggestions, prompt.Suggest{
Text: "-u",
Description: "Add modified and deleted files and exclude untracked files.",
})
for _, fc := range fileChanges {
suggestions = append(suggestions, prompt.Suggest{
Text: fc.Name,
Description: fc.Status + " ~~~",
})
}
return suggestions
}
func GitResetSuggestions() []prompt.Suggest {
fileChanges := FileChangesList()
var suggestions []prompt.Suggest
for _, fc := range fileChanges {
if fc.Status == "Added" || fc.Status == "Partially Added" || fc.Status == "New File" {
suggestions = append(suggestions, prompt.Suggest{
Text: fc.Name,
Description: fc.Status + " ~~~",
})
}
}
return suggestions
}
func CobraCommandToSuggestions(cmds []*cobra.Command) []prompt.Suggest {
var suggestions []prompt.Suggest
for _, branch := range cmds {
suggestions = append(suggestions, prompt.Suggest{
Text: branch.Use,
Description: branch.Short,
})
}
return suggestions
}
type Branch struct {
Author string
Name string
RelativeDate string
AbsoluteDate string
}
type FileChange struct {
Name string
Status string
}
func SuggestionPrompt(prefix string, completer func(d prompt.Document) []prompt.Suggest) string {
result := prompt.Input(prefix, completer,
prompt.OptionTitle(""),
prompt.OptionHistory([]string{""}),
prompt.OptionPrefixTextColor(prompt.Yellow), // fine
//prompt.OptionPreviewSuggestionBGColor(prompt.Yellow),
//prompt.OptionPreviewSuggestionTextColor(prompt.Yellow),
prompt.OptionSelectedSuggestionBGColor(prompt.Yellow),
prompt.OptionSuggestionBGColor(prompt.Yellow),
prompt.OptionSuggestionTextColor(prompt.DarkGray),
prompt.OptionSelectedSuggestionTextColor(prompt.Blue),
prompt.OptionDescriptionBGColor(prompt.Black),
prompt.OptionDescriptionTextColor(prompt.White),
prompt.OptionShowCompletionAtStart(),
prompt.OptionCompletionOnDown(),
prompt.OptionSwitchKeyBindMode(prompt.EmacsKeyBind),
prompt.OptionAddKeyBind(prompt.KeyBind{
Key: prompt.ControlC,
Fn: exit,
}),
prompt.OptionAddASCIICodeBind(prompt.ASCIICodeBind{
ASCIICode: []byte{0x1b, 0x62},
Fn: prompt.GoLeftWord,
}),
prompt.OptionAddASCIICodeBind(prompt.ASCIICodeBind{
ASCIICode: []byte{0x1b, 0x66},
Fn: prompt.GoRightWord,
}),
)
branchName := strings.TrimSpace(result)
if strings.HasPrefix(result, "origin/") {
branchName = branchName[7:]
}
return branchName
}
type Exit int
func exit(_ *prompt.Buffer) {
panic(Exit(0))
}
func HandleExit() {
switch v := recover().(type) {
case nil:
return
case Exit:
os.Exit(int(v))
default:
fmt.Println(v)
fmt.Println(string(debug.Stack()))
fmt.Println("OS:", runtime.GOOS, runtime.GOARCH)
fmt.Println("bit version v0.6.14")
PrintGitVersion()
}
}
func AllBitSubCommands(rootCmd *cobra.Command) ([]*cobra.Command, map[string]*cobra.Command) {
bitCmds := rootCmd.Commands()
bitCmdMap := map[string]*cobra.Command{}
for _, bitCmd := range bitCmds {
bitCmdMap[bitCmd.Name()] = bitCmd
}
return bitCmds, bitCmdMap
}
func AllBitAndGitSubCommands(rootCmd *cobra.Command) (cc []*cobra.Command) {
gitAliases := AllGitAliases()
gitCmds := AllGitSubCommands()
bitCmds, _ := AllBitSubCommands(rootCmd)
commonCommands := CommonCommandsList()
return concatCopyPreAllocate([][]*cobra.Command{commonCommands, gitCmds, bitCmds, gitAliases})
}
func concatCopyPreAllocate(slices [][]*cobra.Command) []*cobra.Command {
var totalLen int
for _, s := range slices {
totalLen += len(s)
}
tmp := make([]*cobra.Command, totalLen)
var i int
for _, s := range slices {
i += copy(tmp[i:], s)
}
return tmp
}
func FlagSuggestionsForCommand(gitSubCmd string, flagtype string) []prompt.Suggest {
str := ""
flagMap := map[string]string{
"add": addFlagsStr,
"diff": diffFlagsStr,
"status": statusFlagsStr,
"commit": commitFlagsStr,
"branch": branchFlagsStr,
"tag": tagFlagsStr,
"checkout": checkoutFlagsStr,
"merge": mergeFlagsStr,
"pull": pullFlagsStr,
"push": pushFlagsStr,
"log": logFlagsStr,
"rebase": rebaseFlagsStr,
"reset": resetFlagsStr,
}
str = flagMap[gitSubCmd]
if str == "" {
return []prompt.Suggest{}
//str = parseManPage(gitSubCmd)
}
list := strings.Split(str, ".\n\n")
//list := strings.Split(strings.Split(op[1], "CONFIGURATION")[0], "\n\n")
var suggestions []prompt.Suggest
for i := 0; i < len(list)-1; i++ {
line := list[i]
if !strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "--") {
continue
}
split := strings.Split(line, "\n")
flags := split[:len(split)-1]
desc := split[len(split)-1]
for _, flag := range flags {
if strings.HasPrefix(flag, "--") && flagtype == "--" {
suggestions = append(suggestions, prompt.Suggest{
Text: flag,
Description: desc,
})
}
if !strings.HasPrefix(flag, "--") && flagtype == "-" {
suggestions = append(suggestions, prompt.Suggest{
Text: flag,
Description: desc,
})
}
}
}
return suggestions
}
func CommonCommandsList() []*cobra.Command {
return []*cobra.Command{
{
Use: "status",
Short: "Show the working tree status",
},
{
Use: "pull --rebase origin master",
Short: "Rebase on origin master branch",
},
{
Use: "push --force-with-lease",
Short: "force push with a safety net",
},
{
Use: "stash pop",
Short: "Use most recently stashed changes",
},
{
Use: "commit -am \"",
Short: "Commit all tracked files",
},
{
Use: "commit -a --amend --no-edit",
Short: "Amend most recent commit with new changes",
},
{
Use: "commit --amend --no-edit",
Short: "Amend most recent commit with added changes",
},
{
Use: "merge --squash",
Short: "Squash and merge changes from a specified branch",
},
{
Use: "release bump",
Short: "Commit unstaged changes, bump minor tag, push",
},
{
Use: "log --oneline",
Short: "Display one commit per line",
},
{
Use: "diff --cached",
Short: "Shows all staged changes",
},
}
}
func RunScriptWithString(path string, script string, args ...string) {
var err error
err = RunInTerminalWithColor("bin/sh", args)
if err != nil {
log.Debug().Err(err)
}
}
func parseManPage(subCmd string) string {
msg, err := exec.Command("/bin/bash", "-c", "git help "+subCmd+" | col -b").CombinedOutput()
if err != nil {
log.Debug().Err(err)
}
splitA := strings.Split(string(msg), "\n\nOPTIONS")
splitB := regexp.MustCompile(`\.\n\n[A-Z]+`).Split(splitA[1], 2)
rawFlagSection := splitB[0]
//removeTabs := strings.ReplaceAll(rawFlagSection, "\t", "%%%")
//removeTabs := strings.ReplaceAll(rawFlagSection, "\n\t", "")
//removeTabs = strings.ReplaceAll(removeTabs, "%%%", "\n\n\t")
return rawFlagSection
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func isBranchCompletionCommand(command string) bool {
return command == "checkout" || command == "switch" || command == "co" || command == "merge"
}
func Find(slice []string, val string) int {
for i, item := range slice {
if item == val {
return i
}
}
return -1
}