-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroot.go
366 lines (320 loc) · 8.78 KB
/
root.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
package root
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/huh/spinner"
"github.com/gertd/go-pluralize"
"github.com/spf13/cobra"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli-plugins/plugin"
"github.com/docker/cli/cli/command"
"github.com/eunomie/docker-runx/internal/commands/cache"
"github.com/eunomie/docker-runx/internal/commands/decorate"
"github.com/eunomie/docker-runx/internal/commands/help"
"github.com/eunomie/docker-runx/internal/commands/version"
"github.com/eunomie/docker-runx/internal/constants"
"github.com/eunomie/docker-runx/internal/pizza"
"github.com/eunomie/docker-runx/internal/prompt"
"github.com/eunomie/docker-runx/internal/registry"
"github.com/eunomie/docker-runx/internal/sugar"
"github.com/eunomie/docker-runx/internal/tui"
"github.com/eunomie/docker-runx/runkit"
)
var (
docs bool
list bool
ask bool
opts []string
noFlagCheck bool
)
func NewCmd(dockerCli command.Cli, isPlugin bool) *cobra.Command {
var (
name = commandName(isPlugin)
cmd = &cobra.Command{
Use: fmt.Sprintf("%s [IMAGE] [ACTION]", name),
Short: "Docker Run, better",
RunE: func(cmd *cobra.Command, args []string) error {
var (
src string
action string
lc = runkit.GetLocalConfig()
cache = runkit.NewLocalCache(dockerCli)
)
switch len(args) {
case 0:
src = lc.Ref
if src == "" {
return cmd.Help()
}
case 1:
if lc.Ref == "" {
src = args[0]
} else {
// here we need to know if the argument is an image or an action
// there's no easy way, so what we'll do is to check if the argument is a reachable image
if registry.ImageExist(cmd.Context(), args[0]) {
// the image exist, let's say we override the default reference
src = args[0]
} else {
// we can't access the image, let's say it's an action
src = lc.Ref
action = args[0]
}
}
case 2:
src = args[0]
action = args[1]
default:
return cmd.Help()
}
var (
err error
rk *runkit.RunKit
)
if tui.IsATTY(dockerCli.In().FD()) {
err = spinner.New().
Type(spinner.Globe).
Title(" Fetching runx details...").
Action(func() {
rk, err = runkit.Get(cmd.Context(), cache, src)
if err != nil {
_, _ = fmt.Fprintln(dockerCli.Err(), err)
os.Exit(1)
}
}).Run()
} else {
rk, err = runkit.Get(cmd.Context(), cache, src)
}
if err != nil {
return err
}
if action == "" && !list && !docs && len(rk.Config.Actions) == 0 {
_, _ = fmt.Fprintln(dockerCli.Out(), tui.Markdown(rk.Readme))
return nil
}
if docs {
if action != "" {
_, _ = fmt.Fprintln(dockerCli.Out(), tui.Markdown(mdAction(rk, action)))
} else {
_, _ = fmt.Fprintln(dockerCli.Out(), tui.Markdown(rk.Readme+"\n---\n"+mdActions(rk)))
}
return nil
}
action = selectAction(action, src, rk.Config.Default)
if list || action == "" {
if tui.IsATTY(dockerCli.In().FD()) && len(rk.Config.Actions) > 0 {
selectedAction := prompt.SelectAction(rk.Config.Actions)
if selectedAction != "" {
return run(cmd.Context(), dockerCli.Err(), src, rk, selectedAction, lc)
}
} else {
_, _ = fmt.Fprintln(dockerCli.Out(), tui.Markdown(mdActions(rk)))
}
return nil
}
if action != "" {
return run(cmd.Context(), dockerCli.Err(), src, rk, action, lc)
}
return cmd.Help()
},
}
)
if isPlugin {
originalPreRunE := cmd.PersistentPreRunE
cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if err := plugin.PersistentPreRunE(cmd, args); err != nil {
return err
}
if originalPreRunE != nil {
if err := originalPreRunE(cmd, args); err != nil {
return err
}
}
return nil
}
} else {
cmd.SilenceUsage = true
cmd.SilenceErrors = true
cmd.TraverseChildren = true
cmd.DisableFlagsInUseLine = true
cli.DisableFlagsInUseLine(cmd)
}
cmd.AddCommand(
help.NewCmd(dockerCli, cmd),
version.NewCmd(dockerCli),
decorate.NewCmd(dockerCli),
cache.NewCmd(dockerCli),
)
f := cmd.Flags()
f.BoolVarP(&docs, "docs", "d", false, "Print the documentation of the image")
f.BoolVarP(&list, "list", "l", false, "List available actions")
f.BoolVar(&ask, "ask", false, "Do not read local configuration option values and always ask them")
f.StringArrayVar(&opts, "opt", nil, "Set an option value")
f.BoolVarP(&noFlagCheck, "yes", "y", false, "Do not check flags before running the command")
return cmd
}
func getValuesLocal(src, action string) map[string]string {
localOpts := make(map[string]string)
lc := runkit.GetLocalConfig()
img, ok := lc.Image(src)
if !ok {
return localOpts
}
if img.AllActions.Opts != nil {
localOpts = img.AllActions.Opts
}
act, ok := img.Actions[action]
if ok {
for k, v := range act.Opts {
localOpts[k] = v
}
}
return localOpts
}
func run(ctx context.Context, out io.Writer, src string, rk *runkit.RunKit, action string, lc *runkit.LocalConfig) error {
runnable, cleanup, err := rk.GetRunnable(action)
defer cleanup()
if err != nil {
return err
}
localOpts := map[string]string{}
if !ask {
localOpts = getValuesLocal(src, action)
for _, opt := range opts {
if key, value, ok := strings.Cut(opt, "="); ok {
localOpts[key] = value
} else {
return fmt.Errorf("invalid option value %s", opt)
}
}
}
options, err := prompt.Ask(runnable.Action, localOpts)
if err != nil {
return err
}
if err = runnable.SetOptionValues(options); err != nil {
return err
}
mdCommand := fmt.Sprintf(`
> **Running the following command:**
%s
---
`, runnable.Command)
var flags []string
if !noFlagCheck && !lc.AcceptTheRisk {
flags, err = runnable.CheckFlags()
}
if err != nil {
return err
} else if len(flags) > 0 {
_, _ = fmt.Fprintln(out, tui.Markdown(mdCommand+fmt.Sprintf(`
> **Some flags require your attention:**
%s
`, strings.Join(pizza.Map(flags, func(flag string) string {
return fmt.Sprintf("- `%s`", flag)
}), "\n"))))
var cont bool
err = huh.NewConfirm().Title("Continue?").Value(&cont).Run()
if err != nil {
return err
}
if !cont {
return errors.New("aborted")
}
} else {
_, _ = fmt.Fprintln(out, tui.Markdown(mdCommand))
}
return runnable.Run(ctx)
}
func selectAction(action, src, defaultAction string) string {
if action != "" {
return action
}
if conf, ok := runkit.GetLocalConfig().Image(src); ok && conf.Default != "" {
return conf.Default
}
return defaultAction
}
func commandName(isPlugin bool) string {
name := constants.SubCommandName
if !isPlugin {
name = constants.BinaryName
}
return name
}
func mdAction(rk *runkit.RunKit, action string) string {
var (
act runkit.Action
found bool
)
for _, a := range rk.Config.Actions {
if a.ID == action {
found = true
act = a
break
}
}
if !found {
return fmt.Sprintf("> action %q not found\n\n%s", action, mdActions(rk))
}
s := strings.Builder{}
if act.Desc != "" {
s.WriteString(fmt.Sprintf("`%s`%s: %s\n", act.ID, sugar.If(act.IsDefault(), " (default)", ""), act.Desc))
} else {
s.WriteString(fmt.Sprintf("`%s`\n", act.ID))
}
if len(act.Env) > 0 {
s.WriteString("\n- Environment " + plural("variable", len(act.Env)) + ":\n")
for _, env := range act.Env {
s.WriteString(" - `" + env + "`\n")
}
}
if len(act.Options) > 0 {
s.WriteString("\n- " + plural("Option", len(act.Options)) + ":\n")
for _, opt := range act.Options {
s.WriteString(" - `" + opt.Name + "`" + sugar.If(opt.Description != "", ": "+opt.Description, "") + "\n")
}
}
if len(act.Shell) > 0 {
s.WriteString("\n- Shell " + plural("command", len(act.Shell)) + ":\n")
for name, cmd := range act.Shell {
s.WriteString(" - `" + name + "`: `" + cmd + "`\n")
}
}
s.WriteString("\n- " + capitalizedTypes[act.Type] + " command:\n")
s.WriteString("```\n" + act.Command + "\n```\n")
return s.String()
}
var capitalizedTypes = map[runkit.ActionType]string{
runkit.ActionTypeRun: "Run",
runkit.ActionTypeBuild: "Build",
}
func mdActions(rk *runkit.RunKit) string {
s := strings.Builder{}
s.WriteString("# Available actions\n\n")
if len(rk.Config.Actions) == 0 {
s.WriteString("> No available action\n")
} else {
for _, action := range rk.Config.Actions {
if action.Desc != "" {
s.WriteString(fmt.Sprintf(" - `%s`%s: %s\n", action.ID, sugar.If(action.IsDefault(), "(default)", ""), action.Desc))
} else {
s.WriteString(fmt.Sprintf(" - `%s`\n", action.ID))
}
}
s.WriteString("\n> Use `docker runx IMAGE ACTION --docs` to get more details about an action\n")
}
return s.String()
}
func plural(str string, n int) string {
p := pluralize.NewClient()
if n > 1 {
return p.Plural(str)
}
return str
}