1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 // Package cmd helps define reusable functions that can be exposed as
6 // [subcommands of] command line programs.
21 type Handler interface {
22 RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int
25 type HandlerFunc func(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int
27 func (f HandlerFunc) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
28 return f(prog, args, stdin, stdout, stderr)
31 // Version is a Handler that prints the package version (set at build
32 // time using -ldflags) and Go runtime version to stdout, and returns
34 var Version versionCommand
38 type versionCommand struct{}
40 func (versionCommand) String() string {
41 return fmt.Sprintf("%s (%s)", version, runtime.Version())
44 func (versionCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
45 prog = regexp.MustCompile(` -*version$`).ReplaceAllLiteralString(prog, "")
46 fmt.Fprintf(stdout, "%s %s (%s)\n", prog, version, runtime.Version())
50 // Multi is a Handler that looks up its first argument in a map (after
51 // stripping any "arvados-" or "crunch-" prefix), and invokes the
52 // resulting Handler with the remaining args.
56 // os.Exit(Multi(map[string]Handler{
57 // "foobar": HandlerFunc(func(prog string, args []string) int {
58 // fmt.Println(args[0])
61 // })("/usr/bin/multi", []string{"foobar", "baz"}))
63 // ...prints "baz" and exits 2.
64 type Multi map[string]Handler
66 func (m Multi) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
67 _, basename := filepath.Split(prog)
68 if i := strings.Index(basename, "~"); i >= 0 {
69 // drop "~anything" suffix (arvados-dispatch-cloud's
70 // DeployRunnerBinary feature relies on this)
71 basename = basename[:i]
73 cmd, ok := m[basename]
75 // "controller" command exists, and binary is named "arvados-controller"
76 cmd, ok = m[strings.TrimPrefix(basename, "arvados-")]
79 // "dispatch-slurm" command exists, and binary is named "crunch-dispatch-slurm"
80 cmd, ok = m[strings.TrimPrefix(basename, "crunch-")]
83 return cmd.RunCommand(prog, args, stdin, stdout, stderr)
84 } else if len(args) < 1 {
85 fmt.Fprintf(stderr, "usage: %s command [args]\n", prog)
88 } else if cmd, ok = m[args[0]]; ok {
89 return cmd.RunCommand(prog+" "+args[0], args[1:], stdin, stdout, stderr)
91 fmt.Fprintf(stderr, "%s: unrecognized command %q\n", prog, args[0])
97 func (m Multi) Usage(stderr io.Writer) {
98 fmt.Fprintf(stderr, "\nAvailable commands:\n")
99 m.listSubcommands(stderr, "")
102 func (m Multi) listSubcommands(out io.Writer, prefix string) {
103 var subcommands []string
105 if strings.HasPrefix(sc, "-") {
106 // Some subcommands have alternate versions
107 // like "--version" for compatibility. Don't
108 // clutter the subcommand summary with those.
111 subcommands = append(subcommands, sc)
113 sort.Strings(subcommands)
114 for _, sc := range subcommands {
115 switch cmd := m[sc].(type) {
117 cmd.listSubcommands(out, prefix+sc+" ")
119 fmt.Fprintf(out, " %s%s\n", prefix, sc)
124 type FlagSet interface {
125 Init(string, flag.ErrorHandling)
128 Parse([]string) error
133 // SubcommandToFront silently parses args using flagset, and returns a
134 // copy of args with the first non-flag argument moved to the
135 // front. If parsing fails or consumes all of args, args is returned
138 // SubcommandToFront invokes methods on flagset that have side
139 // effects, including Parse. In typical usage, flagset will not used
140 // for anything else after being passed to SubcommandToFront.
141 func SubcommandToFront(args []string, flagset FlagSet) []string {
142 flagset.Init("", flag.ContinueOnError)
143 flagset.SetOutput(ioutil.Discard)
144 if err := flagset.Parse(args); err != nil || flagset.NArg() == 0 {
145 // No subcommand found.
148 // Move subcommand to the front.
149 flagargs := len(args) - flagset.NArg()
150 newargs := make([]string, len(args))
151 newargs[0] = args[flagargs]
152 copy(newargs[1:flagargs+1], args[:flagargs])
153 copy(newargs[flagargs+1:], args[flagargs+1:])