-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
98 lines (86 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
// Copyright (c) 2020, Alliance for Sustainable Energy, LLC.
// All rights reserved.
// Package main runs the formatter
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
var (
write = flag.Bool("w", false, "overwrite the file(s)")
versionFlag = flag.Bool("v", false, "display tool version")
emptyLineFlag = flag.Bool("extra-padding", false, "BETA: adds empty lines for padding")
lineLength = flag.Int("line-length", -1, "how many characters allowed per line; -1 means no max")
// build information added by goreleaser
version = "dev"
commit = "none"
date = "unknown"
builtBy = "unknown"
)
func usage() {
fmt.Fprintln(os.Stderr, "usage: modelicafmt [path ...]")
flag.PrintDefaults()
}
func isModelicaFile(f os.FileInfo) bool {
name := f.Name()
return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".mo")
}
func processAndWriteFile(filename string) {
var b bytes.Buffer
err := processFile(filename, bufio.NewWriter(&b), Config{*lineLength, *emptyLineFlag})
if err != nil {
panic(err)
}
if *write {
err := ioutil.WriteFile(filename, b.Bytes(), 777)
if err != nil {
panic(err)
}
} else {
b.WriteTo(os.Stdout)
}
}
func visitFile(filename string, f os.FileInfo, err error) error {
if err != nil && !os.IsNotExist(err) {
fmt.Fprintln(os.Stderr, err.Error())
return nil
}
if isModelicaFile(f) {
processAndWriteFile(filename)
}
return nil
}
func walkDir(path string) {
filepath.Walk(path, visitFile)
}
func main() {
flag.Usage = usage
flag.Parse()
if *versionFlag {
fmt.Printf("modelicafmt v%s (SHA %s)\nBuilt %s by %s\n", version, commit, date, builtBy)
return
}
if flag.NArg() == 0 {
fmt.Fprintln(os.Stderr, "error: must provide at least one file or directory")
usage()
os.Exit(2)
}
for i := 0; i < flag.NArg(); i++ {
path := flag.Arg(i)
switch dir, err := os.Stat(path); {
case err != nil:
fmt.Fprintln(os.Stderr, "error: "+err.Error())
os.Exit(2)
case dir.IsDir():
walkDir(path)
default:
processAndWriteFile(path)
}
}
}