go-jsonschema icon indicating copy to clipboard operation
go-jsonschema copied to clipboard

Expose Public Function for Code Generation in Package

Open agmanchon opened this issue 1 year ago • 1 comments

Could you create a public function in the package to generate code directly? This would allow users to utilize the library programmatically without needing to invoke the binary. For example, it would be helpful to have a function like GenerateCode(config Config, schemaFiles []string) error that could be called from Go code. This would improve flexibility and make it easier to integrate the library into other tools or workflows. Currently, the only way to generate code is by executing the binary, which introduces overhead when integrating with other Go projects. Let me know your thoughts, and thank you for considering this suggestion!

agmanchon avatar Nov 21 '24 10:11 agmanchon

Currently, the only way to generate code is by executing the binary, which introduces overhead when integrating with other Go projects.

I don't think this is true. The API surface used by the binary is exposed so that your own code could perform the same tasks directly.

For example:
import (
	"fmt"

	"github.com/atombender/go-jsonschema/pkg/generator"
)

func main() {
	cfg := generator.Config{
		DefaultPackageName: "example",
		DefaultOutputName:  "generated",
	}
	generator, err := generator.New(cfg)
	if err != nil {
		panic(err)
	}

	if err := generator.DoFile("example.json"); err != nil {
		panic(err)
	}

	sources, err := generator.Sources()
	if err != nil {
		panic(err)
	}

	fmt.Printf("Generated %d files\n", len(sources))
	for filename, content := range sources {
		fmt.Printf("=== Generated file: %s ===\n", filename)
		fmt.Print(string(content))
		fmt.Println()
	}
}

cpu avatar Nov 18 '25 17:11 cpu