@@ -3,6 +3,7 @@ package compiler
3
3
import (
4
4
"context"
5
5
"fmt"
6
+ "html/template"
6
7
"io/fs"
7
8
"io/ioutil"
8
9
"log"
@@ -268,6 +269,7 @@ func (c *Compiler) Build(ctx context.Context, apiName string) error {
268
269
return fmt .Errorf ("failed to create output directory: %w" , err )
269
270
}
270
271
log .Printf ("compiling API %s to output versions" , apiName )
272
+ var versionSpecFiles []string
271
273
for rcIndex , rc := range api .resources {
272
274
specVersions , err := vervet .LoadSpecVersionsFileset (rc .matchedFiles )
273
275
if err != nil {
@@ -312,6 +314,11 @@ func (c *Compiler) Build(ctx context.Context, apiName string) error {
312
314
return buildErr (err )
313
315
}
314
316
jsonSpecPath := versionDir + "/spec.json"
317
+ jsonEmbedPath , err := filepath .Rel (api .output .path , jsonSpecPath )
318
+ if err != nil {
319
+ return buildErr (err )
320
+ }
321
+ versionSpecFiles = append (versionSpecFiles , jsonEmbedPath )
315
322
err = ioutil .WriteFile (jsonSpecPath , jsonBuf , 0644 )
316
323
if err != nil {
317
324
return buildErr (err )
@@ -326,6 +333,11 @@ func (c *Compiler) Build(ctx context.Context, apiName string) error {
326
333
return buildErr (err )
327
334
}
328
335
yamlSpecPath := versionDir + "/spec.yaml"
336
+ yamlEmbedPath , err := filepath .Rel (api .output .path , yamlSpecPath )
337
+ if err != nil {
338
+ return buildErr (err )
339
+ }
340
+ versionSpecFiles = append (versionSpecFiles , yamlEmbedPath )
329
341
err = ioutil .WriteFile (yamlSpecPath , yamlBuf , 0644 )
330
342
if err != nil {
331
343
return buildErr (err )
@@ -334,9 +346,43 @@ func (c *Compiler) Build(ctx context.Context, apiName string) error {
334
346
}
335
347
}
336
348
}
349
+ err = c .writeEmbedGo (filepath .Base (api .output .path ), api , versionSpecFiles )
350
+ if err != nil {
351
+ return fmt .Errorf ("failed to create embed.go: %w" , err )
352
+ }
337
353
return nil
338
354
}
339
355
356
+ func (c * Compiler ) writeEmbedGo (pkgName string , a * api , versionSpecFiles []string ) error {
357
+ f , err := os .Create (filepath .Join (a .output .path , "embed.go" ))
358
+ if err != nil {
359
+ return err
360
+ }
361
+ defer f .Close ()
362
+ return embedGoTmpl .Execute (f , struct {
363
+ Package string
364
+ API * api
365
+ VersionSpecFiles []string
366
+ }{
367
+ Package : pkgName ,
368
+ API : a ,
369
+ VersionSpecFiles : versionSpecFiles ,
370
+ })
371
+ }
372
+
373
+ var embedGoTmpl = template .Must (template .New ("embed.go" ).Parse (`
374
+ package {{ .Package }}
375
+
376
+ import "embed"
377
+
378
+ // Embed compiled OpenAPI specs in Go projects.
379
+
380
+ {{ range .VersionSpecFiles -}}
381
+ //go:embed {{ . }}
382
+ {{ end -}}
383
+ var Versions embed.FS
384
+ ` ))
385
+
340
386
// BuildAll builds all APIs in the project.
341
387
func (c * Compiler ) BuildAll (ctx context.Context ) error {
342
388
return c .apisEach (ctx , c .Build )
0 commit comments