-
Notifications
You must be signed in to change notification settings - Fork 36
/
commands.go
344 lines (289 loc) · 9.69 KB
/
commands.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
package commands
import (
"fmt"
"os"
"runtime"
"strings"
"github.com/enfabrica/enkit/astore/client/astore"
castore "github.com/enfabrica/enkit/astore/client/astore"
arpc "github.com/enfabrica/enkit/astore/rpc/astore"
"github.com/enfabrica/enkit/lib/client"
"github.com/enfabrica/enkit/lib/config"
"github.com/enfabrica/enkit/lib/config/defcon"
"github.com/enfabrica/enkit/lib/config/marshal"
"github.com/enfabrica/enkit/lib/kflags"
"github.com/enfabrica/enkit/lib/kflags/kcobra"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
var (
formatterMap = map[string]castore.Formatter{
"json": NewStructuredStdout(&marshal.JsonEncoder{}),
"toml": NewStructuredStdout(&marshal.TomlEncoder{}),
"yaml": NewStructuredStdout(&marshal.YamlEncoder{}),
"gob": NewStructuredStdout(&marshal.GobEncoder{}),
}
)
type Root struct {
*cobra.Command
*client.BaseFlags
store *client.ServerFlags
outputFile string
consoleFormat string
}
func New(base *client.BaseFlags) *Root {
root := NewRoot(base)
root.AddCommand(NewDownload(root).Command)
root.AddCommand(NewUpload(root).Command)
root.AddCommand(NewList(root).Command)
root.AddCommand(NewGuess(root).Command)
root.AddCommand(NewTag(root).Command)
root.AddCommand(NewNote(root).Command)
root.AddCommand(NewPublic(root).Command)
return root
}
func NewRoot(base *client.BaseFlags) *Root {
rc := &Root{
Command: &cobra.Command{
Use: "astore",
Short: "Push, pull, and publish build artifacts",
SilenceUsage: true,
SilenceErrors: true,
Example: ` $ astore login carlo@enfabrica.net
To obtain credentials to store/retrieve artifacts.
$ astore upload build.out
To upload a file in the artifact repository.
$ astore upload build.out@experiments/builds/
Same as above, stores the file in experiments/build.
$ astore download experiments/builds/build.out
Downloads the latest version of build.out.
$ astore --help
To have a nice help screen.`,
Long: `astore - uploads and downloads artifacts`,
},
BaseFlags: base,
store: client.DefaultServerFlags("store", "Artifacts store metadata server", ""),
}
rc.store.Register(&kcobra.FlagSet{FlagSet: rc.PersistentFlags()}, "")
rc.Command.PersistentFlags().StringVarP(&rc.outputFile, "meta-file", "m", "",
fmt.Sprintf("Meta-data output file. Supported formats: %s", marshal.Formats()))
rc.Command.PersistentFlags().StringVar(
&rc.consoleFormat,
"console-format",
"table",
fmt.Sprintf("Format to use for stdout output. Supported formats: %s", append([]string{"table"}, marshal.Formats()...)),
)
return rc
}
func (rc *Root) StoreClient() (*astore.Client, error) {
if rc.outputFile != "" {
// check output file type is supported
marshaller := marshal.ByExtension(rc.outputFile)
if marshaller == nil {
return nil, fmt.Errorf("Output file extension not supported `%s`. Supported formats: %s",
rc.outputFile, marshal.Formats())
}
// check that the destination is writable
file, err := os.Create(rc.outputFile)
if err != nil {
return nil, fmt.Errorf("Problems creating output file `%s` - %w", rc.outputFile, err)
}
file.Close()
}
_, cookie, err := rc.IdentityCookie()
if err != nil {
return nil, err
}
storeconn, err := rc.store.Connect(client.WithCookie(cookie))
if err != nil {
return nil, err
}
return astore.New(storeconn), nil
}
func (rc *Root) Formatter(mods ...Modifier) astore.Formatter {
// The table formatter doesn't follow the same interface as the others, and
// can't be constructed until this point. This code should only be called once
// per command, making modification of this global OK; even so, it overwrites
// the "table" value each time so should behave as expected.
formatterMap["table"] = NewTableFormatter(mods...)
formatterList := NewFormatterList()
if format, ok := formatterMap[strings.ToLower(rc.consoleFormat)]; ok {
formatterList.Append(format)
} else {
// Fall back to the table formatter
formatterList.Append(formatterMap["table"])
}
if rc.outputFile != "" {
// add a marshal-aware formatter
formatterList.Append(NewOpFile(rc.outputFile))
}
return formatterList
}
func (rc *Root) OutputArtifacts(arts []*arpc.Artifact) {
formatter := rc.Formatter(WithNoNesting)
for _, art := range arts {
formatter.Artifact(art)
}
formatter.Flush()
}
func (rc *Root) ConfigStore(namespace ...string) (config.Store, error) {
return defcon.Open("astore", namespace...)
}
type Download struct {
*cobra.Command
root *Root
ForceUid bool
ForcePath bool
Output string
Overwrite bool
Arch string
Tag []string
}
func SystemArch() string {
return strings.ToLower(runtime.GOARCH + "-" + runtime.GOOS)
}
func NewDownload(root *Root) *Download {
command := &Download{
Command: &cobra.Command{
Use: "download",
Short: "Downloads an artifact",
Aliases: []string{"down", "get", "pull", "fetch"},
},
root: root,
}
command.Command.RunE = command.Run
command.Flags().BoolVarP(&command.ForceUid, "force-uid", "u", false, "The argument specified identifies an uid")
command.Flags().BoolVarP(&command.ForcePath, "force-path", "p", false, "The argument specified identifies a file path")
command.Flags().StringVarP(&command.Output, "output", "o", ".", "Where to output the downloaded files. If multiple files are supplied, a directory with this name will be created")
command.Flags().BoolVarP(&command.Overwrite, "overwrite", "w", false, "Overwrite files that already exist")
command.Flags().StringArrayVarP(&command.Tag, "tag", "t", []string{"latest"}, "Download artifacts matching the tag specified. More than one tag can be specified")
command.Flags().StringVarP(&command.Arch, "arch", "a", SystemArch(), "Architecture to download the file for")
return command
}
func (dc *Download) Run(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return kflags.NewUsageErrorf("use as 'astore download <path|uid>...' - one or more paths to download")
}
if dc.ForceUid && dc.ForcePath {
return kflags.NewUsageErrorf("cannot specify --force-uid together with --force-path - an argument can be either one, but not both")
}
mode := astore.IdAuto
if dc.ForceUid {
mode = astore.IdUid
}
if dc.ForcePath {
mode = astore.IdPath
}
var archs []string
switch strings.TrimSpace(dc.Arch) {
case "":
fallthrough
case "all":
archs = []string{"all"}
default:
archs = []string{dc.Arch, "all"}
}
// If there are multiple files to download, the output must be a directory.
// Append a trailing '/' so one will be created if necessary.
output := dc.Output
if len(args) > 1 && output != "" {
output = output + "/"
}
ftd := []astore.FileToDownload{}
for _, name := range args {
file := astore.FileToDownload{
Remote: name,
RemoteType: mode,
Local: output,
Overwrite: dc.Overwrite,
Architecture: archs,
Tag: &dc.Tag,
}
ftd = append(ftd, file)
}
dc.root.Log.Debugf("Files to download: %+v", ftd)
client, err := dc.root.StoreClient()
if err != nil {
return err
}
arts, err := client.Download(ftd, astore.DownloadOptions{
Context: dc.root.BaseFlags.Context(),
})
if err != nil && os.IsExist(err) {
return fmt.Errorf("file already exists? To overwrite, pass the -w or --overwrite flag - %s", err)
}
formatter := dc.root.Formatter()
for _, art := range arts {
formatter.Artifact(art)
}
return err
}
type List struct {
*cobra.Command
root *Root
Tag []string
All bool
}
func NewList(root *Root) *List {
command := &List{
Command: &cobra.Command{
Use: "list",
Short: "Shows artifacts",
Aliases: []string{"list", "show", "ls", "find"},
},
root: root,
}
command.Command.RunE = command.Run
command.Flags().StringArrayVarP(&command.Tag, "tag", "t", []string{"latest"}, "Restrict the output to artifacts having this tag")
command.Flags().BoolVarP(&command.All, "all", "l", false, "Show all binaries")
return command
}
func (l *List) Run(cmd *cobra.Command, args []string) error {
if len(args) > 1 {
return kflags.NewUsageErrorf("use as 'astore list [PATH]' - with a single, optional, PATH argument (got %d arguments)", len(args))
}
query := ""
if len(args) == 1 {
query = args[0]
}
client, err := l.root.StoreClient()
if err != nil {
return err
}
tags := l.Tag
if l.All {
tags = []string{}
}
options := astore.ListOptions{
Context: l.root.BaseFlags.Context(),
Tag: tags,
}
arts, els, err := client.List(query, options)
if err != nil {
return err
}
formatter := l.root.Formatter()
for _, art := range arts {
formatter.Artifact(art)
}
if !l.All && len(arts) >= 1 {
fmt.Printf("(only showing artifacts with %d tags: %v - use --all or -l to show all)\n", len(l.Tag), l.Tag)
}
for _, el := range els {
formatter.Element(el)
}
formatter.Flush()
return nil
}
type SuggestFlags astore.SuggestOptions
func (sf *SuggestFlags) Register(flagset *pflag.FlagSet) {
flagset.StringVarP(&sf.Directory, "directory", "d", "", "Remote directory where to upload each file. If not specified explicitly, a path will be guessed using other heuristics")
flagset.StringVarP(&sf.File, "file", "f", "", "Remote file name where to store all files. This is useful when uploading multiple files of different architectures")
flagset.BoolVarP(&sf.DisableGit, "disable-git", "G", false, "Don't use the git repository to name the remote file")
flagset.BoolVarP(&sf.DisableAt, "disable-at", "A", false, "Don't use the @ convention to name the remote file")
flagset.BoolVarP(&sf.AllowAbsolute, "allow-absolute", "b", false, "Allow absolute local paths to name remote paths")
flagset.BoolVarP(&sf.AllowSingleElement, "allow-single", "l", false, "Allow a single element path to be used as remote")
}
func (sf *SuggestFlags) Options() *astore.SuggestOptions {
return (*astore.SuggestOptions)(sf)
}