-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
214 lines (202 loc) · 6.24 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
214
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"privado.ai/goastgen/goastgen"
"regexp"
"runtime"
"strings"
)
var Version = "dev"
type InputConfig struct {
out string
inputPath string
excludeFiles string
includeFiles string
includePackages string
}
func main() {
inputConfig := parseArguments()
processRequest(inputConfig)
}
func processFile(out string, inputPath string, path string, info os.FileInfo, resultErr chan error, sem chan int) {
sem <- 1
defer func() {
<-sem
}()
var outFile = ""
var jsonResult string
var err error
directory := filepath.Dir(path)
if out == ".ast" {
outFile = filepath.Join(inputPath, out, strings.ReplaceAll(directory, inputPath, ""), info.Name()+".json")
} else {
outFile = filepath.Join(out, strings.ReplaceAll(directory, inputPath, ""), info.Name()+".json")
}
if strings.HasSuffix(info.Name(), ".go") {
goFile := goastgen.GoFile{File: path}
jsonResult, err = goFile.Parse()
} else if strings.HasSuffix(info.Name(), ".mod") {
var modParser = goastgen.ModFile{File: path}
jsonResult, err = modParser.Parse()
}
if err != nil {
fmt.Printf("Failed to generate AST for %s \n", path)
} else {
err = writeFileContents(outFile, jsonResult)
if err != nil {
fmt.Printf("Error writing AST to output location '%s'\n", outFile)
} else {
fmt.Printf("Converted AST for %s to %s \n", path, outFile)
}
}
resultErr <- err
}
func processRequest(input InputConfig) {
if strings.HasSuffix(input.inputPath, ".go") {
fileInfo, err := os.Stat(input.inputPath)
if err != nil {
log.SetPrefix("[ERROR]")
log.Println("Failed to get file info:", err)
fmt.Printf("Error accessing path '%s'\n", input.inputPath)
return
}
directory := filepath.Dir(input.inputPath)
var outFile = ""
if input.out == ".ast" {
outFile = filepath.Join(directory, input.out, fileInfo.Name()+".json")
} else {
outFile = filepath.Join(input.out, fileInfo.Name()+".json")
}
goFile := goastgen.GoFile{File: input.inputPath}
jsonResult, perr := goFile.Parse()
if perr != nil {
fmt.Printf("Failed to generate AST for %s\n", input.inputPath)
return
} else {
err = writeFileContents(outFile, jsonResult)
if err != nil {
fmt.Printf("Error writing AST to output location '%s'\n", outFile)
} else {
fmt.Printf("Converted AST for %s to %s\n", input.inputPath, outFile)
}
return
}
} else {
concurrency := runtime.NumCPU()
var successCount int = 0
var failCount int = 0
resultErrChan := make(chan error)
sem := make(chan int, concurrency)
var totalSentForProcessing = 0
includeFolders := getIncludePackageFolders(input)
err := filepath.Walk(input.inputPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.SetPrefix("[ERROR]")
log.Printf("Error accessing path %s: %v\n", path, err)
fmt.Printf("Error accessing path '%s'\n", path)
return err
}
if !info.IsDir() && (strings.HasSuffix(info.Name(), ".go") || strings.HasSuffix(info.Name(), ".mod")) {
fileMatched, _ := regexp.MatchString(input.excludeFiles, info.Name())
pathMatched, _ := regexp.MatchString(input.excludeFiles, path)
includePathMatched, _ := regexp.MatchString(input.includeFiles, path)
containingFolder := filepath.Dir(path)
packageMatched := includeFolders.Contains(containingFolder)
if (input.includeFiles == "" || includePathMatched == true) && (input.excludeFiles == "" || (fileMatched == false && pathMatched == false)) && (includeFolders.Size() == 0 || packageMatched) {
totalSentForProcessing++
go processFile(input.out, input.inputPath, path, info, resultErrChan, sem)
}
}
return nil
})
for i := 0; i < totalSentForProcessing; i++ {
err = <-resultErrChan
if err != nil {
failCount++
} else {
successCount++
}
}
if err != nil {
log.SetPrefix("[ERROR]")
log.Printf("Error walking the path %s: %v\n", input.inputPath, err)
}
}
}
func getIncludePackageFolders(config InputConfig) goastgen.StringSet {
packages := goastgen.StringSet{}
if strings.TrimSpace(config.includePackages) != "" {
tokens := strings.Split(config.includePackages, ",")
normalizedPrefix := strings.TrimRight(config.inputPath, `\/`)
for _, token := range tokens {
packages.Add(filepath.Join(normalizedPrefix, strings.Trim(strings.TrimSpace(token), `/`)))
}
}
return packages
}
func parseArguments() InputConfig {
var (
out string
inputPath string = ""
version bool
help bool
excludeFiles string
includeFiles string
includePackages string
)
flag.StringVar(&out, "out", ".ast", "Out put location of ast")
flag.BoolVar(&version, "version", false, "print the version")
flag.BoolVar(&help, "help", false, "print the usage")
flag.StringVar(&excludeFiles, "exclude", "", "regex to exclude files")
flag.StringVar(&includeFiles, "include", "", "regex to include files")
flag.StringVar(&includePackages, "include-packages", "", " ',' separated list of only package folders, e.g. \"/pkg/, /cmd/\". e.g. to include root package excluding sub packages e.g. \"/\"")
flag.Parse()
if version {
fmt.Println(Version)
os.Exit(0)
}
// Check if positional arguments exist
if flag.NArg() > 0 {
// Retrieve positional arguments
inputPath = flag.Arg(0)
}
if inputPath == "" || help {
fmt.Println("Usage:")
fmt.Println("\tgoastgen [falgs] <source location>")
fmt.Println()
fmt.Println("Flags:")
flag.PrintDefaults()
os.Exit(1)
}
return InputConfig{out: out, inputPath: inputPath, excludeFiles: excludeFiles, includeFiles: includeFiles, includePackages: includePackages}
}
func writeFileContents(location string, contents string) error {
// Open the file for writing (creates a new file if it doesn't exist)
dir := filepath.Dir(location)
// Create all directories recursively
err := os.MkdirAll(dir, 0755)
if err != nil {
log.SetPrefix("[ERROR]")
log.Println("Failed to create file:", err)
return err
}
file, err := os.Create(location)
if err != nil {
log.SetPrefix("[ERROR]")
log.Println("Failed to create file:", err)
return err
}
defer file.Close()
// Write the contents to the file
_, err = file.WriteString(contents)
if err != nil {
log.SetPrefix("[ERROR]")
log.Println("Failed to write to file:", err)
return err
}
return nil
}