forked from kaishuu0123/erd-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
erd.go
89 lines (75 loc) · 1.76 KB
/
erd.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
package main
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"syscall"
"text/template"
flags "github.com/jessevdk/go-flags"
"golang.org/x/crypto/ssh/terminal"
)
type Options struct {
InputFile string `short:"i" long:"input" description:"input will be read from the given file."`
OutputFile string `short:"o" long:"output" description:"output will be written to the given file."`
}
var opts Options
func main() {
contents := ""
logStderr := log.New(os.Stderr, "", 0)
optsParser := flags.NewParser(&opts, flags.Default)
optsParser.Name = filepath.Base(os.Args[0])
optsParser.Usage = "[OPTIONS] PATTERN [PATH]"
args, err := optsParser.Parse()
if err != nil {
logStderr.Println(err)
os.Exit(1)
}
if terminal.IsTerminal(int(syscall.Stdin)) {
if len(args) == 0 && opts.InputFile == "" {
optsParser.WriteHelp(os.Stdout)
os.Exit(1)
}
buffer, err := ioutil.ReadFile(opts.InputFile)
if err != nil {
logStderr.Println(err)
os.Exit(1)
}
contents = string(buffer)
} else {
body, err := ioutil.ReadAll(os.Stdin)
if err != nil {
logStderr.Println(err)
os.Exit(1)
}
contents = string(body)
}
parser := &Parser{Buffer: contents}
parser.Init()
err = parser.Parse()
if err != nil {
logStderr.Println(err)
os.Exit(1)
}
parser.Execute()
if parser.Erd.IsError {
os.Exit(1)
}
dot, _ := Asset("templates/dot.tmpl")
tables, _ := Asset("templates/dot_tables.tmpl")
relations, _ := Asset("templates/dot_relations.tmpl")
templates := template.Must(
template.New("").Parse(
string(dot) +
string(tables) +
string(relations)))
fd := os.Stdout
if opts.OutputFile != "" {
fd, err = os.Create(opts.OutputFile)
if err != nil {
logStderr.Println(err)
os.Exit(1)
}
}
templates.ExecuteTemplate(fd, "dot", parser.Erd)
}