-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
128 lines (107 loc) · 2.23 KB
/
app.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package goif
import (
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"github.com/adammck/venv"
"github.com/spf13/afero"
)
const (
// EnvPrefix is the name of the ENV variable containing the grouped prefix
EnvPrefix = "GOIF_PREFIX"
)
type App struct {
fs afero.Fs
err io.Writer
prefix string
excludedPaths []string
}
func NewApp(fs afero.Fs, err io.Writer) *App {
return &App{
fs: fs,
err: err,
}
}
func (app *App) Run(prefix, exclude string, env venv.Env) {
if prefix == "" {
prefix = env.Getenv(EnvPrefix)
}
app.prefix = prefix
app.excludedPaths = strings.Split(exclude, ",")
app.traverse("./")
}
func (app *App) traverse(dirname string) {
files, err := afero.ReadDir(app.fs, dirname)
if err != nil {
app.error("reading directory", err)
return
}
for _, file := range files {
path := dirname + file.Name()
if app.isExcluded(path) {
continue
}
if file.IsDir() {
app.traverse(path + "/")
continue
}
if !strings.HasSuffix(path, ".go") {
continue
}
if err := app.formatFile(path); err != nil {
app.error(path, err)
}
}
}
func (app *App) isExcluded(path string) bool {
path = strings.TrimPrefix(path, "./")
for _, e := range app.excludedPaths {
if e == path {
return true
}
}
return false
}
func (app *App) formatFile(path string) error {
file, err := app.fs.Open(path)
if err != nil {
return err
}
defer file.Close()
safePath := strings.Replace(path, string(os.PathSeparator), "_", -1)
temp, err := ioutil.TempFile("", safePath)
if err != nil {
return err
}
defer temp.Close()
formatter := NewFormatter(app.prefix)
// format file to temp file
if err := formatter.Format(file, temp); err != nil {
// if an error occurs, scrap the temp file, return error
return err
}
// close file for reads
if err := file.Close(); err != nil {
return err
}
// reopen for write, scrapping it
file, err = app.fs.Create(path)
if err != nil {
return err
}
defer file.Close()
// reset cursor to the beginning of the file
if _, err := temp.Seek(0, 0); err != nil {
return err
}
// replace the file by the temp
if _, err := io.Copy(file, temp); err != nil {
return err
}
return nil
}
func (app *App) error(args ... interface{}) {
fmt.Fprintln(app.err, args...)
}