-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
140 lines (118 loc) · 2.44 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/url"
"os"
"path/filepath"
"strings"
)
// go build -ldflags "-X main.version=@(#)$(git describe --tags --always --dirty)"
// '@(#)' is a special tag recognized by the 'what' command
var version = "master"
func init() {
if len(version) > 0 && version[0] == '@' {
version = version[4:]
}
}
type debugFlags struct {
Trace bool
}
func (dbg debugFlags) String() string {
if dbg.Trace {
return "trace"
}
return ""
}
func (dbg *debugFlags) Set(s string) error {
if s == "" {
return nil
}
vals := strings.Split(s, ",")
for _, v := range vals {
switch v {
case "trace":
dbg.Trace = true
default:
return fmt.Errorf("invalid debug value %q", v)
}
}
return nil
}
func main() {
code, err := _main()
if err != nil {
fmt.Fprintln(os.Stderr, err)
if code == 0 {
code = 1
}
}
os.Exit(code)
}
func _main() (int, error) {
log.SetPrefix("")
log.SetFlags(0)
var showVersion bool
flag.BoolVar(&showVersion, "version", false, "show program version")
var debug debugFlags
flag.Var(&debug, "debug", "debug flags comma separated (trace=trace document navigation)")
var compactJSON bool
flag.BoolVar(&compactJSON, "c", false, "compact JSON output")
flag.BoolVar(&compactJSON, "compact-output", false, "compact JSON output")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [<option>...] <file>\nOptions:\n", os.Args[0])
flag.PrintDefaults()
os.Exit(1)
}
flag.Parse()
if showVersion {
fmt.Println(version)
return 0, nil
}
if flag.NArg() < 1 {
flag.Usage()
}
enc := json.NewEncoder(os.Stdout)
if !compactJSON {
enc.SetIndent("", " ")
}
return 0, processFile(flag.Arg(0), enc.Encode, &debug)
}
func processFile(pth string, encode func(interface{}) error, debug *debugFlags) error {
pth, err := filepath.Abs(pth)
if err != nil {
return err
}
spec, err := loadFile(pth)
if err != nil {
return err
}
var tmp interface{} = spec
var trace func(string)
if debug.Trace {
buf := append(make([]byte, 0, 1024), "[TRACE] "...)
trace = func(s string) {
buf = append(append(buf, s...), '\n')
os.Stderr.Write(buf)
buf = buf[:8]
}
}
err = ExpandRefs(&tmp, &url.URL{
//Scheme: "file",
Path: filepath.ToSlash(pth),
}, trace)
if err != nil {
return err
}
for _, transform := range []func(*interface{}) error{
CleanUnused,
} {
err = transform(&tmp)
if err != nil {
return err
}
}
return encode(tmp)
}