-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
100 lines (85 loc) · 2.23 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
// Copyright 2017 aaharu All rights reserved.
// This source code is licensed under the 2-clause BSD license found in
// the LICENSE file in the root directory of this source tree.
// This source code use following software(s):
// - golang.org/x/crypto/ssh/terminal
// Copyright 2011 The Go Authors.
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"syscall"
"golang.org/x/crypto/ssh/terminal"
"github.com/aaharu/schemarshal/codegen"
"github.com/aaharu/schemarshal/cui"
"github.com/aaharu/schemarshal/utils"
"github.com/aaharu/schemarshal/version"
)
func main() {
args := cui.ParseArguments()
if args.ShowVersion {
fmt.Println(version.String())
os.Exit(0)
}
var input io.Reader
typeName := args.TypeName
if args.InputFileName != "" || terminal.IsTerminal(int(syscall.Stdin)) {
// input from file
if args.InputFileName == "" && len(flag.Args()) < 1 {
cui.Usage()
os.Exit(1)
}
inputFileName := args.InputFileName
if inputFileName == "" {
inputFileName = flag.Args()[0]
}
inputFile, err := os.Open(inputFileName)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open schema: %s\n", err)
os.Exit(1)
}
defer inputFile.Close()
if typeName == "" {
typeName = utils.FileName(inputFile)
}
input = inputFile
} else {
// input from pipe
stdin, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to read input: %s\n", err)
os.Exit(1)
}
if typeName == "" {
// default type name
typeName = "SchemarshalType"
}
input = strings.NewReader(string(stdin))
}
codeGenerator := codegen.NewGenerator(args.PackageName, strings.Trim(fmt.Sprintf("%v", os.Args), "[]"))
if err := codeGenerator.ReadSchema(input, typeName); err != nil {
fmt.Fprintf(os.Stderr, "failed to parse: %s\n", err)
os.Exit(1)
}
src, err := codeGenerator.Generate(args.NoComment)
if err != nil {
fmt.Println(string(src))
fmt.Fprintf(os.Stderr, "failed to generate: %s\n", err)
os.Exit(1)
}
if args.OutputFileName == "" {
fmt.Println(string(src))
} else {
outputFile, err := os.Create(args.OutputFileName)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to write file: %s\n", err)
os.Exit(1)
}
outputFile.Write(src)
outputFile.Close()
}
}