-
Notifications
You must be signed in to change notification settings - Fork 83
/
cmd_template.go
101 lines (80 loc) · 2.17 KB
/
cmd_template.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
package gowrap
import (
"errors"
"fmt"
"io"
"os"
)
type writeFileFunc func(filename string, data []byte, perm os.FileMode) error
// remoteTemplateLoader returns loads template by an URL or a reference to the github repo
type remoteTemplateLoader interface {
List() ([]string, error)
Load(path string) (tmpl []byte, url string, err error)
}
// NewTemplateCommand creates TemplateCommand
func NewTemplateCommand(loader remoteTemplateLoader) *TemplateCommand {
return &TemplateCommand{
BaseCommand: BaseCommand{
Short: "manage decorators templates",
Usage: "subcommand [options]",
Help: `
Subcommands are:
list - list all template in gowrap repository
copy - copy remote template to a local file, i.e.
gowrap template copy fallback templates/fallback
`,
},
loader: loader,
}
}
// TemplateCommand implements Command interface
type TemplateCommand struct {
BaseCommand
loader remoteTemplateLoader
}
var errExpectedSubcommand = CommandLineError("expected subcommand")
var errUnknownSubcommand = CommandLineError("unknown subcommand")
// Run implements Command interface
func (gc *TemplateCommand) Run(args []string, w io.Writer) error {
if len(args) == 0 {
return errExpectedSubcommand
}
subcommand := args[0]
switch subcommand {
case "list":
return gc.list(w)
case "copy":
return gc.fetch(w, os.WriteFile, args[1:])
}
return errUnknownSubcommand
}
var errNoTemplatesFound = errors.New("no remote templates found")
func (gc *TemplateCommand) list(w io.Writer) error {
templates, err := gc.loader.List()
if err != nil {
return err
}
if len(templates) == 0 {
return errNoTemplatesFound
}
fmt.Fprintln(w, "List of available remote templates:")
for _, t := range templates {
fmt.Fprintf(w, " %s\n", t)
}
return nil
}
func (gc *TemplateCommand) fetch(w io.Writer, wf writeFileFunc, args []string) error {
if len(args) < 2 {
return CommandLineError("expected template and a local file name")
}
template, dstFileName := args[0], args[1]
body, url, err := gc.loader.Load(template)
if err != nil {
return err
}
if err := wf(dstFileName, body, 0777); err != nil {
return err
}
fmt.Fprintf(w, "successfully copied from %s\n", url)
return nil
}