-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubcommand.go
More file actions
59 lines (48 loc) · 1.27 KB
/
subcommand.go
File metadata and controls
59 lines (48 loc) · 1.27 KB
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
package main
import (
"fmt"
"io"
"log"
"os"
"github.com/SeeSpotRun/coerce"
docopt "github.com/docopt/docopt-go"
"github.com/samsalisbury/semv"
)
type subCommand interface {
description() string
docs() string
action(out, err io.Writer)
}
func run(name string, sc subCommand, args []string, toplevel map[string]interface{}) {
if err := subParseArgv(sc, args, toplevel); err != nil {
log.Fatal(err)
}
debug("subcommand: %#v", sc)
sc.action(os.Stdout, os.Stderr)
}
func fullDocs(docs string) string {
return docs + `
For common options, see 'versiontool help'
`
}
func subParseArgv(sc subCommand, argv []string, toplevel map[string]interface{}) error {
parsed, err := docopt.Parse(fullDocs(sc.docs()), argv, true, "", true)
if err != nil {
return err
}
err = coerce.Struct(sc, toplevel, "-%s", "--%s", "<%s>")
if err != nil {
return err
}
return coerce.Struct(sc, parsed, "-%s", "--%s", "<%s>")
}
func parseVersion(prefix, version string, strict bool) (semv.Version, error) {
if version[0:len(prefix)] == prefix {
version = version[len(prefix):len(version)]
} else if strict {
return semv.Version{}, fmt.Errorf("Version string: %q does not start with prefix %q", version, prefix)
}
v, err := semv.Parse(version)
debug("version parsed: %#v", v)
return v, err
}