Debian Codegraph @

tpl/openapi/openapi3/openapi3.go

raw
1 // Copyright 2020 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package openapi3 provides functions for generating OpenAPI v3 (Swagger) documentation.
15 package openapi3
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "net/url"
22 "path"
23 "path/filepath"
24 "strings"
25
26 kopenapi3 "github.com/getkin/kin-openapi/openapi3"
27 "github.com/gohugoio/hugo/cache/dynacache"
28 "github.com/gohugoio/hugo/common/hashing"
29 "github.com/gohugoio/hugo/common/hmaps"
30 "github.com/gohugoio/hugo/common/hugio"
31 "github.com/gohugoio/hugo/deps"
32 "github.com/gohugoio/hugo/identity"
33 "github.com/gohugoio/hugo/parser/metadecoders"
34 "github.com/gohugoio/hugo/resources"
35 "github.com/gohugoio/hugo/resources/resource"
36 resourcestpl "github.com/gohugoio/hugo/tpl/resources"
37 "github.com/mitchellh/mapstructure"
38 )
39
40 // New returns a new instance of the openapi3-namespaced template functions.
41 func New(deps *deps.Deps) *Namespace {
42 return &Namespace{
43 cache: dynacache.GetOrCreatePartition[string, *OpenAPIDocument](deps.MemCache, "/tmpl/openapi3", dynacache.OptionsPartition{Weight: 30, ClearWhen: dynacache.ClearOnChange}),
44 deps: deps,
45 }
46 }
47
48 // Namespace provides template functions for the "openapi3".
49 type Namespace struct {
50 cache *dynacache.Partition[string, *OpenAPIDocument]
51 deps *deps.Deps
52 resourcesNs *resourcestpl.Namespace
53 }
54
55 // OpenAPIDocument represents an OpenAPI 3 document.
56 type OpenAPIDocument struct {
57 *kopenapi3.T
58 identityGroup identity.Identity
59 }
60
61 func (o *OpenAPIDocument) GetIdentityGroup() identity.Identity {
62 return o.identityGroup
63 }
64
65 type unmarshalOptions struct {
66 // Options passed to resources.GetRemote when resolving remote $ref.
67 GetRemote map[string]any
68 }
69
70 // Unmarshal unmarshals the given resource into an OpenAPI 3 document.
71 func (ns *Namespace) Unmarshal(ctx context.Context, args ...any) (*OpenAPIDocument, error) {
72 if len(args) < 1 || len(args) > 2 {
73 return nil, errors.New("must provide a Resource and optionally an options map")
74 }
75
76 r := args[0].(resource.UnmarshableResource)
77 key := r.Key()
78 if key == "" {
79 return nil, errors.New("no Key set in Resource")
80 }
81
82 var opts unmarshalOptions
83 if len(args) > 1 {
84 optsm, err := hmaps.ToStringMapE(args[1])
85 if err != nil {
86 return nil, err
87 }
88 if err := mapstructure.WeakDecode(optsm, &opts); err != nil {
89 return nil, err
90 }
91 key += "_" + hashing.HashString(optsm)
92 }
93
94 v, err := ns.cache.GetOrCreate(key, func(string) (*OpenAPIDocument, error) {
95 f := metadecoders.FormatFromStrings(r.MediaType().Suffixes()...)
96 if f == "" {
97 return nil, fmt.Errorf("MIME %q not supported", r.MediaType())
98 }
99
100 reader, err := r.ReadSeekCloser()
101 if err != nil {
102 return nil, err
103 }
104 defer reader.Close()
105
106 b, err := hugio.ReadAll(reader)
107 if err != nil {
108 return nil, err
109 }
110
111 s := &kopenapi3.T{}
112 switch f {
113 case metadecoders.YAML:
114 err = metadecoders.UnmarshalYaml(b, s)
115 default:
116 err = metadecoders.Default.UnmarshalTo(b, f, s)
117 }
118 if err != nil {
119 return nil, err
120 }
121
122 var resourcePath string
123 if res, ok := r.(resource.Resource); ok {
124 resourcePath = resources.InternalResourceSourcePath(res)
125 }
126 var relDir string
127 if resourcePath != "" {
128 if rel, ok := ns.deps.Assets.MakePathRelative(filepath.FromSlash(resourcePath), true); ok {
129 relDir = filepath.Dir(rel)
130 }
131 }
132
133 var idm identity.Manager = identity.NopManager
134 if v := identity.GetDependencyManager(r); v != nil {
135 idm = v
136 }
137 idg := identity.FirstIdentity(r)
138
139 resolver := &refResolver{
140 ctx: ctx,
141 idm: idm,
142 opts: opts,
143 relBase: filepath.ToSlash(relDir),
144 ns: ns,
145 }
146
147 loader := kopenapi3.NewLoader()
148 loader.IsExternalRefsAllowed = true
149 loader.ReadFromURIFunc = resolver.resolveExternalRef
150 err = loader.ResolveRefsIn(s, nil)
151
152 return &OpenAPIDocument{T: s, identityGroup: idg}, err
153 })
154 if err != nil {
155 return nil, err
156 }
157
158 return v, nil
159 }
160
161 type refResolver struct {
162 ctx context.Context
163 idm identity.Manager
164 opts unmarshalOptions
165 relBase string
166 ns *Namespace
167 }
168
169 // resolveExternalRef resolves external references in OpenAPI documents by either fetching
170 // remote URLs or loading local files from the assets directory, depending on the reference location.
171 func (r *refResolver) resolveExternalRef(loader *kopenapi3.Loader, loc *url.URL) ([]byte, error) {
172 if loc.Scheme != "" && loc.Host != "" {
173 res, err := r.ns.resourcesNs.GetRemote(loc.String(), r.opts.GetRemote)
174 if err != nil {
175 return nil, fmt.Errorf("failed to get remote ref %q: %w", loc.String(), err)
176 }
177 content, err := resources.InternalResourceSourceContent(r.ctx, res)
178 if err != nil {
179 return nil, fmt.Errorf("failed to read remote ref %q: %w", loc.String(), err)
180 }
181 r.idm.AddIdentity(identity.FirstIdentity(res))
182 return []byte(content), nil
183 }
184
185 var filename string
186 if strings.HasPrefix(loc.Path, "/") {
187 filename = loc.Path
188 } else {
189 filename = path.Join(r.relBase, loc.Path)
190 }
191
192 res := r.ns.resourcesNs.Get(filename)
193 if res == nil {
194 return nil, fmt.Errorf("local ref %q not found", loc.String())
195 }
196 content, err := resources.InternalResourceSourceContent(r.ctx, res)
197 if err != nil {
198 return nil, fmt.Errorf("failed to read local ref %q: %w", loc.String(), err)
199 }
200 r.idm.AddIdentity(identity.FirstIdentity(res))
201 return []byte(content), nil
202 }