-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
91 lines (78 loc) · 2.02 KB
/
command.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
package main
import (
"fmt"
"html/template"
"log"
"os"
"github.com/Pallinder/go-randomdata"
"github.com/leekchan/gtf"
"github.com/spf13/cobra"
)
// Command is the basic command structure
type Command struct {
Name string `yaml:"name"`
Aliases []string `yaml:"aliases"`
Help string `yaml:"help"`
Output string `yaml:"output"`
Commands []Command `yaml:"commands"`
Flags []Flag `yaml:"flags"`
}
func validateCommand(command Command) error {
if command.Name == "" {
return fmt.Errorf("Missing name for command: %+v", command)
}
if command.Help == "" {
return fmt.Errorf("Missing help for command: %s", command.Name)
}
return nil
}
func setCommand(command Command) *cobra.Command {
c := &cobra.Command{Use: command.Name}
if command.Help != "" {
c.Short = command.Help
c.Long = command.Help
}
if len(command.Aliases) > 0 {
c.Aliases = command.Aliases
}
if command.Output != "" {
c.Run = func(c *cobra.Command, args []string) {
funcmap := template.FuncMap{
"name": randomdata.SillyName,
"fullname": randomFullName,
"email": randomdata.Email,
"city": randomdata.City,
"street": randomdata.Street,
"address": randomdata.Address,
"number": randomdata.Number,
"paragraph": randomdata.Paragraph,
"ipaddress": randomdata.IpV4Address,
"day": randomdata.Day,
"month": randomdata.Month,
"date": randomdata.FullDate,
"string": toString,
"bool": toBool,
"int": toInt,
"float": toFloat,
"count": count,
}
gtf.Inject(funcmap)
data := struct {
Flags map[string]Flag
Args []string
}{
Flags: flags,
Args: args,
}
t, err := template.New("output").Funcs(funcmap).Parse(command.Output)
if err != nil {
log.Fatalf("Error parsing %s output: %s", command.Name, err.Error())
}
err = template.Must(t, err).Execute(os.Stdout, data)
if err != nil {
log.Fatalf("Error parsing %s output: %s", command.Name, err.Error())
}
}
}
return c
}