1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 // package cmd defines a RunFunc type, representing a process that can
6 // be invoked from a command line.
18 // A RunFunc runs a command with the given args, and returns an exit
20 type RunFunc func(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int
22 // Multi returns a RunFunc that looks up its first argument in m, and
23 // invokes the resulting RunFunc with the remaining args.
27 // os.Exit(Multi(map[string]RunFunc{
28 // "foobar": func(prog string, args []string) int {
29 // fmt.Println(args[0])
32 // })("/usr/bin/multi", []string{"foobar", "baz"}))
34 // ...prints "baz" and exits 2.
35 func Multi(m map[string]RunFunc) RunFunc {
36 return func(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
38 fmt.Fprintf(stderr, "usage: %s command [args]\n", prog)
42 if cmd, ok := m[args[0]]; !ok {
43 fmt.Fprintf(stderr, "unrecognized command %q\n", args[0])
47 return cmd(prog+" "+args[0], args[1:], stdin, stdout, stderr)
52 func multiUsage(stderr io.Writer, m map[string]RunFunc) {
53 var subcommands []string
55 if strings.HasPrefix(sc, "-") {
56 // Some subcommands have alternate versions
57 // like "--version" for compatibility. Don't
58 // clutter the subcommand summary with those.
61 subcommands = append(subcommands, sc)
63 sort.Strings(subcommands)
64 fmt.Fprintf(stderr, "\nAvailable commands:\n")
65 for _, sc := range subcommands {
66 fmt.Fprintf(stderr, " %s\n", sc)
70 type FlagSet interface {
71 Init(string, flag.ErrorHandling)
77 // SubcommandToFront silently parses args using flagset, and returns a
78 // copy of args with the first non-flag argument moved to the
79 // front. If parsing fails or consumes all of args, args is returned
82 // SubcommandToFront invokes methods on flagset that have side
83 // effects, including Parse. In typical usage, flagset will not used
84 // for anything else after being passed to SubcommandToFront.
85 func SubcommandToFront(args []string, flagset FlagSet) []string {
86 flagset.Init("", flag.ContinueOnError)
87 flagset.SetOutput(ioutil.Discard)
88 if err := flagset.Parse(args); err != nil || flagset.NArg() == 0 {
89 // No subcommand found.
92 // Move subcommand to the front.
93 flagargs := len(args) - flagset.NArg()
94 newargs := make([]string, len(args))
95 newargs[0] = args[flagargs]
96 copy(newargs[1:flagargs+1], args[:flagargs])
97 copy(newargs[flagargs+1:], args[flagargs+1:])