-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
executable file
·90 lines (78 loc) · 1.97 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
// Copyright (C) 2019 Leandro Lisboa Penz <lpenz@lpenz.org>
// This file is subject to the terms and conditions defined in
// file 'LICENSE', which is part of this source code package.
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"reflect"
"strings"
"text/template"
"../../common"
)
type jsonsFlags []string
func (i *jsonsFlags) String() string {
return "my string representation"
}
func (i *jsonsFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
var myJsonsFlags jsonsFlags
func cmdLineParse() ([]string, string, string, error) {
flag.Var(&myJsonsFlags, "json", "json to import into scope")
flag.Parse()
if flag.NFlag() > 3 || flag.NFlag() < 1 {
empty := []string{}
return empty, "", "", fmt.Errorf("could not parse %s", os.Args)
}
output := "-"
if flag.NFlag() == 1 {
output = flag.Arg(1)
}
return myJsonsFlags, flag.Arg(0), output, nil
}
func strTypeOf(x interface{}) string {
return reflect.TypeOf(x).String()
}
func isNil(x interface{}) bool {
return x == nil
}
func mkSlice(args ...interface{}) []interface{} {
return args
}
func main() {
jsonfilenames, tmplfilename, outfilename, err := cmdLineParse()
common.PanicIf(err)
info := map[string]interface{}{}
for _, jsonfilename := range jsonfilenames {
jsonString, err := ioutil.ReadFile(jsonfilename)
common.PanicIf(err)
var tmp map[string]interface{}
err = json.Unmarshal(jsonString, &tmp)
for k, v := range tmp {
info[k] = v
}
common.PanicIf(err)
}
t, err := template.New("").Funcs(template.FuncMap{
"stringsIndex": strings.Index,
"ToLower": strings.ToLower,
"typeOf": strTypeOf,
"isNil": isNil,
"mkSlice": mkSlice,
}).ParseFiles(tmplfilename)
common.PanicIf(err)
if outfilename != "-" {
outfile, err := os.Create(outfilename)
common.PanicIf(err)
err = t.ExecuteTemplate(outfile, tmplfilename, info)
common.PanicIf(err)
} else {
err = t.ExecuteTemplate(os.Stdout, tmplfilename, info)
common.PanicIf(err)
}
}