This repository has been archived by the owner on Jul 24, 2021. It is now read-only.
/
main.go
91 lines (75 loc) · 1.78 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
package main
import (
"flag"
"fmt"
"io"
"os"
"path"
"unicode"
)
var templateName = flag.String("name", "", "Name of the template, this will be the function name")
var inputFile = flag.String("input", "", "Template path e.g. templates/example.cote")
var outputFile = flag.String("output", "", "Compiled output path e.g. templates/example.cote.go")
func main() {
flag.Parse()
in, name := inputReader()
defer in.Close()
out := outputWriter()
defer out.Close()
if err := Convert(name, in, out); err != nil {
panic(err)
}
}
// Reads the input file from the -input flag or Stdin. Exits if
// no template name given when using stdin, or no input path given.
func inputReader() (f io.ReadCloser, name string) {
if isUsingStdin() {
if *templateName == "" {
fmt.Fprintln(os.Stderr, "Template name not specified. Use -name flag.")
os.Exit(1)
}
f = os.Stdin
name = *templateName
} else {
if *inputFile == "" {
fmt.Fprintln(os.Stderr, "Input path not specified. Use -input flag or Stdin")
os.Exit(1)
}
var err error
f, err = os.Open(*inputFile)
if err != nil {
panic(err)
}
name = *templateName
if name == "" {
name = templateNameFromFilePath(*inputFile)
}
}
return
}
// Extract a sensible template name from the file path
func templateNameFromFilePath(p string) string {
name := path.Base(p)
if ext := path.Ext(name); ext != "" {
name = name[:len(name)-len(ext)]
}
return string(unicode.ToUpper(rune(name[0]))) + name[1:]
}
func isUsingStdin() bool {
s, err := os.Stdin.Stat()
if err != nil {
panic(err)
}
return s.Size() > 0
}
// Gets an output writer, either a file or Stdout
func outputWriter() io.WriteCloser {
if *outputFile == "" {
return os.Stdout
}
w, err := os.Create(*outputFile)
if err != nil {
panic(err)
}
return w
}