api/codegen.go

90 lines
2.5 KiB
Go
Raw Normal View History

// SPDX-License-Identifier: EUPL-1.2
package api
import (
"context"
"iter"
"maps"
"slices"
core "dappco.re/go/core"
)
// Supported SDK target languages.
var supportedLanguages = map[string]string{
"go": "go",
"typescript-fetch": "typescript-fetch",
"typescript-axios": "typescript-axios",
"python": "python",
"java": "java",
"csharp": "csharp-netcore",
"ruby": "ruby",
"swift": "swift5",
"kotlin": "kotlin",
"rust": "rust",
"php": "php",
}
// SDKGenerator wraps openapi-generator-cli for SDK generation.
type SDKGenerator struct {
SpecPath string
OutputDir string
PackageName string
}
// Generate creates an SDK for the given language using openapi-generator-cli.
// Routes through c.Process() — requires go-process registered.
//
// r := gen.Generate(ctx, c, "go")
func (g *SDKGenerator) Generate(ctx context.Context, c *core.Core, language string) core.Result {
generator, ok := supportedLanguages[language]
if !ok {
return core.Result{Value: core.E("SDKGenerator.Generate", core.Sprintf("unsupported language %q", language), nil), OK: false}
}
fs := c.Fs()
if !fs.Exists(g.SpecPath) {
return core.Result{Value: core.E("SDKGenerator.Generate", core.Concat("spec file not found: ", g.SpecPath), nil), OK: false}
}
outputDir := core.JoinPath(g.OutputDir, language)
fs.EnsureDir(outputDir)
args := g.buildArgs(generator, outputDir)
return c.Process().Run(ctx, "openapi-generator-cli", args...)
}
// buildArgs constructs the openapi-generator-cli command arguments.
func (g *SDKGenerator) buildArgs(generator, outputDir string) []string {
args := []string{
"generate",
"-i", g.SpecPath,
"-g", generator,
"-o", outputDir,
}
if g.PackageName != "" {
args = append(args, "--additional-properties", core.Concat("packageName=", g.PackageName))
}
return args
}
// Available checks if openapi-generator-cli is installed.
// Uses App.Find which searches PATH without importing os/exec.
//
// r := gen.Available()
func (g *SDKGenerator) Available() bool {
r := core.App{}.Find("openapi-generator-cli", "OpenAPI Generator")
return r.OK
}
// SupportedLanguages returns the list of supported SDK target languages.
func SupportedLanguages() []string {
return slices.Sorted(maps.Keys(supportedLanguages))
}
// SupportedLanguagesIter returns an iterator over supported SDK target languages.
func SupportedLanguagesIter() iter.Seq[string] {
return slices.Values(SupportedLanguages())
}