Debian Codegraph @

tygoja.go

raw symbols SCIP
1 package tygoja
2
3 import (
4 "fmt"
5 "path/filepath"
6 "regexp"
7 "strings"
8
9 "golang.org/x/tools/go/packages"
10 )
11
12 // Tygoja is a generator for one or more input packages,
13 // responsible for linking them together if necessary.
14 type Tygoja struct {
15 conf *Config
16
17 parent *Tygoja
18 implicitPackages map[string][]string
19 generatedTypes map[string][]string
20 generatedPackageDocs map[string]struct{}
21 }
22
23 // New initializes a new Tygoja generator from the specified config.
24 func New(config Config) *Tygoja {
25 config.InitDefaults()
26
27 return &Tygoja{
28 conf: &config,
29 implicitPackages: map[string][]string{},
30 generatedTypes: map[string][]string{},
31 generatedPackageDocs: map[string]struct{}{},
32 }
33 }
34
35 // Generate executes the generator and produces the related TS files.
36 func (g *Tygoja) Generate() (string, error) {
37 // extract config packages
38 configPackages := make([]string, 0, len(g.conf.Packages))
39 for p, types := range g.conf.Packages {
40 if len(types) == 0 {
41 continue // no typings
42 }
43 configPackages = append(configPackages, p)
44 }
45
46 // load packages info
47 pkgs, err := packages.Load(&packages.Config{
48 Mode: packages.NeedSyntax | packages.NeedFiles | packages.NeedDeps | packages.NeedImports | packages.NeedTypes,
49 }, configPackages...)
50 if err != nil {
51 return "", err
52 }
53
54 var s strings.Builder
55
56 // Heading
57 if g.parent == nil {
58 s.WriteString("// GENERATED CODE - DO NOT MODIFY BY HAND\n")
59
60 if g.conf.Heading != "" {
61 s.WriteString(g.conf.Heading)
62 }
63
64 // write base types
65 // ---
66 s.WriteString("type ")
67 s.WriteString(BaseTypeDict)
68 s.WriteString(" = { [key:string | number | symbol]: any; }\n")
69
70 s.WriteString("type ")
71 s.WriteString(BaseTypeAny)
72 s.WriteString(" = any\n")
73 // ---
74 }
75
76 for i, pkg := range pkgs {
77 if len(pkg.Errors) > 0 {
78 return "", fmt.Errorf("%+v", pkg.Errors)
79 }
80
81 if len(pkg.GoFiles) == 0 {
82 return "", fmt.Errorf("no input go files for package index %d", i)
83 }
84
85 if len(g.conf.Packages[pkg.ID]) == 0 {
86 // ignore the package as it has no typings
87 continue
88 }
89
90 pkgGen := &PackageGenerator{
91 conf: g.conf,
92 pkg: pkg,
93 types: g.conf.Packages[pkg.ID],
94 withPkgDoc: !g.isPackageDocGenerated(pkg.ID),
95 generatedTypes: map[string]struct{}{},
96 unknownTypes: map[string]struct{}{},
97 imports: map[string][]string{},
98 }
99
100 code, err := pkgGen.Generate()
101 if err != nil {
102 return "", err
103 }
104
105 g.generatedPackageDocs[pkg.ID] = struct{}{}
106
107 for t := range pkgGen.generatedTypes {
108 g.generatedTypes[pkg.ID] = append(g.generatedTypes[pkg.ID], t)
109 }
110
111 for t := range pkgGen.unknownTypes {
112 parts := strings.Split(t, ".")
113 var tPkg string
114 var tName string
115
116 if len(parts) == 0 {
117 continue
118 }
119
120 if len(parts) == 2 {
121 // type from external package
122 tPkg = parts[0]
123 tName = parts[1]
124 } else {
125 // unexported type from the current package
126 tName = parts[0]
127
128 // already mapped for export
129 if pkgGen.isTypeAllowed(tName) {
130 continue
131 }
132
133 tPkg = packageNameFromPath(pkg.ID)
134
135 // add to self import later
136 pkgGen.imports[pkg.ID] = []string{tPkg}
137 }
138
139 for p, aliases := range pkgGen.imports {
140 for _, alias := range aliases {
141 if tName != "" && alias == tPkg && !g.isTypeGenerated(p, tName) && !exists(g.implicitPackages[p], tName) {
142 if g.implicitPackages[p] == nil {
143 g.implicitPackages[p] = []string{}
144 }
145 g.implicitPackages[p] = append(g.implicitPackages[p], tName)
146 break
147 }
148 }
149 }
150 }
151
152 s.WriteString(code)
153 }
154
155 // recursively try to generate the found unknown types
156 if len(g.implicitPackages) > 0 {
157 subConfig := *g.conf
158 subConfig.Heading = ""
159 if (subConfig.TypeMappings) == nil {
160 subConfig.TypeMappings = map[string]string{}
161 }
162
163 // extract the nonempty package definitions
164 subConfig.Packages = make(map[string][]string, len(g.implicitPackages))
165 for p, types := range g.implicitPackages {
166 if len(types) == 0 {
167 continue
168 }
169 subConfig.Packages[p] = types
170 }
171
172 subGenerator := New(subConfig)
173 subGenerator.parent = g
174 subResult, err := subGenerator.Generate()
175 if err != nil {
176 return "", err
177 }
178
179 s.WriteString(subResult)
180 }
181
182 return s.String(), nil
183 }
184
185 func (g *Tygoja) isPackageDocGenerated(pkgId string) bool {
186 _, ok := g.generatedPackageDocs[pkgId]
187 if ok {
188 return true
189 }
190
191 if g.parent != nil {
192 return g.parent.isPackageDocGenerated(pkgId)
193 }
194
195 return false
196 }
197
198 func (g *Tygoja) isTypeGenerated(pkg string, name string) bool {
199 if g.parent != nil && g.parent.isTypeGenerated(pkg, name) {
200 return true
201 }
202
203 if len(g.generatedTypes[pkg]) == 0 {
204 return false
205 }
206
207 for _, t := range g.generatedTypes[pkg] {
208 if t == name {
209 return true
210 }
211 }
212
213 return false
214 }
215
216 // isTypeAllowed checks whether the provided type name is allowed by the generator "types".
217 func (g *PackageGenerator) isTypeAllowed(name string) bool {
218 name = strings.TrimSpace(name)
219
220 if name == "" {
221 return false
222 }
223
224 for _, t := range g.types {
225 if t == name || t == "*" {
226 return true
227 }
228 }
229
230 return false
231 }
232
233 func (g *PackageGenerator) markTypeAsGenerated(t string) {
234 g.generatedTypes[t] = struct{}{}
235 }
236
237 var versionRegex = regexp.MustCompile(`^v\d+$`)
238
239 // packageNameFromPath extracts and normalizes the imported package identifier.
240 //
241 // For example:
242 //
243 // "github.com/labstack/echo/v5" -> "echo"
244 // "github.com/go-ozzo/ozzo-validation/v4" -> "ozzo_validation"
245 func packageNameFromPath(path string) string {
246 name := filepath.Base(strings.Trim(path, `"' `))
247
248 if versionRegex.MatchString(name) {
249 name = filepath.Base(filepath.Dir(path))
250 }
251
252 return strings.ReplaceAll(name, "-", "_")
253 }
254
255 // exists checks if search exists in list.
256 func exists[T comparable](list []T, search T) bool {
257 for _, v := range list {
258 if v == search {
259 return true
260 }
261 }
262
263 return false
264 }