/
alias_generator.go
151 lines (122 loc) · 4 KB
/
alias_generator.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
package main
import (
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"log/slog"
"os"
"sort"
"strings"
"unicode"
"golang.org/x/tools/go/packages"
)
func generateAliases(inputFilePath, outputFilePath string) error {
outputPackageNameSplit := strings.Split(outputFilePath, "/")
outputPackageName := outputPackageNameSplit[len(outputPackageNameSplit)-2]
// Parse the input file
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, inputFilePath, nil, parser.ParseComments)
if err != nil {
return fmt.Errorf("parse input file: %w", err)
}
outputStringBuilder := &strings.Builder{}
fmt.Fprintf(outputStringBuilder, "// Code generated by github.com/raito-io/sdk-go/generator, DO NOT EDIT.\n\n")
pkg, err := packages.Load(&packages.Config{Mode: packages.NeedName})
if err != nil {
return fmt.Errorf("load package information: %w", err)
}
filePathSplit := strings.Split(inputFilePath, "/")
filePath := strings.Join(filePathSplit[:len(filePathSplit)-1], "/")
pkgAlias := filePathSplit[len(filePathSplit)-2]
pkgPath := pkg[0].PkgPath + "/" + filePath
constAssignments := make(map[string][]string)
// Write package declaration
fmt.Fprintf(outputStringBuilder, "package %s\n\n", outputPackageName)
// Write import statements
fmt.Fprintf(outputStringBuilder, "import %s \"%s\"\n", pkgAlias, pkgPath)
// Iterate through the file's declarations
for _, decl := range file.Decls {
if d, ok := decl.(*ast.GenDecl); ok {
if d.Tok == token.TYPE {
// Iterate through type specs
for _, spec := range d.Specs {
if ts, ok := spec.(*ast.TypeSpec); ok {
// Check if it is a struct
if unicode.IsUpper(rune(ts.Name.Name[0])) {
// Write alias declaration
fmt.Fprintf(outputStringBuilder, "type %s = %s.%s\n", ts.Name, pkgAlias, ts.Name)
}
}
}
} else if d.Tok == token.CONST {
var assignments []string
// Iterator through const specs
for _, spec := range d.Specs {
if vs, ok := spec.(*ast.ValueSpec); ok {
if it, ok := vs.Type.(*ast.Ident); ok {
for i := range vs.Names {
if unicode.IsUpper(rune(vs.Names[i].Name[0])) {
constAssignments[it.Name] = append(constAssignments[it.Name], vs.Names[i].Name)
assignments = append(assignments, fmt.Sprintf("%s %s = %s.%s", vs.Names[i].Name, it.Name, pkgAlias, vs.Names[i].Name))
}
}
}
}
}
if len(assignments) > 0 {
fmt.Fprintf(outputStringBuilder, "const (%s\n)\n\n", strings.Join(assignments, "\n\t"))
}
}
}
}
if len(constAssignments) > 0 {
fmt.Fprintf(outputStringBuilder, "\n")
keys := make([]string, 0, len(constAssignments))
for k := range constAssignments {
keys = append(keys, k)
}
sort.Strings(keys)
for _, constType := range keys {
assignments := constAssignments[constType]
fmt.Fprintf(outputStringBuilder, "var All%s = []%s{%s}\n", constType, constType, strings.Join(assignments, ", "))
}
}
// Format the output file
formattedOutput, err := format.Source([]byte(outputStringBuilder.String()))
if err != nil {
return fmt.Errorf("format generated file: %w", err)
}
// Create the output file
outputFile, err := os.Create(outputFilePath)
if err != nil {
return fmt.Errorf("create generated file: %w", err)
}
defer outputFile.Close()
// Write the formatted output to the file
_, err = outputFile.Write(formattedOutput)
if err != nil {
return fmt.Errorf("write generated file: %w", err)
}
return nil
}
func main() {
// Parse command line flags
inputFile := flag.String("input", "", "Input Go file path")
outputFile := flag.String("output", "", "Output Go file path")
flag.Parse()
// Validate input parameters
if *inputFile == "" || *outputFile == "" {
slog.Error("Usage: go run main.go -input <input_file_path> -package <output_package_name> -output <output_file_path>")
os.Exit(1)
}
// Generate aliases
err := generateAliases(*inputFile, *outputFile)
if err != nil {
slog.Error("Error:", err)
os.Exit(1)
}
slog.Info("Code generation completed successfully.")
}