-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfiguration.go
439 lines (379 loc) · 14 KB
/
configuration.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package config
import (
"fmt"
"strings"
"github.com/AlekSi/pointer"
"github.com/mitchellh/mapstructure"
)
const (
v1 = "1.0.0"
v2 = "2.0.0"
Version = v2
GithubWritePermission = "write"
// Constants to be used as keys in the config files
Languages = "languages"
Mode = "mode"
GithubAccessToken = "github_access_token"
SpeakeasyApiKey = "speakeasy_api_key"
SpeakeasyServerURL = "speakeasy_server_url"
OpenAPIDocAuthHeader = "openapi_doc_auth_header"
OpenAPIDocAuthToken = "openapi_doc_auth_token"
OpenAPIDocs = "openapi_docs"
DefaultGithubTokenSecretName = "GITHUB_TOKEN"
DefaultSpeakeasyAPIKeySecretName = "SPEAKEASY_API_KEY"
)
type OptionalPropertyRenderingOption string
const (
OptionalPropertyRenderingOptionAlways OptionalPropertyRenderingOption = "always"
OptionalPropertyRenderingOptionNever OptionalPropertyRenderingOption = "never"
OptionalPropertyRenderingOptionWithExample OptionalPropertyRenderingOption = "withExample"
)
type UsageSnippets struct {
OptionalPropertyRendering OptionalPropertyRenderingOption `yaml:"optionalPropertyRendering"`
AdditionalProperties map[string]any `yaml:",inline"` // Captures any additional properties that are not explicitly defined for backwards/forwards compatibility
}
type Fixes struct {
NameResolutionDec2023 bool `yaml:"nameResolutionDec2023"`
ParameterOrderingFeb2024 bool `yaml:"parameterOrderingFeb2024"`
RequestResponseComponentNamesFeb2024 bool `yaml:"requestResponseComponentNamesFeb2024"`
AdditionalProperties map[string]any `yaml:",inline"` // Captures any additional properties that are not explicitly defined for backwards/forwards compatibility
}
type Auth struct {
OAuth2ClientCredentialsEnabled bool `yaml:"oAuth2ClientCredentialsEnabled"`
OAuth2PasswordEnabled bool `yaml:"oAuth2PasswordEnabled"`
}
type Tests struct {
GenerateNewTests bool `yaml:"generateNewTests"`
}
type Generation struct {
DevContainers *DevContainers `yaml:"devContainers,omitempty"`
BaseServerURL string `yaml:"baseServerUrl,omitempty"`
SDKClassName string `yaml:"sdkClassName,omitempty"`
MaintainOpenAPIOrder bool `yaml:"maintainOpenAPIOrder,omitempty"`
UsageSnippets *UsageSnippets `yaml:"usageSnippets,omitempty"`
UseClassNamesForArrayFields bool `yaml:"useClassNamesForArrayFields,omitempty"`
Fixes *Fixes `yaml:"fixes,omitempty"`
Auth *Auth `yaml:"auth,omitempty"`
// Mock server generation configuration.
MockServer *MockServer `yaml:"mockServer,omitempty"`
Tests Tests `yaml:"tests,omitempty"`
AdditionalProperties map[string]any `yaml:",inline"` // Captures any additional properties that are not explicitly defined for backwards/forwards compatibility
}
type DevContainers struct {
Enabled bool `yaml:"enabled"`
// This can be a local path or a remote URL
SchemaPath string `yaml:"schemaPath"`
AdditionalProperties map[string]any `yaml:",inline"` // Captures any additional properties that are not explicitly defined for backwards/forwards compatibility
}
// Generation configuration for the inter-templated mockserver target for test generation.
type MockServer struct {
// Disables the code generation of the mockserver target.
Disabled bool `yaml:"disabled"`
}
type LanguageConfig struct {
Version string `yaml:"version"`
Cfg map[string]any `yaml:",inline"`
}
type SDKGenConfigField struct {
Name string `yaml:"name" json:"name"`
Required bool `yaml:"required" json:"required"`
RequiredForPublishing *bool `yaml:"requiredForPublishing,omitempty" json:"required_for_publishing,omitempty"`
DefaultValue *any `yaml:"defaultValue,omitempty" json:"default_value,omitempty"`
Description *string `yaml:"description,omitempty" json:"description,omitempty"`
Language *string `yaml:"language,omitempty" json:"language,omitempty"`
SecretName *string `yaml:"secretName,omitempty" json:"secret_name,omitempty"`
ValidationRegex *string `yaml:"validationRegex,omitempty" json:"validation_regex,omitempty"`
ValidationMessage *string `yaml:"validationMessage,omitempty" json:"validation_message,omitempty"`
TestValue *any `yaml:"testValue,omitempty" json:"test_value,omitempty"`
}
type Configuration struct {
ConfigVersion string `yaml:"configVersion"`
Generation Generation `yaml:"generation"`
Languages map[string]LanguageConfig `yaml:",inline"`
New map[string]bool `yaml:"-"`
}
type PublishWorkflow struct {
Name string `yaml:"name"`
Permissions Permissions `yaml:"permissions,omitempty"`
On PublishOn `yaml:"on"`
Jobs Jobs `yaml:"jobs"`
}
type PublishOn struct {
Push Push `yaml:"push"`
WorkflowDispatch *WorkflowDispatchEmpty `yaml:"workflow_dispatch,omitempty"`
}
type TagOn struct {
Push Push `yaml:"push"`
WorkflowDispatch WorkflowDispatchEmpty `yaml:"workflow_dispatch"`
}
type Push struct {
Branches []string `yaml:"branches"`
Paths []string `yaml:"paths"`
}
type GenerateWorkflow struct {
Name string `yaml:"name"`
Permissions Permissions `yaml:"permissions,omitempty"`
On GenerateOn `yaml:"on"`
Jobs Jobs `yaml:"jobs"`
}
type TaggingWorkflow struct {
Name string `yaml:"name"`
Permissions Permissions `yaml:"permissions,omitempty"`
On TagOn `yaml:"on"`
Jobs Jobs `yaml:"jobs"`
}
type Permissions struct {
Checks string `yaml:"checks,omitempty"`
Contents string `yaml:"contents,omitempty"`
PullRequests string `yaml:"pull-requests,omitempty"`
Statuses string `yaml:"statuses,omitempty"`
IDToken string `yaml:"id-token,omitempty"`
}
type GenerateOn struct {
WorkflowDispatch WorkflowDispatch `yaml:"workflow_dispatch"`
Schedule []Schedule `yaml:"schedule,omitempty"`
}
type Jobs struct {
Generate Job `yaml:"generate,omitempty"`
Publish Job `yaml:"publish,omitempty"`
Tag Job `yaml:"tag,omitempty"`
}
type Job struct {
Uses string `yaml:"uses"`
With map[string]any `yaml:"with,omitempty"`
Secrets map[string]string `yaml:"secrets,omitempty"`
}
type WorkflowDispatch struct {
Inputs Inputs `yaml:"inputs"`
}
type WorkflowDispatchEmpty struct{}
type Schedule struct {
Cron string `yaml:"cron"`
}
type Inputs struct {
Force Force `yaml:"force"`
PushCodeSamplesOnly *PushCodeSamplesOnly `yaml:"push_code_samples_only,omitempty"`
SetVersion *SetVersion `yaml:"set_version,omitempty"`
Target *Target `yaml:"target,omitempty"`
}
type Force struct {
Description string `yaml:"description"`
Type string `yaml:"type"`
Default bool `yaml:"default"`
}
type PushCodeSamplesOnly struct {
Description string `yaml:"description"`
Type string `yaml:"type"`
Default bool `yaml:"default"`
}
type SetVersion struct {
Description string `yaml:"description"`
Type string `yaml:"type"`
}
type Target struct {
Description string `yaml:"description"`
Type string `yaml:"type"`
}
func GetDefaultConfig(newSDK bool, getLangDefaultFunc GetLanguageDefaultFunc, langs map[string]bool) (*Configuration, error) {
defaults := GetGenerationDefaults(newSDK)
fields := map[string]any{}
for _, field := range defaults {
if field.DefaultValue != nil {
if strings.Contains(field.Name, ".") {
parts := strings.Split(field.Name, ".")
currMap := fields
for i, part := range parts {
if i == len(parts)-1 {
currMap[part] = *field.DefaultValue
} else {
if _, ok := currMap[part]; !ok {
currMap[part] = map[string]any{}
}
currMap = currMap[part].(map[string]any)
}
}
} else {
fields[field.Name] = *field.DefaultValue
}
}
}
var genConfig Generation
d, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: &genConfig,
TagName: "yaml",
})
if err != nil {
return nil, err
}
if err := d.Decode(fields); err != nil {
return nil, err
}
cfg := &Configuration{
ConfigVersion: Version,
Generation: genConfig,
Languages: map[string]LanguageConfig{},
New: map[string]bool{},
}
for lang, new := range langs {
langDefault := &LanguageConfig{
Version: "0.0.1",
}
if getLangDefaultFunc != nil {
var err error
langDefault, err = getLangDefaultFunc(lang, new)
if err != nil {
return nil, err
}
}
cfg.Languages[lang] = *langDefault
}
return cfg, nil
}
func GetGenerationDefaults(newSDK bool) []SDKGenConfigField {
return []SDKGenConfigField{
{
Name: "baseServerURL",
Required: false,
DefaultValue: ptr(""),
Description: pointer.To("The base URL of the server. This value will be used if global servers are not defined in the spec."),
ValidationRegex: pointer.To(`^(https?):\/\/([\w\-]+\.)+\w+(\/.*)?$`),
ValidationMessage: pointer.To("Must be a valid server URL"),
},
{
Name: "sdkClassName",
Required: false,
DefaultValue: ptr("SDK"),
Description: pointer.To("Generated name of the root SDK class"),
ValidationRegex: pointer.To(`^[\w.\-]+$`),
ValidationMessage: pointer.To("Letters, numbers, or .-_ only"),
},
{
Name: "maintainOpenAPIOrder",
Required: false,
DefaultValue: ptr(newSDK),
Description: pointer.To("Maintains the order of things like parameters and fields when generating the SDK"),
},
{
Name: "usageSnippets.optionalPropertyRendering",
Required: false,
DefaultValue: ptr(OptionalPropertyRenderingOptionWithExample),
Description: pointer.To("Controls how optional properties are rendered in usage snippets, by default they will be rendered when an example is present in the OpenAPI spec"),
},
{
Name: "useClassNamesForArrayFields",
Required: false,
DefaultValue: ptr(newSDK),
Description: pointer.To("Use class names for array fields instead of the child's schema type"),
},
{
Name: "fixes.nameResolutionDec2023",
Required: false,
DefaultValue: ptr(newSDK),
Description: pointer.To("Enables a number of breaking changes introduced in December 2023, that improve name resolution for inline schemas and reduce chances of name collisions"),
},
{
Name: "fixes.parameterOrderingFeb2024",
Required: false,
DefaultValue: ptr(newSDK),
Description: pointer.To("Enables fixes to the ordering of parameters for an operation if they include multiple types of parameters (ie header, query, path) to match the order they are defined in the OpenAPI spec"),
},
{
Name: "fixes.requestResponseComponentNamesFeb2024",
Required: false,
DefaultValue: ptr(newSDK),
Description: pointer.To("Enables fixes that will name inline schemas within request and response components with the component name of the parent if only one content type is defined"),
},
{
Name: "fixes.methodSignaturesApr2024",
Required: false,
DefaultValue: ptr(newSDK),
Description: pointer.To("Enables fixes that will detect and mark optional request and security method arguments and order them according to optionality."),
},
{
Name: "auth.oAuth2ClientCredentialsEnabled",
Required: false,
DefaultValue: ptr(newSDK),
Description: pointer.To("Enables support for OAuth2 client credentials grant type (Enterprise tier only)"),
},
{
Name: "auth.oAuth2PasswordEnabled",
Required: false,
DefaultValue: ptr(newSDK),
Description: pointer.To("Enables support for OAuth2 resource owner password credentials grant type (Enterprise tier only)"),
},
{
Name: "tests.generateNewTests",
Required: false,
DefaultValue: ptr(false),
Description: pointer.To("Enables generation of new tests for any new operations found in the OpenAPI spec"),
},
}
}
func (c *Configuration) GetGenerationFieldsMap() (map[string]any, error) {
fields := map[string]any{}
// Yes the decoder can encode too :face_palm:
d, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: &fields,
TagName: "yaml",
})
if err != nil {
return nil, err
}
if err := d.Decode(c.Generation); err != nil {
return nil, err
}
return fields, nil
}
func ptr(a any) *any {
return &a
}
func DefaultGenerationFile() *GenerateWorkflow {
secrets := make(map[string]string)
secrets[GithubAccessToken] = FormatGithubSecretName(DefaultGithubTokenSecretName)
secrets[SpeakeasyApiKey] = FormatGithubSecretName(DefaultSpeakeasyAPIKeySecretName)
return &GenerateWorkflow{
Name: "Generate",
On: GenerateOn{
WorkflowDispatch: WorkflowDispatch{
Inputs: Inputs{
Force: Force{
Description: "Force generation of SDKs",
Type: "boolean",
Default: false,
},
},
},
Schedule: []Schedule{
{
Cron: "0 0 * * *",
},
},
},
Jobs: Jobs{
Generate: Job{
Uses: "speakeasy-api/sdk-generation-action/.github/workflows/workflow-executor.yaml@v15",
With: map[string]any{
"speakeasy_version": "latest",
"force": "${{ github.event.inputs.force }}",
Mode: "pr",
},
Secrets: secrets,
},
},
Permissions: Permissions{
Checks: GithubWritePermission,
Statuses: GithubWritePermission,
Contents: GithubWritePermission,
PullRequests: GithubWritePermission,
},
}
}
func FormatGithubSecretName(name string) string {
return fmt.Sprintf("${{ secrets.%s }}", strings.ToUpper(FormatGithubSecret(name)))
}
func FormatGithubSecret(secret string) string {
if secret != "" && secret[0] == '$' {
secret = secret[1:]
}
return strings.ToLower(secret)
}