-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (102 loc) · 2.06 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/influxdata/kapacitor/tick"
)
const backupExt = ".orig"
var writeFlag = flag.Bool("w", false, "write formatted contents to source file instead of STDOUT.")
var backupFlag = flag.Bool("b", false, fmt.Sprintf("create backup files with extension '%s'.", backupExt))
func usage() {
message := `Usage: %s [options] [path...]
If no source files are provided reads from STDIN.
Options:
`
fmt.Fprintf(os.Stderr, message, os.Args[0])
flag.PrintDefaults()
}
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) == 0 {
if *writeFlag {
fmt.Fprintln(os.Stderr, "Cannot write source files, none given.")
flag.Usage()
os.Exit(2)
}
args = []string{"-"}
}
for _, path := range args {
path = filepath.Clean(path)
err := formatFile(path, *writeFlag, *backupFlag)
if err != nil {
log.Fatal(err)
}
}
}
func formatFile(filename string, write, backup bool) error {
data, err := readFile(filename)
if err != nil {
return err
}
formatted, err := tick.Format(data)
if err != nil {
return err
}
if write {
dir := filepath.Dir(filename)
tmp, err := writeTmpFile(dir, formatted)
if err != nil {
return err
}
defer os.Remove(tmp)
if backup {
err := os.Rename(filename, filename+backupExt)
if err != nil {
return err
}
}
err = os.Rename(tmp, filename)
if err != nil {
return err
}
} else {
_, err := os.Stdout.Write([]byte(formatted))
if err != nil {
return err
}
}
return nil
}
func readFile(filename string) (string, error) {
var f *os.File
if filename == "-" {
f = os.Stdin
} else {
var err error
f, err = os.Open(filename)
if err != nil {
return "", nil
}
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return "", nil
}
return string(data), nil
}
func writeTmpFile(dir, contents string) (string, error) {
f, err := ioutil.TempFile(dir, "tickfmt")
if err != nil {
return "", err
}
defer f.Close()
_, err = f.Write([]byte(contents))
return f.Name(), err
}