-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgust.go
executable file
·712 lines (676 loc) · 18.7 KB
/
gust.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
// 2>/dev/null; e=$(mktemp); go build -o $e "$0"; $e "$@" ; r=$?; rm $e; exit $r
/*
Name: gust (Golang Universal Shell script Template)
Version: 0.1.7
Release: 1
License: CC-BA (Creative Commons By Attribution)
http://creativecommons.org/licenses/by/4.0/legalcode
Group: System
Source: N/A
URL: https://github.com/lateralblast/just
Distribution: UNIX
Vendor: UNIX
Packager: Richard Spindler <[email protected]>
Description: A template for writing golang shell scripts
*/
package main
// Import modules
import (
"strconv"
"os/exec"
"unicode"
"runtime"
"strings"
"regexp"
"bufio"
"fmt"
"os"
)
// Create a structure to manage commandline arguments/switches
type Argument struct {
info string
short string
long string
category string
function func()
}
// Initialize variables
var (
// Create a map to store default values for options
// This should contain a default value for each option created
defaults = map[string]string{
"verbose": "false",
"force": "false",
"dryrun": "false",
"doactions": "false",
"dooptions": "false",
"help": "all",
}
// Create options map
options = map[string]string{}
// Create a map of Argument structs to store commanline argument information
// This gets populated in the populate_arguments function
arguments = map[string]Argument{}
)
/*
Function: capitalize
Parameters: sentence
Description: A routine to capitalize a sentence
*/
func capitalize(sentence string) string {
var output []rune //create an output slice
isWord := true
for _, val := range sentence {
if isWord && unicode.IsLetter(val) { //check if character is a letter convert the first character to upper case
output = append(output, unicode.ToUpper(val))
isWord = false
} else if !unicode.IsLetter(val) {
isWord = true
output = append(output, val)
} else {
output = append(output, val)
}
}
sentence = string(output)
return sentence
}
/*
Function: verbose_message
Parameters: message and formet
Description: A routine to create consistently formatted output
*/
func verbose_message(message, format string) {
var header string
format = strings.ToLower(format)
format = capitalize(format)
matches, _ := regexp.MatchString("verbose", format)
if matches {
fmt.Println(message)
} else {
matches, _ = strconv.ParseBool(options["verbose"])
if matches {
matches, _ := regexp.MatchString("ing$", format)
if matches {
header = format
} else {
matches, _ := regexp.MatchString("s$|n$", format)
if matches {
header = format+"ing"
} else {
matches, _ := regexp.MatchString("t$", format)
if matches {
header = format+"ting"
} else {
matches, _ := regexp.MatchString("e$", format)
if matches {
header = string(format[:len(format)-1])
header = header+"ing"
} else {
matches, _ := regexp.MatchString("^Info$", format)
if matches {
header = "Information"
} else {
header = format
}
}
}
}
}
if len(header) < 15 {
fmt.Printf("%s:\t\t%s\n", header, message)
} else {
fmt.Printf("%s:\t%s\n", header, message)
}
}
}
}
/*
Function: warning_message
Parameters: message
Description: A routine to display a warning, overriding non verbose mode if needed
*/
func warning_message(message string) {
matches, _ := strconv.ParseBool(options["verbose"])
if matches {
verbose_message(message, "warn")
} else {
options["verbose"] = "true"
verbose_message(message, "warn")
options["verbose"] = "false"
}
}
/*
Function: check_command
Parameters: command
Description: A routine to check that a shell command exists
*/
func check_command(command string) bool {
exists := false
shell := exec.Command("command", "-v", command)
stdout, _ := shell.Output()
output := string(stdout)
matches, _ := regexp.MatchString(command, output)
if matches {
exists = true
} else {
exists = false
}
return exists
}
/*
Function: linter
Parameters: script_file
Description: A routine to run linter over script
*/
func linter() {
command := "golangci-lint"
exists := check_command(command)
if exists {
fmt.Println("Linter output:")
script_file := options["script"]
shell := exec.Command(command, "run", script_file)
stdout, _ := shell.Output()
output := string(stdout)
fmt.Println(output)
} else {
warning_message("No linter found")
}
os.Exit(0)
}
/*
Function: print_help_category
Parameters: category
Description: A routine to print help information for a specific category
*/
func print_help_category(category string) {
fmt.Printf("Usage (%s):\n", category)
fmt.Println("")
for key, argument := range arguments {
matches, _ := regexp.MatchString(category, argument.category)
if matches {
if len(key) > 1 {
if len(argument.long) <1 {
if len(argument.short) < 7 {
fmt.Printf("%s:\t\t\t%s\n", argument.short, argument.info)
} else {
fmt.Printf("%s:\t\t%s\n", argument.short, argument.info)
}
} else {
if len(argument.long) < 15 {
fmt.Printf("%s, %s:\t\t%s\n", argument.long, argument.short, argument.info)
} else {
fmt.Printf("%s, %s:\t%s\n", argument.long, argument.short, argument.info)
}
}
}
}
}
fmt.Println("")
}
/*
Function: print_help
Parameters: options
Description: A routine to print help information
*/
func help() {
switch options["help"] {
case "option", "options":
print_help_category("option")
case "switch", "switches":
print_help_category("switch")
case "action", "actions":
print_help_category("action")
case "all":
print_help_category("switch")
print_help_category("option")
print_help_category("action")
}
os.Exit(0)
}
/*
Function: version
Parameters: options
Description: A routine to print version information
*/
func version() {
script_file := options["script"]
open_file, file_error := os.Open(script_file)
if file_error != nil {
fmt.Println(file_error)
}
defer open_file.Close()
regexp := regexp.MustCompile("[0-9]")
scanner := bufio.NewScanner(open_file)
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "Version:") {
matches := regexp.MatchString(line)
if matches {
fmt.Println(line)
}
}
}
os.Exit(0)
}
/*
Function: handle_options
Parameters: values
Description: A routine to handle otions
e.g. --verbose sets the verbose option to true
e.g. --noverbose sets the verbose option to false
*/
func handle_options(values string) {
parameters := []string{}
matches, _ := regexp.MatchString(",", values)
if matches {
parameters = strings.Split(values, ",")
} else {
parameters = append(parameters, values)
}
regexp := regexp.MustCompile("^no")
for number := 0 ; number < len(parameters) ; number++ {
parameter := parameters[number]
matches := regexp.MatchString(parameter)
format := ""
if matches {
format = "disable"
parameter = strings.Split(parameter, "no")[1]
options[parameter] = "false"
} else {
format = "enable"
options[parameter] = "true"
}
verbose_message(parameter, format)
}
}
/*
Function: check_value
Parameters: arg_num
Description: A routine to handle argument values
*/
func check_value(arg_num int) {
parameter := os.Args[arg_num]
if arg_num == len(os.Args)-1 {
message := "No value given for " + parameter
switch parameter {
case "--help", "-h":
options["help"] = "all"
help()
default:
verbose_message(message, "warn")
options["help"] = "all"
help()
}
os.Exit(1)
}
check_value := os.Args[arg_num+1]
matches, _ := regexp.MatchString("^-", check_value)
if matches {
message := "No value given for " + parameter
options["verbose"] = "true"
verbose_message(message, "warn")
os.Exit(1)
} else {
message := "Value given for " + parameter + " " + check_value
verbose_message(message, "info")
matches, _ := regexp.MatchString("help|h", parameter)
if matches {
value := os.Args[arg_num+1]
options["help"] = value
help()
}
}
}
/*
Function: printenv
Parameters: none
Description: A routine to print environment variables (options)
*/
func printenv() {
fmt.Println("Environment (Options):")
fmt.Println()
regexp := regexp.MustCompile("script")
for key, value := range options {
matches := regexp.MatchString(key)
if (!matches) {
def := defaults[key]
if len(key) < 7 {
fmt.Printf("%s:\t\t%s\t(default = %s)\n", key, value, def)
} else {
fmt.Printf("%s:\t%s\t(default = %s)\n", key, value, def)
}
}
}
fmt.Println()
}
/*
Function: printdefs
Parameters: none
Description: A routine to print default environment variables (options)
*/
func printdefs() {
fmt.Println("Defaults (Options):")
fmt.Println()
for key, value := range defaults {
if len(key) < 7 {
fmt.Printf("%s:\t\t%s\n", key, value)
} else {
fmt.Printf("%s:\t%s\n", key, value)
}
}
fmt.Println()
}
func populate_arguments() {
arguments["action"] = Argument{
info: "Perform action",
short: "a",
long: "action",
category: "switch",
}
arguments["a"] = Argument{
info: "Perform action",
short: "a",
long: "action",
category: "switch",
}
arguments["option"] = Argument{
info: "Set option",
short: "o",
long: "option",
category: "switch",
}
arguments["o"] = Argument{
info: "Set option",
short: "o",
long: "option",
category: "switch",
}
arguments["dryrun"] = Argument{
info: "Enable dryrun mode",
short: "d",
long: "dryrun",
category: "option",
}
arguments["d"] = Argument{
info: "Enable dryrun mode",
short: "d",
long: "dryrun",
category: "option",
}
arguments["d"] = Argument{
info: "Print help information",
short: "h",
long: "help",
category: "switch",
}
arguments["verbose"] = Argument{
info: "Enable verbose output",
short: "v",
long: "verbose",
category: "option",
}
arguments["v"] = Argument{
info: "Enable verbose output",
short: "v",
long: "verbose",
category: "option",
}
arguments["help"] = Argument{
info: "Print help information",
short: "h",
long: "help",
category: "action",
function: func() {
help()
},
}
arguments["h"] = Argument{
info: "Print help information",
short: "h",
long: "help",
category: "action",
}
arguments["linter"] = Argument{
info: "Check script with linter",
short: "l",
long: "linter",
category: "action",
function: func() {
linter()
},
}
arguments["l"] = Argument{
info: "Check script with linter",
short: "linter",
long: "",
category: "action",
}
arguments["printdefs"] = Argument{
info: "Print Defaults",
short: "d",
long: "printdefs",
category: "action",
function: func() {
printdefs()
},
}
arguments["D"] = Argument{
info: "Print Defaults",
short: "printdefs",
long: "",
category: "action",
}
arguments["printenv"] = Argument{
info: "Print Environment",
short: "e",
long: "printenv",
category: "action",
function: func() {
printenv()
},
}
arguments["E"] = Argument{
info: "Print Environment",
short: "printenv",
long: "",
category: "action",
}
arguments["version"] = Argument{
info: "Print version information",
short: "V",
long: "version",
category: "switch",
function: func() {
version()
},
}
arguments["V"] = Argument{
info: "Print version information",
short: "V",
long: "version",
category: "switch",
}
}
// Main function
func main() {
// Get script file
_, script_file, _, _ := runtime.Caller(0)
options["script"] = script_file
populate_arguments()
// Copy defaults to options map
for key, value := range defaults {
options[key] = value
}
// Create arrays to store actions or options
action_flags := []string{}
option_flags := []string{}
// Save CLI arguments and check for verbose option
cli_args := strings.Join([]string(os.Args), " ")
matches, _ := regexp.MatchString("noverbose", cli_args)
if matches {
options["verbose"] = "false"
} else {
matches, _ := regexp.MatchString("verbose", cli_args)
if matches {
options["verbose"] = "true"
}
}
// If we have no arguments print help information
if len(os.Args) < 2 {
options["help"] = "all"
help()
}
regexp1 := regexp.MustCompile("^-[a-z,A-Z][a-z,A-Z]")
regexp2 := regexp.MustCompile("^-")
regexp3 := regexp.MustCompile("option")
regexp4 := regexp.MustCompile(",")
regexp5 := regexp.MustCompile("^no")
regexp6 := regexp.MustCompile("action|switch")
// regexp6 := regexp.MustCompile("action")
// loop through command line arguments and handle them
for arg_num := 1 ; arg_num < len(os.Args) ; arg_num++ {
arg_name := os.Args[arg_num]
// Convert plural arguments to non plural
arg_name = strings.Replace(arg_name, "options", "option", -1)
arg_name = strings.Replace(arg_name, "actions", "action", -1)
// Check if we have a -abc style switch and process
matches := regexp1.MatchString(arg_name)
if matches {
// Strip -
arg_names := strings.Split(arg_name, "-")[1]
// Step though each command line arguement, e.g. -abc > a, b, c,
letters := strings.Split(arg_names, "")
for num :=0 ; num < len(letters) ; num++ {
letter := letters[num]
_, exists := arguments[letter]
if (exists) {
long_name := arguments[letter].long
// Check that an argument structure exists and grab the long version
matches := regexp3.MatchString(arguments[letter].category)
if matches {
handle_options(long_name)
} else {
arguments[long_name].function()
}
} else {
fmt.Println(arg_name)
// Print help if there is no argument structure
message := "Commandline argument "+letter+" does not exist"
warning_message(message)
options["help"] = "all"
help()
}
}
} else {
matches := regexp2.MatchString(arg_name)
if matches {
// Strip -
arg_name = strings.Replace(arg_name, "-", "", -1)
// Check argument structure exists
_, exists := arguments[arg_name]
if exists {
// If argument structure exists check if it is an option and handle
long_name := arguments[arg_name].long
matches := regexp3.MatchString(arguments[long_name].category)
if matches {
handle_options(long_name)
} else {
_, exists := arguments[long_name]
if exists {
// If argument is not an option, handle appropriatly
switch long_name {
case "action":
check_value(arg_num)
action_flags = append(action_flags, os.Args[arg_num+1])
options["doactions"] = "true"
case "option":
check_value(arg_num)
option_flags = append(option_flags, os.Args[arg_num+1])
options["dooptions"] = "true"
case "help":
check_value(arg_num)
default:
matches := regexp6.MatchString(arguments[long_name].category)
if matches {
arguments[long_name].function()
}else {
options["help"] = "all"
help()
}
}
}
}
} else {
// check if argument is a negative option, e.g. noverbose and handle
matches := regexp5.MatchString(arg_name)
if matches {
parameter := strings.Split(arg_name, "no")[1]
matches := regexp3.MatchString(arguments[parameter].category)
if matches {
handle_options(arg_name)
} else {
// If argument structure does exist warn and print help
message := "Commandline argument "+arg_name+" does not exist"
warning_message(message)
options["help"] = "all"
help()
}
} else {
long_name := arguments[arg_name].long
matches := regexp6.MatchString(arguments[long_name].category)
if matches {
arguments[long_name].function()
} else {
// If argument structure does exist warn and print help
message := "Commandline argument "+arg_name+" does not exist"
warning_message(message)
options["help"] = "all"
help()
}
}
}
}
}
}
// If we have option(s) handle each
do_options, _ := strconv.ParseBool(options["dooptions"])
if do_options {
for number := 0 ; number < len(option_flags) ; number++ {
values := option_flags[number]
handle_options(values)
}
}
// If we have action(s) handle each
do_actions, _ := strconv.ParseBool(options["doactions"])
if do_actions {
for number := 0 ; number < len(action_flags) ; number++ {
action_list := []string{}
action_name := action_flags[number]
matches := regexp4.MatchString(action_name)
if matches {
action_list = strings.Split(action_name, ",")
} else {
action_list = append(action_list, action_name)
}
for act_num := 0 ; act_num < len(action_list) ; act_num++ {
parameter := action_list[act_num]
message := "action flag " +parameter
verbose_message(message, "process")
_, exists := arguments[parameter]
if exists {
matches := regexp6.MatchString(arguments[parameter].category)
if (matches) {
arguments[parameter].function()
} else {
options["help"] = "all"
help()
}
} else {
options["help"] = "all"
help()
}
}
}
}
os.Exit(0)
}