/
entrypoint.go
74 lines (61 loc) · 2.04 KB
/
entrypoint.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
package main
import (
"errors"
"io/ioutil"
"github.com/BurntSushi/toml"
)
// processAndGenerate processes `inFile` and writes the generated `main.go` file
// contents to `outFile`. It returns an error if:
//
// - We can't read or process the input file.
// - We can't generate the `main.go` file (i.e. invalid generator).
// - We can't output the generated file.
func processAndGenerate(inFile, outFile string) error {
raw, err := ioutil.ReadFile(inFile)
if err != nil {
return err
}
var m MetaInfo
if err := toml.Unmarshal(raw, &m); err != nil {
return err
}
return generateOutFile(outFile, &m)
}
// MetaInfo contains the information needed to generate the CLI boilerplate.
// It consists of two main sections:
//
// - General info: general information about the top level CLI entrypoint.
// - Commands: information about the commands to generate.
type MetaInfo struct {
General map[string]string `toml:"general"`
Commands []map[string]interface{} `toml:"command"`
}
// CLIGenerator is the function interface that a new CLI generator needs to
// implement.
type CLIGenerator func(string, *MetaInfo) error
// Register all generators here.
var knownGenerators = map[string]CLIGenerator{
"github.com/urfave/cli": urfaveGenerator,
"github.com/abiosoft/ishell": abiosoftIShellGenerator,
}
var (
// ErrUnknownGenerator is the error returned when we try to generate a
// CLI from a config that references an unknown generator.
ErrUnknownGenerator = errors.New("unknown generator")
// ErrNoGeneratorProvided is the error that is returned when no
// generator in the `[general]` section of the found config file.
ErrNoGeneratorProvided = errors.New("no generator provided")
)
// generateOutFile calls out to the config's generator to generate the CLI
// boilerplate.
func generateOutFile(outFile string, m *MetaInfo) error {
generatorName, ok := m.General["generator"]
if !ok {
return ErrNoGeneratorProvided
}
generator, ok := knownGenerators[generatorName]
if !ok {
return ErrUnknownGenerator
}
return generator(outFile, m)
}