/
openapi_file_loader.go
88 lines (68 loc) · 2.11 KB
/
openapi_file_loader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package jsonast
import (
"fmt"
"os"
"path/filepath"
"github.com/go-openapi/spec"
"github.com/pkg/errors"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/astmodel"
)
type OpenAPIFileLoader interface {
loadFile(absPath string) (PackageAndSwagger, error)
knownFiles() []string
}
type PackageAndSwagger struct {
Package *astmodel.LocalPackageReference
Swagger spec.Swagger
}
// CachingFileLoader is a cache of schema that have been loaded,
// identified by file path
type CachingFileLoader struct {
files map[string]PackageAndSwagger
}
var _ OpenAPIFileLoader = CachingFileLoader{}
// NewCachingFileLoader creates an OpenAPISchemaCache with the initial
// file path → spec mapping
func NewCachingFileLoader(specs map[string]PackageAndSwagger) CachingFileLoader {
files := make(map[string]PackageAndSwagger, len(specs))
for specPath, spec := range specs {
files[filepath.ToSlash(specPath)] = spec
}
return CachingFileLoader{
files: files,
}
}
func (fileCache CachingFileLoader) knownFiles() []string {
result := make([]string, 0, len(fileCache.files))
for k := range fileCache.files {
result = append(result, k)
}
return result
}
// fetchFileAbsolute fetches the schema for the absolute path specified
func (fileCache CachingFileLoader) loadFile(absPath string) (PackageAndSwagger, error) {
if !filepath.IsAbs(absPath) {
panic(fmt.Sprintf("filePath %s must be absolute", absPath)) // assertion, not error
}
key := filepath.ToSlash(absPath)
if swagger, ok := fileCache.files[key]; ok {
return swagger, nil
}
// here the package will be unpopulated,
// which indicates to the caller to reuse the existing package for definitions
result := PackageAndSwagger{}
fileContent, err := os.ReadFile(absPath)
if err != nil {
return result, errors.Wrapf(err, "unable to read swagger file %q", absPath)
}
err = result.Swagger.UnmarshalJSON(fileContent)
if err != nil {
return result, errors.Wrapf(err, "unable to parse swagger file %q", absPath)
}
fileCache.files[key] = result
return result, err
}