-
Notifications
You must be signed in to change notification settings - Fork 5
/
cli.go
88 lines (74 loc) · 1.53 KB
/
cli.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
package make2help
import (
"fmt"
"io"
"os"
"regexp"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
)
const version = "0.1.0"
var revision = "HEAD"
const (
exitCodeOK = iota
exitCodeParseFlagError
exitCodeErr
)
// CLI is struct for command line tool
type CLI struct {
OutStream, ErrStream io.Writer
}
// Run the make2help
func (cli *CLI) Run(argv []string) int {
argv, isHelp, all := parseFlags(argv)
if isHelp {
fmt.Fprintln(cli.ErrStream, help())
return exitCodeOK
}
if len(argv) < 1 {
argv = []string{"Makefile"}
}
colorful := false
if w, ok := cli.OutStream.(*os.File); ok {
colorful = isatty.IsTerminal(w.Fd())
cli.OutStream = colorable.NewColorable(w)
}
r := rules{}
for _, f := range argv {
tmpRule, err := scan(f)
if err != nil {
fmt.Fprintln(cli.ErrStream, err)
return exitCodeErr
}
r = r.merge(tmpRule)
}
fmt.Fprint(cli.OutStream, r.string(all, colorful))
return exitCodeOK
}
var (
helpReg = regexp.MustCompile(`^--?h(?:elp)?$`)
allReg = regexp.MustCompile(`^--?all$`)
)
func parseFlags(argv []string) (restArgv []string, isHelp, isAll bool) {
for _, v := range argv {
if helpReg.MatchString(v) {
isHelp = true
return
}
if allReg.MatchString(v) {
isAll = true
continue
}
restArgv = append(restArgv, v)
}
return
}
func help() string {
return fmt.Sprintf(`Usage:
$ make2help [Makefiles]
Utility for self-documented Makefile
It shows rules in Makefiles with documents.
Options:
-all display all rules in the Makefiles
Version: %s`, version)
}