-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
213 lines (191 loc) · 5.72 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main
import (
"bytes"
"fmt"
"go/parser"
"go/token"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/alexflint/go-arg"
"github.com/pkg/errors"
"github.com/sirkon/gosrcfmt"
parser2 "github.com/sirkon/go-imports-rename/internal/parser"
"github.com/sirkon/go-imports-rename/internal/replacer"
)
type args struct {
Root string `arg:"--root" help:"Root path to search go files in."`
Exclude []string `arg:"-x,--exclude" help:"Exclude dirs and/or files from search."`
Save bool `arg:"-s,--save" help:"Save changes."`
Rule RuleType `arg:"positional,required" help:"A rule to make import path changes"`
}
// Description of the application purpose.
func (args) Description() string {
return "A tool to change import paths based on either prefix switch or regular expressions"
}
func main() {
var inputArgs args
inputArgs.Root = "."
argParse := arg.MustParse(&inputArgs)
xclude := make(map[string]struct{}, len(inputArgs.Exclude))
for _, p := range inputArgs.Exclude {
xclude[p] = struct{}{}
}
var rep replacer.Replacer
switch v := inputArgs.Rule.Rule.(type) {
case parser2.Prefix:
rep = replacer.Prefix(v.From, v.To)
case parser2.Add:
var err error
rep, err = replacer.Versioned(v.Import, v.Jump)
if err != nil {
argParse.Fail(err.Error())
}
case parser2.Regexp:
var err error
rep, err = replacer.Regexp(v.From, v.To)
if err != nil {
argParse.Fail(err.Error())
}
}
logger := newLogger()
var changesCounter int
var actualChanges int
var filesCounter int
err := filepath.Walk(inputArgs.Root, func(path string, info os.FileInfo, err error) error {
for p := range xclude {
cut, found := strings.CutPrefix(path, p)
if !found {
continue
}
if cut == "" {
return filepath.SkipDir
}
if strings.HasPrefix(cut, string(filepath.Separator)) {
return nil
}
}
_, base := filepath.Split(path)
if info.IsDir() {
if strings.HasPrefix(base, ".") && len(base) > 1 {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") {
return nil
}
filesCounter++
fset := token.NewFileSet()
goFile, err := parser.ParseFile(fset, path, nil, parser.AllErrors|parser.ParseComments)
if err != nil {
logger.Error().Err(err).Msgf("failed to parse %s", path)
return nil
}
var localChanges int
for _, imp := range goFile.Imports {
pathValue := strings.Trim(imp.Path.Value, `"`)
rep := rep.Replace(pathValue)
switch v := rep.(type) {
case replacer.Replacement:
if !inputArgs.Save {
logger.Info().Msgf("%s: import %s => %s", path, pathValue, v.String())
} else {
imp.Path.Value = fmt.Sprintf(`"%s"`, v.String())
}
changesCounter++
localChanges++
case replacer.Nothing:
continue
default:
logger.Fatal().Msgf("invalid variant case %T", v)
}
}
if inputArgs.Save && localChanges > 0 {
// create some temporary file in
fullPath, err := getFullPath(inputArgs.Root, info.Name())
if err != nil {
logger.Error().Err(err).Msgf("failed to resolve absolute path of %s", path)
}
dir, base := filepath.Split(fullPath)
file, err := ioutil.TempFile(dir, base)
if err != nil {
logger.Error().Err(err).Msgf("failed to update %s", path)
return nil
}
formatted, err := gosrcfmt.AST(fset, goFile)
if err != nil {
logger.Error().Err(err).Msg("error when formatting a file")
return nil
}
if _, err := io.Copy(file, bytes.NewBuffer(formatted)); err != nil {
logger.Error().Err(err).Msgf("error when saving changes to %s", path)
return nil
}
if err := file.Close(); err != nil {
logger.Error().Err(err).Msgf("something went wrong for %s", path)
}
if err := os.Rename(file.Name(), path); err != nil {
logger.Error().Err(err).Msgf("failed to update %s", path)
}
actualChanges += localChanges
}
return nil
})
var filesMention string
switch filesCounter {
case 0:
logger.Warn().Msgf("no *.go files detected in %s", inputArgs.Root)
return
case 1:
filesMention = "1 *.go file"
default:
filesMention = fmt.Sprintf("%d *.go files", filesCounter)
}
if changesCounter == 0 {
logger.Info().Msgf("no changes detected in %d files", filesCounter)
} else {
if inputArgs.Save {
if actualChanges < changesCounter {
switch actualChanges {
case 0:
logger.Warn().Msgf("there were errors on saving changes, noting out of %d was commited in %s", changesCounter, filesMention)
case 1:
logger.Warn().Msgf("there were errors on saving changes, only %d out of %d was commited in %s", actualChanges, changesCounter, filesMention)
default:
logger.Warn().Msgf("there were errors on saving changes, only %d out of %d were commited in %s", actualChanges, changesCounter, filesMention)
}
} else {
switch changesCounter {
case 0:
logger.Info().Msgf("no changes were detected in %s", filesMention)
case 1:
logger.Info().Msgf("%d change was detected and commited in %s", changesCounter, filesMention)
default:
logger.Info().Msgf("%d changes were detected and commited in %s", changesCounter, filesMention)
}
}
} else {
switch changesCounter {
case 0:
logger.Info().Msgf("no changes were detected in %s", changesCounter, filesMention)
case 1:
logger.Info().Msgf("%d change was detected in %s", changesCounter, filesMention)
default:
logger.Info().Msgf("%d changes were detected in %s", changesCounter, filesMention)
}
}
}
if err != nil {
logger.Error().Err(err).Msgf("failed to scan %s directory tree", inputArgs.Root)
}
}
func getFullPath(root string, name string) (string, error) {
rootAbs, err := filepath.Abs(root)
if err != nil {
return "", errors.WithMessage(err, "full absolute path computation")
}
return filepath.Join(rootAbs, name), nil
}