-
Notifications
You must be signed in to change notification settings - Fork 3
/
script.go
85 lines (74 loc) · 1.85 KB
/
script.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
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"strings"
"github.com/hexops/cmder"
"github.com/hexops/wrench/internal/errors"
"github.com/hexops/wrench/internal/wrench/scripts"
)
func init() {
usage := `wrench script: run a script built-in to wrench
Usage:
wrench script <command> [arguments]
The scripts are:
`
maxCmdStrLen := 0
for _, script := range scripts.Scripts {
cmdStr := script.Command
if len(script.Args) > 0 {
cmdStr = fmt.Sprintf("%s [%s]", cmdStr, strings.Join(script.Args, "] ["))
}
if len(cmdStr) > maxCmdStrLen {
maxCmdStrLen = len(cmdStr)
}
}
for _, script := range scripts.Scripts {
cmdStr := script.Command
if len(script.Args) > 0 {
cmdStr = fmt.Sprintf("%s [%s]", cmdStr, strings.Join(script.Args, "] ["))
}
usage = fmt.Sprintf("%s\n %-"+fmt.Sprint(maxCmdStrLen+2)+"s%s", usage, cmdStr, script.Description)
}
usage += "\n\n"
// Parse flags for our subcommand.
flagSet := flag.NewFlagSet("script", flag.ExitOnError)
// Handles calls to our subcommand.
handler := func(args []string) error {
_ = flagSet.Parse(args)
if len(args) < 1 {
return &cmder.UsageError{Err: errors.New("expected command")}
}
for _, script := range scripts.Scripts {
if args[0] != script.Command {
continue
}
resp, err := script.Run(args[1:]...)
if err != nil {
return err
}
if resp != nil {
data, err := json.MarshalIndent(resp, "", " ")
if err != nil {
return errors.Wrap(err, "Marshal")
}
fmt.Fprintf(os.Stdout, "%s\n", data)
}
return nil
}
return nil
}
// Register the command.
commands = append(commands, &cmder.Command{
FlagSet: flagSet,
Aliases: []string{},
Handler: handler,
UsageFunc: func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'wrench %s':\n", flagSet.Name())
flagSet.PrintDefaults()
fmt.Printf("%s", usage)
},
})
}