MCPcopy Create free account
hub / github.com/apache/fory / generateCodeForFile

Function generateCodeForFile

go/fory/codegen/generator.go:276–351  ·  view source on GitHub ↗

generateCodeForFile generates code with file-based naming

(pkg *packages.Package, structs []*StructInfo, sourceFile string)

Source from the content-addressed store, hash-verified

274
275// generateCodeForFile generates code with file-based naming
276func generateCodeForFile(pkg *packages.Package, structs []*StructInfo, sourceFile string) error {
277 var buf bytes.Buffer
278
279 // Generate file header
280 fmt.Fprintf(&buf, "// Code generated by forygen. DO NOT EDIT.\n")
281 fmt.Fprintf(&buf, "// source: %s\n", sourceFile)
282 fmt.Fprintf(&buf, "// generated at: %s\n\n", time.Now().Format(time.RFC3339))
283 fmt.Fprintf(&buf, "package %s\n\n", pkg.Name)
284
285 // Determine which imports are needed
286 needsTime := false
287 needsReflect := false
288 needsOptional := false
289
290 for _, s := range structs {
291 for _, field := range s.Fields {
292 typeStr := field.Type.String()
293 if typeStr == "time.Time" || typeStr == "github.com/apache/fory/go/fory.Date" {
294 needsTime = true
295 }
296 if field.IsOptional {
297 needsOptional = true
298 }
299 // We need reflect for the interface compatibility methods
300 needsReflect = true
301 }
302 }
303
304 // Generate imports
305 // Note: "fmt" is not imported by default. Add it only if the generated code uses fmt.
306 fmt.Fprintf(&buf, "import (\n")
307 if needsReflect {
308 fmt.Fprintf(&buf, "\t\"reflect\"\n")
309 }
310 if needsTime {
311 fmt.Fprintf(&buf, "\t\"time\"\n")
312 }
313 fmt.Fprintf(&buf, "\t\"github.com/apache/fory/go/fory\"\n")
314 if needsOptional {
315 fmt.Fprintf(&buf, "\t\"github.com/apache/fory/go/fory/optional\"\n")
316 }
317 fmt.Fprintf(&buf, ")\n\n")
318
319 // Generate init function to register serializer factories
320 fmt.Fprintf(&buf, "func init() {\n")
321 for _, s := range structs {
322 fmt.Fprintf(&buf, "\tfory.RegisterSerializerFactory((*%s)(nil), NewSerializerFor_%s)\n", s.Name, s.Name)
323 }
324 fmt.Fprintf(&buf, "}\n\n")
325
326 // Generate serializers for each struct
327 for _, s := range structs {
328 if err := generateStructSerializer(&buf, s); err != nil {
329 return fmt.Errorf("generating serializer for %s: %w", s.Name, err)
330 }
331 }
332
333 // Generate compile-time guards to ensure struct definitions haven't changed

Callers 1

processPackageFileFunction · 0.85

Calls 6

generateStructSerializerFunction · 0.85
convertStructInfosFunction · 0.85
generateCompileGuardFunction · 0.85
BytesMethod · 0.80
StringMethod · 0.45
WriteStringMethod · 0.45

Tested by

no test coverage detected