diff --git a/.changesets/1789466351-99ef89f9.yaml b/.changesets/1789466351-99ef89f9.yaml new file mode 100644 index 00000000..7a69a73e --- /dev/null +++ b/.changesets/1789466351-99ef89f9.yaml @@ -0,0 +1,10 @@ +id: 1789466351-99ef89f9 +features: + - core +targets: + - terraform +type: fix +bump: patch +description: apply path parameter schema defaults and x-speakeasy-terraform-custom-default in ImportState when omitted from the JSON import ID +author: AshGodfrey +date: "2026-09-15" diff --git a/templates/templates/terraform/includes/frameworkSchemaDefaults.ts b/templates/templates/terraform/includes/frameworkSchemaDefaults.ts index c368aec8..2ee93d83 100644 --- a/templates/templates/terraform/includes/frameworkSchemaDefaults.ts +++ b/templates/templates/terraform/includes/frameworkSchemaDefaults.ts @@ -91,13 +91,17 @@ function createSchemaDefault( case "date": case "date-time": case "string": - return typeof defaultValue.Value === "string" - ? new StringSchemaDefaultStatic(defaultValue.Value) - : undefined; + return staticSchemaDefault( + typeDef, + defaultValue.Value, + (literal) => new StringSchemaDefaultStatic(defaultValue.Value, literal), + ); case "boolean": - return typeof defaultValue.Value === "boolean" - ? new BoolSchemaDefaultStatic(defaultValue.Value) - : undefined; + return staticSchemaDefault( + typeDef, + defaultValue.Value, + (literal) => new BoolSchemaDefaultStatic(defaultValue.Value, literal), + ); case "enum": return createSchemaDefault( typeDef.Enum.Type, @@ -106,23 +110,31 @@ function createSchemaDefault( fieldConfig, ); case "float32": - return typeof defaultValue.Value === "number" - ? new Float32SchemaDefaultStatic(defaultValue.Value) - : undefined; + return staticSchemaDefault( + typeDef, + defaultValue.Value, + (literal) => + new Float32SchemaDefaultStatic(defaultValue.Value, literal), + ); case "int32": - return typeof defaultValue.Value === "number" && - Number.isInteger(defaultValue.Value) - ? new Int32SchemaDefaultStatic(defaultValue.Value) - : undefined; + return staticSchemaDefault( + typeDef, + defaultValue.Value, + (literal) => new Int32SchemaDefaultStatic(defaultValue.Value, literal), + ); case "integer": - return typeof defaultValue.Value === "number" && - Number.isInteger(defaultValue.Value) - ? new Int64SchemaDefaultStatic(defaultValue.Value) - : undefined; + return staticSchemaDefault( + typeDef, + defaultValue.Value, + (literal) => new Int64SchemaDefaultStatic(defaultValue.Value, literal), + ); case "number": - return typeof defaultValue.Value === "number" - ? new Float64SchemaDefaultStatic(defaultValue.Value) - : undefined; + return staticSchemaDefault( + typeDef, + defaultValue.Value, + (literal) => + new Float64SchemaDefaultStatic(defaultValue.Value, literal), + ); case "set": { // Exclude set-nested (class/union item types) which become // SetNestedAttribute and do not support defaults. @@ -156,6 +168,86 @@ function createSchemaDefault( } } +function staticSchemaDefault( + typeDef: TypeDef, + value: unknown, + build: (literal: string) => SchemaDefault, +): SchemaDefault | undefined { + const literal = staticDefaultGoLiteral(typeDef, value); + return literal === undefined ? undefined : build(literal); +} + +function staticDefaultGoLiteral( + typeDef: TypeDef, + value: unknown, +): string | undefined { + if (value === undefined || value === null || value === "null") { + return undefined; + } + + switch (typeDef.Type.toString()) { + case "any": + case "bytes": + case "date": + case "date-time": + case "string": + return typeof value === "string" + ? templateBuiltinString(value) + : undefined; + case "boolean": + return typeof value === "boolean" ? String(value) : undefined; + case "enum": + return typeDef.Enum + ? staticDefaultGoLiteral(typeDef.Enum.Type, value) + : undefined; + case "float32": + case "number": + return typeof value === "number" ? String(value) : undefined; + case "int32": + case "integer": + return typeof value === "number" && Number.isInteger(value) + ? String(value) + : undefined; + default: + return undefined; + } +} + +type ScalarDefault = + | { kind: "custom"; config: TerraformCustomDefault } + | { kind: "static"; literal: string }; + +const importScalarTypes = new Set([ + "boolean", + "float32", + "int32", + "integer", + "number", + "string", +]); + +function resolveScalarDefault( + typeDef: TypeDef, + defaultValue: AnyValue | undefined, +): ScalarDefault | undefined { + const scalarType = + typeDef.Type.toString() === "enum" ? typeDef.Enum?.Type : typeDef; + + if (!scalarType || !importScalarTypes.has(scalarType.Type.toString())) { + return undefined; + } + + const customDefaultConfig = typeDef.Extensions?.TerraformCustomDefault; + + if (customDefaultConfig) { + return { kind: "custom", config: customDefaultConfig }; + } + + const literal = staticDefaultGoLiteral(typeDef, defaultValue?.Value); + + return literal === undefined ? undefined : { kind: "static", literal }; +} + /** * Abstract typed default for terraform-plugin-framework defaults.Bool * implementations. Ensures type safety when used with BoolAttribute schema @@ -171,10 +263,12 @@ abstract class BoolSchemaDefault extends SchemaDefault { */ class BoolSchemaDefaultStatic extends BoolSchemaDefault { private readonly value: boolean; + private readonly literal: string; - constructor(value: boolean) { + constructor(value: boolean, literal: string) { super(); this.value = value; + this.literal = literal; } description(): string { @@ -191,7 +285,7 @@ class BoolSchemaDefaultStatic extends BoolSchemaDefault { } template(): string { - return `booldefault.StaticBool(${this.value})`; + return `booldefault.StaticBool(${this.literal})`; } } @@ -240,10 +334,12 @@ abstract class Float32SchemaDefault extends SchemaDefault { */ class Float32SchemaDefaultStatic extends Float32SchemaDefault { private readonly value: number; + private readonly literal: string; - constructor(value: number) { + constructor(value: number, literal: string) { super(); this.value = value; + this.literal = literal; } description(): string { @@ -260,7 +356,7 @@ class Float32SchemaDefaultStatic extends Float32SchemaDefault { } template(): string { - return `float32default.StaticFloat32(${this.value})`; + return `float32default.StaticFloat32(${this.literal})`; } } @@ -279,10 +375,12 @@ abstract class Float64SchemaDefault extends SchemaDefault { */ class Float64SchemaDefaultStatic extends Float64SchemaDefault { private readonly value: number; + private readonly literal: string; - constructor(value: number) { + constructor(value: number, literal: string) { super(); this.value = value; + this.literal = literal; } description(): string { @@ -299,7 +397,7 @@ class Float64SchemaDefaultStatic extends Float64SchemaDefault { } template(): string { - return `float64default.StaticFloat64(${this.value})`; + return `float64default.StaticFloat64(${this.literal})`; } } @@ -318,10 +416,12 @@ abstract class Int32SchemaDefault extends SchemaDefault { */ class Int32SchemaDefaultStatic extends Int32SchemaDefault { private readonly value: number; + private readonly literal: string; - constructor(value: number) { + constructor(value: number, literal: string) { super(); this.value = value; + this.literal = literal; } description(): string { @@ -338,7 +438,7 @@ class Int32SchemaDefaultStatic extends Int32SchemaDefault { } template(): string { - return `int32default.StaticInt32(${this.value})`; + return `int32default.StaticInt32(${this.literal})`; } } @@ -357,10 +457,12 @@ abstract class Int64SchemaDefault extends SchemaDefault { */ class Int64SchemaDefaultStatic extends Int64SchemaDefault { private readonly value: number; + private readonly literal: string; - constructor(value: number) { + constructor(value: number, literal: string) { super(); this.value = value; + this.literal = literal; } description(): string { @@ -377,7 +479,7 @@ class Int64SchemaDefaultStatic extends Int64SchemaDefault { } template(): string { - return `int64default.StaticInt64(${this.value})`; + return `int64default.StaticInt64(${this.literal})`; } } @@ -633,10 +735,12 @@ abstract class StringSchemaDefault extends SchemaDefault { */ class StringSchemaDefaultStatic extends StringSchemaDefault { private readonly value: string; + private readonly literal: string; - constructor(value: string) { + constructor(value: string, literal: string) { super(); this.value = value; + this.literal = literal; } description(): string { @@ -653,6 +757,6 @@ class StringSchemaDefaultStatic extends StringSchemaDefault { } template(): string { - return `stringdefault.StaticString(${templateBuiltinString(this.value)})`; + return `stringdefault.StaticString(${this.literal})`; } } diff --git a/templates/templates/terraform/includes/generateImportState.ts b/templates/templates/terraform/includes/generateImportState.ts index d70838fc..7513fcc0 100644 --- a/templates/templates/terraform/includes/generateImportState.ts +++ b/templates/templates/terraform/includes/generateImportState.ts @@ -221,6 +221,70 @@ function genIsZeroValue( return undefined; } +function templateImportCustomDefault( + symbolManager: Record, + field: FieldDef, + sanitizedFieldName: string, + config: TerraformCustomDefault, + curSymbol: string, + path: string, + fieldName: string, +): string[] { + const scalarType = + field.Type.Type.toString() === "enum" ? field.Type.Enum.Type : field.Type; + const accessor = primitiveAccessor(scalarType, false); + + if (!accessor) { + throw new Error( + `unsupported custom default type ${scalarType.Type} in import for ${field.Name}`, + ); + } + + const defaultTypeName = accessor.slice("Value".length, -"()".length); + const responseVar = getPluralizedVarSymbolName( + symbolManager, + sanitizedFieldName, + "DefaultResponse", + ); + const valueVar = getPluralizedVarSymbolName( + symbolManager, + sanitizedFieldName, + "Default", + ); + + addGenImport( + "github.com/hashicorp/terraform-plugin-framework/resource/schema/defaults", + ); + config.Imports?.forEach((importPath) => addGenImport(importPath)); + + return [ + `var ${responseVar} defaults.${defaultTypeName}Response`, + `${config.SchemaDefinition}.Default${defaultTypeName}(ctx, defaults.${defaultTypeName}Request{Path: ${path}}, &${responseVar})`, + `resp.Diagnostics.Append(${responseVar}.Diagnostics...)`, + `if resp.Diagnostics.HasError() {`, + `return`, + `}`, + `if ${responseVar}.PlanValue.IsNull() || ${responseVar}.PlanValue.IsUnknown() {`, + `resp.Diagnostics.AddError("Missing required field", \`The field ${fieldName} is required but was not found in the json encoded ID and its default resolved to no value.\`)`, + `return`, + `}`, + `${valueVar} := ${sanitizeType( + field.Type, + false, + "", + )}(${responseVar}.PlanValue.${accessor})`, + `${curSymbol} = &${valueVar}`, + ]; +} + +function isImportPointerField(field: FieldDef): boolean { + return ( + field.Optional || + field.Nullable || + resolveScalarDefault(field.Type, field.Default) !== undefined + ); +} + function validateAndSet( valSymbol: string, hierarchy: string[], @@ -257,10 +321,11 @@ function validateAndSet( addGenImport("github.com/hashicorp/terraform-plugin-framework/path"); - const check = - field.Optional || field.Nullable - ? `${curSymbol} == nil` - : genIsZeroValue(accessorType, curSymbol); + const isPointer = isImportPointerField(field); + const check = isPointer + ? `${curSymbol} == nil` + : genIsZeroValue(accessorType, curSymbol); + const scalarDefault = resolveScalarDefault(field.Type, field.Default); const frameworkType = FrameworkTypeFromFieldDef(field); const isGlobalField = curHierarchy.length === 1 && sanitizedFieldName in globalFields; @@ -276,11 +341,7 @@ function validateAndSet( if (isGlobalField) { frameworkType - .templateTerraformToSDKImports( - field.Type, - true, - field.Optional || field.Nullable, - ) + .templateTerraformToSDKImports(field.Type, true, isPointer) .forEach((importStr) => { addGenImport(importStr); }); @@ -291,7 +352,7 @@ function validateAndSet( sanitizedFieldName, field.Type, true, - field.Optional || field.Nullable, + isPointer, curSymbol, `r.${sanitizedFieldName}`, false, @@ -302,22 +363,48 @@ function validateAndSet( result.push(`if ${check} {`); } - // Only include example hint if there's a real OAS-defined example - const hasExample = field.Type.Examples?.length > 0; const fieldName = sanitizeTFStateName(curHierarchy); - if (hasExample) { - const exampleValue = FrameworkTypeFromTypeDef( - field.Type, - ).templateExampleJSONValue(field.Type); + if (scalarDefault?.kind === "static") { + const defaultVar = getPluralizedVarSymbolName( + symbolManager, + sanitizedFieldName, + "Default", + ); result.push( - `resp.Diagnostics.AddError("Missing required field", \`The field ${fieldName} is required but was not found in the json encoded ID. It's expected to be a value alike '${exampleValue}'\`)`, + `var ${defaultVar} ${sanitizeType(field.Type, false, "")} = ${ + scalarDefault.literal + }`, ); - } else { + result.push(`${curSymbol} = &${defaultVar}`); + } else if (scalarDefault?.kind === "custom") { result.push( - `resp.Diagnostics.AddError("Missing required field", \`The field ${fieldName} is required but was not found in the json encoded ID.\`)`, + ...templateImportCustomDefault( + symbolManager, + field, + sanitizedFieldName, + scalarDefault.config, + curSymbol, + path, + fieldName, + ), ); + } else { + // Only include example hint if there's a real OAS-defined example + const hasExample = field.Type.Examples?.length > 0; + if (hasExample) { + const exampleValue = FrameworkTypeFromTypeDef( + field.Type, + ).templateExampleJSONValue(field.Type); + result.push( + `resp.Diagnostics.AddError("Missing required field", \`The field ${fieldName} is required but was not found in the json encoded ID. It's expected to be a value alike '${exampleValue}'\`)`, + ); + } else { + result.push( + `resp.Diagnostics.AddError("Missing required field", \`The field ${fieldName} is required but was not found in the json encoded ID.\`)`, + ); + } + result.push(`return`); } - result.push(`return`); if (isGlobalField) { result.push(`}`); @@ -414,7 +501,7 @@ function templateImportJSONStruct(requiredAttributes: TypeDef): string { const structFieldTag = `\`json:"${attributeName}"\``; const structFieldType = sanitizeType( field.Type, - field.Optional || field.Nullable, + isImportPointerField(field), "", ); diff --git a/tests/specs/review-terraform.yaml b/tests/specs/review-terraform.yaml index cca0fb69..4487b5d0 100644 --- a/tests/specs/review-terraform.yaml +++ b/tests/specs/review-terraform.yaml @@ -331,6 +331,106 @@ paths: application/json: schema: $ref: '#/components/schemas/FrameworkTypeResponse' + /v0/import-defaulted-id/{workspace}/{tier}/{region}: + parameters: + - name: workspace + description: Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID + in: path + required: true + schema: + type: string + default: default-workspace + - name: tier + description: Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID + in: path + required: true + schema: + type: string + enum: + - basic + - premium + default: basic + - name: region + description: Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID + in: path + required: true + schema: + type: string + default: oas-region + x-speakeasy-terraform-custom-default: + imports: + - github.com/hashicorp/terraform-provider-testing/internal/customdefaults + schemaDefinition: "customdefaults.String()" + post: + x-speakeasy-entity-operation: ImportDefaultedId#create + description: Create a new import defaulted id resource, whose read path includes a parameter with a schema default + operationId: create-import-defaulted-id + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ImportDefaultedIdRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ImportDefaultedIdResponse' + /v0/import-defaulted-id/{workspace}/{tier}/{region}/{id}: + parameters: + - name: workspace + description: Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID + in: path + required: true + schema: + type: string + default: default-workspace + - name: tier + description: Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID + in: path + required: true + schema: + type: string + enum: + - basic + - premium + default: basic + - name: region + description: Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID + in: path + required: true + schema: + type: string + default: oas-region + x-speakeasy-terraform-custom-default: + imports: + - github.com/hashicorp/terraform-provider-testing/internal/customdefaults + schemaDefinition: "customdefaults.String()" + - name: id + in: path + required: true + schema: + type: string + delete: + x-speakeasy-entity-operation: ImportDefaultedId#delete + description: Delete an import defaulted id resource + operationId: delete-import-defaulted-id + responses: + '200': + description: OK + get: + x-speakeasy-entity-operation: ImportDefaultedId#read + description: Get an import defaulted id resource + operationId: get-import-defaulted-id + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ImportDefaultedIdResponse' /v0/import-id-enum-string: post: x-speakeasy-entity-operation: ImportIdEnumString#create @@ -9148,6 +9248,23 @@ components: string_date_time: type: string format: date-time + ImportDefaultedIdRequest: + type: object + additionalProperties: false + properties: + requestBodyProperty: + type: string + ImportDefaultedIdResponse: + x-speakeasy-entity: ImportDefaultedId + type: object + additionalProperties: false + properties: + id: + type: string + workspace: + type: string + requestBodyProperty: + type: string ImportIdEnumStringRequest: type: object additionalProperties: false diff --git a/zSDKs/terraform-provider-testing/.speakeasy/gen.lock b/zSDKs/terraform-provider-testing/.speakeasy/gen.lock index b04e25f7..b55b2c70 100644 --- a/zSDKs/terraform-provider-testing/.speakeasy/gen.lock +++ b/zSDKs/terraform-provider-testing/.speakeasy/gen.lock @@ -1,7 +1,7 @@ lockVersion: 2.0.0 id: review-sdk-test-id management: - docChecksum: 4739592738991be9857d1c4474c7aa95 + docChecksum: 0cc5566564e38d98df9fd68ef8704acb docVersion: 0.0.1 speakeasyVersion: internal generationVersion: internal @@ -55,6 +55,8 @@ trackedFiles: last_write_checksum: sha1:a21b63c90ce67e7b78e103fb57e8b55ba8ab4073 examples/data-sources/testing_framework_type/data-source.tf: last_write_checksum: sha1:5962afcf4758bc7d18e755dc83cfc85948e89f9f + examples/data-sources/testing_import_defaulted_id/data-source.tf: + last_write_checksum: sha1:9fd5403a5345d8badc85bc876d3ead0eb679d264 examples/data-sources/testing_import_id_enum_string/data-source.tf: last_write_checksum: sha1:434c8e3e33f4aea19b907934669a18bda4362087 examples/data-sources/testing_import_id_int32/data-source.tf: @@ -287,6 +289,12 @@ trackedFiles: last_write_checksum: sha1:5283f92195a9546994be1b73292ba87eb5b5d245 examples/resources/testing_framework_type/resource.tf: last_write_checksum: sha1:24d7d1eebf90ad3fc482138f7afd7372e79abaa5 + examples/resources/testing_import_defaulted_id/import-by-string-id.tf: + last_write_checksum: sha1:0f89789edb9761026519c53c950e582bf1e8ffc3 + examples/resources/testing_import_defaulted_id/import.sh: + last_write_checksum: sha1:a3c4d79e7e3ea9e4ef09737a5bef04e697047685 + examples/resources/testing_import_defaulted_id/resource.tf: + last_write_checksum: sha1:a8a9564f134ce64f16eed45aff0a7120e1117589 examples/resources/testing_import_id_enum_string/import-by-string-id.tf: last_write_checksum: sha1:a01b97f0a7718d85908f69d4e61d54984be46d23 examples/resources/testing_import_id_enum_string/import.sh: @@ -775,6 +783,14 @@ trackedFiles: last_write_checksum: sha1:d44c355b22f26fd7b534fb458b1cbe81b80e1919 internal/provider/frameworktype_resource_sdk.go: last_write_checksum: sha1:73f3268858f1bd5ae2d73fa868e569470b6088c3 + internal/provider/importdefaultedid_data_source.go: + last_write_checksum: sha1:297a3b3f17843f1f5da9317b7c3c5c3b01685867 + internal/provider/importdefaultedid_data_source_sdk.go: + last_write_checksum: sha1:6c086fbfa6439b47090334c881b5f8d0f65fe7f5 + internal/provider/importdefaultedid_resource.go: + last_write_checksum: sha1:c9c59d7ce9e8addd65ca0e981596bc08427b3d74 + internal/provider/importdefaultedid_resource_sdk.go: + last_write_checksum: sha1:0c70caf18aa6b2ad018b21cfa0df4432f7c61486 internal/provider/importidenumstring_data_source.go: last_write_checksum: sha1:e6b068f00e651ffc130fc382eb6c1c5e52ab5963 internal/provider/importidenumstring_data_source_sdk.go: @@ -1048,7 +1064,7 @@ trackedFiles: internal/provider/patch_resource_sdk.go: last_write_checksum: sha1:9b583e2ac47191350373ce5a86408c118bd606b1 internal/provider/provider.go: - last_write_checksum: sha1:165aa656ebff0c9e83540c0fececc3cf4ab7eeeb + last_write_checksum: sha1:11ad9098df8c62b56d5aab92cde0913a063b03e3 internal/provider/reflect/diags.go: last_write_checksum: sha1:ace8bc53054bb1d8ee8689acf3e4323de75a6297 internal/provider/reflect/doc.go: @@ -2194,7 +2210,7 @@ trackedFiles: internal/provider/xglobals_data_source_sdk.go: last_write_checksum: sha1:9966b8bb938807ea6bdd5a577bc18916452fc5e6 internal/provider/xglobals_resource.go: - last_write_checksum: sha1:6b02d409441f40071659402765d62205490fa98c + last_write_checksum: sha1:5b19f7ccf451a0f49e1c1d7d3c60f72ce639baca internal/provider/xglobals_resource_sdk.go: last_write_checksum: sha1:f3e07ecf4e9205eb56c86f9ae86fc549e0b0e88f internal/provider/xmatch_data_source.go: @@ -2419,6 +2435,8 @@ trackedFiles: last_write_checksum: sha1:715e571da7c0da9a9bf8d4d3ae3a313f623c643a internal/sdk/models/operations/createframeworktype.go: last_write_checksum: sha1:1473ee200106e11a09d436f415f66f8032147fec + internal/sdk/models/operations/createimportdefaultedid.go: + last_write_checksum: sha1:e6bafbcdd061dace291c8868c4f09f5550229c06 internal/sdk/models/operations/createimportidenumstring.go: last_write_checksum: sha1:e6aff15e1e450a453ee5a3114b439a1f3ec6ac72 internal/sdk/models/operations/createimportidint32.go: @@ -2565,6 +2583,8 @@ trackedFiles: last_write_checksum: sha1:ab4a1348806216f6464dc195515e22003e987d60 internal/sdk/models/operations/deleteframeworktype.go: last_write_checksum: sha1:cb1ec4b73bcc82a659f952ab412d978c3378dffb + internal/sdk/models/operations/deleteimportdefaultedid.go: + last_write_checksum: sha1:7fa0087efbb1e4e6689211ca620efefcda531e72 internal/sdk/models/operations/deleteimportidenumstring.go: last_write_checksum: sha1:8dfef5bf1d30e610127bd0665fbf1ff5adedbfd3 internal/sdk/models/operations/deleteimportidint32.go: @@ -2703,6 +2723,8 @@ trackedFiles: last_write_checksum: sha1:8c3bcb9baa37be554d9fc5669e0a09b6fa536ea5 internal/sdk/models/operations/getframeworktype.go: last_write_checksum: sha1:a766fb78f32a52bcca85fcbf206712c6ed0f9f00 + internal/sdk/models/operations/getimportdefaultedid.go: + last_write_checksum: sha1:93856b2bf51efaf2c110f062fc3a06e356c422a1 internal/sdk/models/operations/getimportidenumstring.go: last_write_checksum: sha1:d71cb665d543afccd4dfcfee12af1605c62ec001 internal/sdk/models/operations/getimportidint32.go: @@ -3097,6 +3119,10 @@ trackedFiles: last_write_checksum: sha1:883b03b0b38369abef3d5ef1877aec8efc5e9472 internal/sdk/models/shared/globalenumstring.go: last_write_checksum: sha1:67206cfaee16690785fa23dc881543e87fa45f0f + internal/sdk/models/shared/importdefaultedidrequest.go: + last_write_checksum: sha1:b8523186abdd14ed6fe995f5a9a93e7606c0a549 + internal/sdk/models/shared/importdefaultedidresponse.go: + last_write_checksum: sha1:2096ad5ee71a7f34272f50ec141422097f43a7f1 internal/sdk/models/shared/importidenumstringrequest.go: last_write_checksum: sha1:340524eb2b7b0d43485701dcbd8cf3ce9dc49951 internal/sdk/models/shared/importidenumstringresponse.go: @@ -3540,7 +3566,7 @@ trackedFiles: internal/sdk/retry/config.go: last_write_checksum: sha1:102d1953fbd7e9f312c4442c71ccca2eaaeaa27d internal/sdk/sdk.go: - last_write_checksum: sha1:f160394d83562721b762d238bbef07e10d1db48e + last_write_checksum: sha1:224db2187527a941b29d524d57531f33cfc70f48 internal/sdk/types/bigint.go: last_write_checksum: sha1:49b004005d0461fb04b846eca062b070b0360b31 internal/sdk/types/date.go: @@ -5951,4 +5977,35 @@ examples: "200": application/json: {"name": "", "kind": "alpha", "credentials": {"client_id": ""}} delete-root-union-writeonly: {} + create-import-defaulted-id: + speakeasy-default-create-import-defaulted-id: + parameters: + path: + workspace: "default-workspace" + tier: "basic" + region: "oas-region" + requestBody: + application/json: {} + responses: + "200": + application/json: {} + delete-import-defaulted-id: + speakeasy-default-delete-import-defaulted-id: + parameters: + path: + workspace: "default-workspace" + id: "" + tier: "basic" + region: "oas-region" + get-import-defaulted-id: + speakeasy-default-get-import-defaulted-id: + parameters: + path: + workspace: "default-workspace" + id: "" + tier: "basic" + region: "oas-region" + responses: + "200": + application/json: {} examplesVersion: 1.0.2 diff --git a/zSDKs/terraform-provider-testing/.speakeasy/logs/naming.log b/zSDKs/terraform-provider-testing/.speakeasy/logs/naming.log index 5cbbd633..9f3e6a51 100644 --- a/zSDKs/terraform-provider-testing/.speakeasy/logs/naming.log +++ b/zSDKs/terraform-provider-testing/.speakeasy/logs/naming.log @@ -2238,6 +2238,18 @@ DEBUG discriminated: Renamed to "XUnknownValuesResponse_closed_enum_string" registrationID: "scope:shared refType:Schemas refName:XUnknownValuesResponse originalName:closed_enum_string" DEBUG +--- Renaming 3 types with name "tier" --- +DEBUG discriminated: Renamed to "create_import_defaulted_id_tier" + labels: "original_name:tier operation:create_import_defaulted_id data_type:enum parameter:pathParam" + registrationID: "scope:operations operation:create-import-defaulted-id parameter:pathParam originalName:tier" +DEBUG discriminated: Renamed to "delete_import_defaulted_id_tier" + labels: "original_name:tier operation:delete_import_defaulted_id data_type:enum parameter:pathParam" + registrationID: "scope:operations operation:delete-import-defaulted-id parameter:pathParam originalName:tier" +DEBUG discriminated: Renamed to "get_import_defaulted_id_tier" + labels: "original_name:tier operation:get_import_defaulted_id data_type:enum parameter:pathParam" + registrationID: "scope:operations operation:get-import-defaulted-id parameter:pathParam originalName:tier" +DEBUG + --- Renaming 2 types with name "id" --- DEBUG discriminated: Renamed to "delete_import_id_enum_string_id" labels: "original_name:id operation:delete_import_id_enum_string data_type:enum constProperty:Default parameter:pathParam" @@ -2508,6 +2520,17 @@ GetFrameworkTypeRequest (id: string) GetFrameworkTypeResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) UpdateFrameworkTypeRequest (id: string, FrameworkTypeRequest: FrameworkTypeRequest) UpdateFrameworkTypeResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) +CreateImportDefaultedIdRequest (workspace: string, tier: enum, region: string ...) + CreateImportDefaultedIdTier (enum: basic, premium) + ImportDefaultedIdRequest (requestBodyProperty: string) +CreateImportDefaultedIdResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) + ImportDefaultedIdResponse (id: string, workspace: string, requestBodyProperty: string) +DeleteImportDefaultedIdRequest (workspace: string, tier: enum, region: string ...) + DeleteImportDefaultedIdTier (enum: basic, premium) +DeleteImportDefaultedIdResponse (ContentType: string, StatusCode: int32, RawResponse: response) +GetImportDefaultedIdRequest (workspace: string, tier: enum, region: string ...) + GetImportDefaultedIdTier (enum: basic, premium) +GetImportDefaultedIdResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) ImportIdEnumStringRequest (empty) CreateImportIdEnumStringResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) ImportIdEnumStringResponse (id: enum) diff --git a/zSDKs/terraform-provider-testing/README.md b/zSDKs/terraform-provider-testing/README.md index 5382412e..f26d58fe 100644 --- a/zSDKs/terraform-provider-testing/README.md +++ b/zSDKs/terraform-provider-testing/README.md @@ -105,6 +105,7 @@ Available configuration: * [testing_discriminated_union](docs/resources/discriminated_union.md) * [testing_discriminated_union_array](docs/resources/discriminated_union_array.md) * [testing_framework_type](docs/resources/framework_type.md) +* [testing_import_defaulted_id](docs/resources/import_defaulted_id.md) * [testing_import_id_enum_string](docs/resources/import_id_enum_string.md) * [testing_import_id_int32](docs/resources/import_id_int32.md) * [testing_import_id_int64](docs/resources/import_id_int64.md) @@ -180,6 +181,7 @@ Available configuration: * [testing_basic](docs/data-sources/basic.md) * [testing_discriminated_union](docs/data-sources/discriminated_union.md) * [testing_framework_type](docs/data-sources/framework_type.md) +* [testing_import_defaulted_id](docs/data-sources/import_defaulted_id.md) * [testing_import_id_enum_string](docs/data-sources/import_id_enum_string.md) * [testing_import_id_int32](docs/data-sources/import_id_int32.md) * [testing_import_id_int64](docs/data-sources/import_id_int64.md) diff --git a/zSDKs/terraform-provider-testing/docs/data-sources/import_defaulted_id.md b/zSDKs/terraform-provider-testing/docs/data-sources/import_defaulted_id.md new file mode 100644 index 00000000..333e0176 --- /dev/null +++ b/zSDKs/terraform-provider-testing/docs/data-sources/import_defaulted_id.md @@ -0,0 +1,36 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "testing_import_defaulted_id Data Source - terraform-provider-testing" +subcategory: "" +description: |- + ImportDefaultedID DataSource +--- + +# testing_import_defaulted_id (Data Source) + +ImportDefaultedID DataSource + +## Example Usage + +```terraform +data "testing_import_defaulted_id" "my_importdefaultedid" { + id = "...my_id..." + region = "oas-region" + tier = "basic" + workspace = "default-workspace" +} +``` + + +## Schema + +### Required + +- `region` (String) Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID +- `tier` (String) Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID. must be one of ["basic", "premium"] +- `workspace` (String) Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID + +### Read-Only + +- `id` (String) The ID of this resource. +- `request_body_property` (String) diff --git a/zSDKs/terraform-provider-testing/docs/resources/import_defaulted_id.md b/zSDKs/terraform-provider-testing/docs/resources/import_defaulted_id.md new file mode 100644 index 00000000..f43428e3 --- /dev/null +++ b/zSDKs/terraform-provider-testing/docs/resources/import_defaulted_id.md @@ -0,0 +1,60 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "testing_import_defaulted_id Resource - terraform-provider-testing" +subcategory: "" +description: |- + ImportDefaultedID Resource +--- + +# testing_import_defaulted_id (Resource) + +ImportDefaultedID Resource + +## Example Usage + +```terraform +resource "testing_import_defaulted_id" "my_importdefaultedid" { + region = "oas-region" + request_body_property = "...my_request_body_property..." + tier = "basic" + workspace = "default-workspace" +} +``` + + +## Schema + +### Optional + +- `region` (String) Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID. Requires replacement if changed. +- `request_body_property` (String) Requires replacement if changed. +- `tier` (String) Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID. Default: "basic"; must be one of ["basic", "premium"]; Requires replacement if changed. +- `workspace` (String) Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID. Default: "default-workspace"; Requires replacement if changed. + +### Read-Only + +- `id` (String) The ID of this resource. + +## Import + +Import is supported using the following syntax: + +In Terraform v1.5.0 and later, the [`import` block](https://developer.hashicorp.com/terraform/language/import) can be used with the `id` attribute, for example: + +```terraform +import { + to = testing_import_defaulted_id.my_testing_import_defaulted_id + id = jsonencode({ + id = "..." + region = "..." + tier = "basic" + workspace = "..." + }) +} +``` + +The [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import) can be used, for example: + +```shell +terraform import testing_import_defaulted_id.my_testing_import_defaulted_id '{"id": "...", "region": "...", "tier": "basic", "workspace": "..."}' +``` diff --git a/zSDKs/terraform-provider-testing/examples/data-sources/testing_import_defaulted_id/data-source.tf b/zSDKs/terraform-provider-testing/examples/data-sources/testing_import_defaulted_id/data-source.tf new file mode 100644 index 00000000..fea5c53e --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/data-sources/testing_import_defaulted_id/data-source.tf @@ -0,0 +1,6 @@ +data "testing_import_defaulted_id" "my_importdefaultedid" { + id = "...my_id..." + region = "oas-region" + tier = "basic" + workspace = "default-workspace" +} \ No newline at end of file diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/import-by-string-id.tf b/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/import-by-string-id.tf new file mode 100644 index 00000000..bb8f5d81 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/import-by-string-id.tf @@ -0,0 +1,9 @@ +import { + to = testing_import_defaulted_id.my_testing_import_defaulted_id + id = jsonencode({ + id = "..." + region = "..." + tier = "basic" + workspace = "..." + }) +} diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/import.sh b/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/import.sh new file mode 100644 index 00000000..e15d3c53 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/import.sh @@ -0,0 +1 @@ +terraform import testing_import_defaulted_id.my_testing_import_defaulted_id '{"id": "...", "region": "...", "tier": "basic", "workspace": "..."}' diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/resource.tf b/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/resource.tf new file mode 100644 index 00000000..9ee84a0b --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/resource.tf @@ -0,0 +1,6 @@ +resource "testing_import_defaulted_id" "my_importdefaultedid" { + region = "oas-region" + request_body_property = "...my_request_body_property..." + tier = "basic" + workspace = "default-workspace" +} \ No newline at end of file diff --git a/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_data_source.go b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_data_source.go new file mode 100644 index 00000000..f093f13b --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_data_source.go @@ -0,0 +1,151 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "fmt" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + "github.com/hashicorp/terraform-provider-testing/internal/sdk" +) + +// Ensure provider defined types fully satisfy framework interfaces. +var _ datasource.DataSource = &ImportDefaultedIDDataSource{} +var _ datasource.DataSourceWithConfigure = &ImportDefaultedIDDataSource{} + +func NewImportDefaultedIDDataSource() datasource.DataSource { + return &ImportDefaultedIDDataSource{} +} + +// ImportDefaultedIDDataSource is the data source implementation. +type ImportDefaultedIDDataSource struct { + // Provider configured SDK client. + client *sdk.SDK +} + +// ImportDefaultedIDDataSourceModel describes the data model. +type ImportDefaultedIDDataSourceModel struct { + ID types.String `tfsdk:"id"` + Region types.String `tfsdk:"region"` + RequestBodyProperty types.String `tfsdk:"request_body_property"` + Tier types.String `tfsdk:"tier"` + Workspace types.String `tfsdk:"workspace"` +} + +// Metadata returns the data source type name. +func (r *ImportDefaultedIDDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_import_defaulted_id" +} + +// Schema defines the schema for the data source. +func (r *ImportDefaultedIDDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "ImportDefaultedID DataSource", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Required: true, + }, + "region": schema.StringAttribute{ + Required: true, + Description: `Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID`, + }, + "request_body_property": schema.StringAttribute{ + Computed: true, + }, + "tier": schema.StringAttribute{ + Required: true, + Description: `Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID. must be one of ["basic", "premium"]`, + Validators: []validator.String{ + stringvalidator.OneOf( + "basic", + "premium", + ), + }, + }, + "workspace": schema.StringAttribute{ + Required: true, + Description: `Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID`, + }, + }, + } +} + +func (r *ImportDefaultedIDDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + providerData, ok := req.ProviderData.(*TestingProviderConfigureData) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected DataSource Configure Type", + fmt.Sprintf("Expected *TestingProviderConfigureData, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + r.client = providerData.SDKClient +} + +func (r *ImportDefaultedIDDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var data *ImportDefaultedIDDataSourceModel + var item types.Object + + resp.Diagnostics.Append(req.Config.Get(ctx, &item)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsGetImportDefaultedIDRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.GetImportDefaultedID(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", err.Error()) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ImportDefaultedIDResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedImportDefaultedIDResponse(ctx, res.ImportDefaultedIDResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_data_source_sdk.go b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_data_source_sdk.go new file mode 100644 index 00000000..f3644e3c --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_data_source_sdk.go @@ -0,0 +1,46 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/operations" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" +) + +func (r *ImportDefaultedIDDataSourceModel) RefreshFromSharedImportDefaultedIDResponse(ctx context.Context, resp *shared.ImportDefaultedIDResponse) diag.Diagnostics { + var diags diag.Diagnostics + + if resp != nil { + r.ID = types.StringPointerValue(resp.ID) + r.RequestBodyProperty = types.StringPointerValue(resp.RequestBodyProperty) + r.Workspace = types.StringPointerValue(resp.Workspace) + } + + return diags +} + +func (r *ImportDefaultedIDDataSourceModel) ToOperationsGetImportDefaultedIDRequest(ctx context.Context) (*operations.GetImportDefaultedIDRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var workspace string + workspace = r.Workspace.ValueString() + + tier := operations.GetImportDefaultedIDTier(r.Tier.ValueString()) + var region string + region = r.Region.ValueString() + + var id string + id = r.ID.ValueString() + + out := operations.GetImportDefaultedIDRequest{ + Workspace: workspace, + Tier: tier, + Region: region, + ID: id, + } + + return &out, diags +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource.go b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource.go new file mode 100644 index 00000000..cb181092 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource.go @@ -0,0 +1,357 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/defaults" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + "github.com/hashicorp/terraform-provider-testing/internal/customdefaults" + speakeasy_stringplanmodifier "github.com/hashicorp/terraform-provider-testing/internal/planmodifiers/stringplanmodifier" + "github.com/hashicorp/terraform-provider-testing/internal/sdk" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/operations" +) + +// Ensure provider defined types fully satisfy framework interfaces. +var _ resource.Resource = &ImportDefaultedIDResource{} +var _ resource.ResourceWithImportState = &ImportDefaultedIDResource{} + +func NewImportDefaultedIDResource() resource.Resource { + return &ImportDefaultedIDResource{} +} + +// ImportDefaultedIDResource defines the resource implementation. +type ImportDefaultedIDResource struct { + // Provider configured SDK client. + client *sdk.SDK +} + +// ImportDefaultedIDResourceModel describes the resource data model. +type ImportDefaultedIDResourceModel struct { + ID types.String `tfsdk:"id"` + Region types.String `tfsdk:"region"` + RequestBodyProperty types.String `tfsdk:"request_body_property"` + Tier types.String `tfsdk:"tier"` + Workspace types.String `tfsdk:"workspace"` +} + +func (r *ImportDefaultedIDResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_import_defaulted_id" +} + +func (r *ImportDefaultedIDResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "ImportDefaultedID Resource", + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Computed: true, + }, + "region": schema.StringAttribute{ + Computed: true, + Optional: true, + Default: customdefaults.String(), + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplaceIfConfigured(), + }, + Description: `Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID. Requires replacement if changed.`, + }, + "request_body_property": schema.StringAttribute{ + Computed: true, + Optional: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplaceIfConfigured(), + speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), + }, + Description: `Requires replacement if changed.`, + }, + "tier": schema.StringAttribute{ + Computed: true, + Optional: true, + Default: stringdefault.StaticString(`basic`), + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplaceIfConfigured(), + }, + Description: `Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID. Default: "basic"; must be one of ["basic", "premium"]; Requires replacement if changed.`, + Validators: []validator.String{ + stringvalidator.OneOf( + "basic", + "premium", + ), + }, + }, + "workspace": schema.StringAttribute{ + Computed: true, + Optional: true, + Default: stringdefault.StaticString(`default-workspace`), + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplaceIfConfigured(), + speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), + }, + Description: `Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID. Default: "default-workspace"; Requires replacement if changed.`, + }, + }, + } +} + +func (r *ImportDefaultedIDResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + providerData, ok := req.ProviderData.(*TestingProviderConfigureData) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *TestingProviderConfigureData, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + r.client = providerData.SDKClient +} + +func (r *ImportDefaultedIDResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data *ImportDefaultedIDResourceModel + var plan types.Object + + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(plan.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsCreateImportDefaultedIDRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.CreateImportDefaultedID(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", err.Error()) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ImportDefaultedIDResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedImportDefaultedIDResponse(ctx, res.ImportDefaultedIDResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(refreshPlan(ctx, plan, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ImportDefaultedIDResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data *ImportDefaultedIDResourceModel + var item types.Object + + resp.Diagnostics.Append(req.State.Get(ctx, &item)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsGetImportDefaultedIDRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.GetImportDefaultedID(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", err.Error()) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode == 404 { + resp.State.RemoveResource(ctx) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ImportDefaultedIDResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedImportDefaultedIDResponse(ctx, res.ImportDefaultedIDResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ImportDefaultedIDResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var data *ImportDefaultedIDResourceModel + var plan types.Object + + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + merge(ctx, req, resp, &data) + if resp.Diagnostics.HasError() { + return + } + + // Not Implemented; all attributes marked as RequiresReplace + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ImportDefaultedIDResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data *ImportDefaultedIDResourceModel + var item types.Object + + resp.Diagnostics.Append(req.State.Get(ctx, &item)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsDeleteImportDefaultedIDRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.DeleteImportDefaultedID(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", err.Error()) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + switch res.StatusCode { + case 200, 404: + break + default: + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + +} + +func (r *ImportDefaultedIDResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + dec := json.NewDecoder(bytes.NewReader([]byte(req.ID))) + dec.DisallowUnknownFields() + var data struct { + ID string `json:"id"` + Region *string `json:"region"` + Tier *operations.GetImportDefaultedIDTier `json:"tier"` + Workspace *string `json:"workspace"` + } + + if err := dec.Decode(&data); err != nil { + resp.Diagnostics.AddError("Invalid ID", `The import ID is not valid. It is expected to be a JSON object string with the format: '{"id": "...", "region": "...", "tier": "basic", "workspace": "..."}': `+err.Error()) + return + } + + if len(data.ID) == 0 { + resp.Diagnostics.AddError("Missing required field", `The field id is required but was not found in the json encoded ID.`) + return + } + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), data.ID)...) + if data.Region == nil { + var regionDefaultResponse defaults.StringResponse + customdefaults.String().DefaultString(ctx, defaults.StringRequest{Path: path.Root("region")}, ®ionDefaultResponse) + resp.Diagnostics.Append(regionDefaultResponse.Diagnostics...) + if resp.Diagnostics.HasError() { + return + } + if regionDefaultResponse.PlanValue.IsNull() || regionDefaultResponse.PlanValue.IsUnknown() { + resp.Diagnostics.AddError("Missing required field", `The field region is required but was not found in the json encoded ID and its default resolved to no value.`) + return + } + regionDefault := string(regionDefaultResponse.PlanValue.ValueString()) + data.Region = ®ionDefault + } + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), data.Region)...) + if data.Tier == nil { + var tierDefault operations.GetImportDefaultedIDTier = `basic` + data.Tier = &tierDefault + } + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("tier"), data.Tier)...) + if data.Workspace == nil { + var workspaceDefault string = `default-workspace` + data.Workspace = &workspaceDefault + } + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("workspace"), data.Workspace)...) +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource_sdk.go b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource_sdk.go new file mode 100644 index 00000000..a03d59a5 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource_sdk.go @@ -0,0 +1,112 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/operations" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" +) + +func (r *ImportDefaultedIDResourceModel) RefreshFromSharedImportDefaultedIDResponse(ctx context.Context, resp *shared.ImportDefaultedIDResponse) diag.Diagnostics { + var diags diag.Diagnostics + + if resp != nil { + r.ID = types.StringPointerValue(resp.ID) + r.RequestBodyProperty = types.StringPointerValue(resp.RequestBodyProperty) + r.Workspace = types.StringPointerValue(resp.Workspace) + } + + return diags +} + +func (r *ImportDefaultedIDResourceModel) ToOperationsCreateImportDefaultedIDRequest(ctx context.Context) (*operations.CreateImportDefaultedIDRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var workspace string + workspace = r.Workspace.ValueString() + + tier := operations.CreateImportDefaultedIDTier(r.Tier.ValueString()) + var region string + region = r.Region.ValueString() + + importDefaultedIDRequest, importDefaultedIDRequestDiags := r.ToSharedImportDefaultedIDRequest(ctx) + diags.Append(importDefaultedIDRequestDiags...) + + if diags.HasError() { + return nil, diags + } + + out := operations.CreateImportDefaultedIDRequest{ + Workspace: workspace, + Tier: tier, + Region: region, + ImportDefaultedIDRequest: *importDefaultedIDRequest, + } + + return &out, diags +} + +func (r *ImportDefaultedIDResourceModel) ToOperationsDeleteImportDefaultedIDRequest(ctx context.Context) (*operations.DeleteImportDefaultedIDRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var workspace string + workspace = r.Workspace.ValueString() + + tier := operations.DeleteImportDefaultedIDTier(r.Tier.ValueString()) + var region string + region = r.Region.ValueString() + + var id string + id = r.ID.ValueString() + + out := operations.DeleteImportDefaultedIDRequest{ + Workspace: workspace, + Tier: tier, + Region: region, + ID: id, + } + + return &out, diags +} + +func (r *ImportDefaultedIDResourceModel) ToOperationsGetImportDefaultedIDRequest(ctx context.Context) (*operations.GetImportDefaultedIDRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var workspace string + workspace = r.Workspace.ValueString() + + tier := operations.GetImportDefaultedIDTier(r.Tier.ValueString()) + var region string + region = r.Region.ValueString() + + var id string + id = r.ID.ValueString() + + out := operations.GetImportDefaultedIDRequest{ + Workspace: workspace, + Tier: tier, + Region: region, + ID: id, + } + + return &out, diags +} + +func (r *ImportDefaultedIDResourceModel) ToSharedImportDefaultedIDRequest(ctx context.Context) (*shared.ImportDefaultedIDRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + requestBodyProperty := new(string) + if !r.RequestBodyProperty.IsUnknown() && !r.RequestBodyProperty.IsNull() { + *requestBodyProperty = r.RequestBodyProperty.ValueString() + } else { + requestBodyProperty = nil + } + out := shared.ImportDefaultedIDRequest{ + RequestBodyProperty: requestBodyProperty, + } + + return &out, diags +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource_test.go b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource_test.go new file mode 100644 index 00000000..3a9446a9 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource_test.go @@ -0,0 +1,103 @@ +package provider_test + +import ( + "encoding/json" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/knownvalue" + "github.com/hashicorp/terraform-plugin-testing/statecheck" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" + "github.com/hashicorp/terraform-provider-testing/internal/provider" + "github.com/hashicorp/terraform-provider-testing/internal/tfmockserver" +) + +func TestImportDefaultedIDResourceLifecycle(t *testing.T) { + t.Parallel() + + endpoints := tfmockserver.ResourceEndpoints{ + Create: tfmockserver.Endpoints{ + { + Endpoint: "POST /v0/import-defaulted-id/{workspace}/{tier}/{region}", + }, + }, + Get: tfmockserver.Endpoints{ + { + Endpoint: "GET /v0/import-defaulted-id/{workspace}/{tier}/{region}/{id}", + }, + }, + Delete: tfmockserver.Endpoints{ + { + Endpoint: "DELETE /v0/import-defaulted-id/{workspace}/{tier}/{region}/{id}", + }, + }, + } + mockServer := tfmockserver.StartServer(endpoints, t) + defer mockServer.Close() + + resourceAddress := "testing_import_defaulted_id.my_importdefaultedid" + + resource.Test(t, resource.TestCase{ + Steps: []resource.TestStep{ + // Verifies resource create and read with the schema default applied. + { + ConfigDirectory: config.TestNameDirectory(), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: config.Variables{ + "server_url": config.StringVariable(mockServer.URL), + }, + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("id"), + knownvalue.StringExact(tfmockserver.StoreKey), + ), + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("workspace"), + knownvalue.StringExact("default-workspace"), + ), + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("tier"), + knownvalue.StringExact("basic"), + ), + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("region"), + knownvalue.StringExact("custom default"), + ), + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("request_body_property"), + knownvalue.StringExact("test-request-body"), + ), + }, + }, + // Verifies import applies the schema default when the defaulted + // field is omitted from the JSON import ID. + { + ConfigDirectory: config.TestNameDirectory(), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: config.Variables{ + "server_url": config.StringVariable(mockServer.URL), + }, + ResourceName: resourceAddress, + ImportState: true, + ImportStateIdFunc: func(s *terraform.State) (string, error) { + importIDBytes, err := json.Marshal(struct { + ID string `json:"id"` + }{ + ID: s.RootModule().Resources[resourceAddress].Primary.Attributes["id"], + }) + + return string(importIDBytes), err + }, + ImportStateVerify: true, + }, + // Testing framework implicitly verifies resource delete. + }, + }) +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/provider.go b/zSDKs/terraform-provider-testing/internal/provider/provider.go index 484398c5..778b1906 100644 --- a/zSDKs/terraform-provider-testing/internal/provider/provider.go +++ b/zSDKs/terraform-provider-testing/internal/provider/provider.go @@ -810,6 +810,7 @@ func (p *TestingProvider) Resources(ctx context.Context) []func() resource.Resou NewDiscriminatedUnionResource, NewDiscriminatedUnionArrayResource, NewFrameworkTypeResource, + NewImportDefaultedIDResource, NewImportIDEnumStringResource, NewImportIDInt32Resource, NewImportIDInt64Resource, @@ -888,6 +889,7 @@ func (p *TestingProvider) DataSources(ctx context.Context) []func() datasource.D NewBasicDataSource, NewDiscriminatedUnionDataSource, NewFrameworkTypeDataSource, + NewImportDefaultedIDDataSource, NewImportIDEnumStringDataSource, NewImportIDInt32DataSource, NewImportIDInt64DataSource, diff --git a/zSDKs/terraform-provider-testing/internal/provider/testdata/TestImportDefaultedIDResourceLifecycle/main.tf b/zSDKs/terraform-provider-testing/internal/provider/testdata/TestImportDefaultedIDResourceLifecycle/main.tf new file mode 100644 index 00000000..87ed3237 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/testdata/TestImportDefaultedIDResourceLifecycle/main.tf @@ -0,0 +1,11 @@ +variable "server_url" { + type = string +} + +provider "testing" { + server_url = var.server_url +} + +resource "testing_import_defaulted_id" "my_importdefaultedid" { + request_body_property = "test-request-body" +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/xglobals_resource.go b/zSDKs/terraform-provider-testing/internal/provider/xglobals_resource.go index 1809193e..3efc718e 100644 --- a/zSDKs/terraform-provider-testing/internal/provider/xglobals_resource.go +++ b/zSDKs/terraform-provider-testing/internal/provider/xglobals_resource.go @@ -886,8 +886,8 @@ func (r *XGlobalsResource) ImportState(ctx context.Context, req resource.ImportS data.GlobalBooleanWithDefault = r.GlobalBooleanWithDefault.ValueBoolPointer() } if data.GlobalBooleanWithDefault == nil { - resp.Diagnostics.AddError("Missing required field", `The field global_boolean_with_default is required but was not found in the json encoded ID.`) - return + var globalBooleanWithDefaultDefault bool = true + data.GlobalBooleanWithDefault = &globalBooleanWithDefaultDefault } } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("global_boolean_with_default"), data.GlobalBooleanWithDefault)...) @@ -976,8 +976,8 @@ func (r *XGlobalsResource) ImportState(ctx context.Context, req resource.ImportS data.GlobalFloat32WithDefault = r.GlobalFloat32WithDefault.ValueFloat32Pointer() } if data.GlobalFloat32WithDefault == nil { - resp.Diagnostics.AddError("Missing required field", `The field global_float32_with_default is required but was not found in the json encoded ID.`) - return + var globalFloat32WithDefaultDefault float32 = 1.2 + data.GlobalFloat32WithDefault = &globalFloat32WithDefaultDefault } } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("global_float32_with_default"), data.GlobalFloat32WithDefault)...) @@ -996,8 +996,8 @@ func (r *XGlobalsResource) ImportState(ctx context.Context, req resource.ImportS data.GlobalFloat64WithDefault = r.GlobalFloat64WithDefault.ValueFloat64Pointer() } if data.GlobalFloat64WithDefault == nil { - resp.Diagnostics.AddError("Missing required field", `The field global_float64_with_default is required but was not found in the json encoded ID.`) - return + var globalFloat64WithDefaultDefault float64 = 3.4 + data.GlobalFloat64WithDefault = &globalFloat64WithDefaultDefault } } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("global_float64_with_default"), data.GlobalFloat64WithDefault)...) @@ -1016,8 +1016,8 @@ func (r *XGlobalsResource) ImportState(ctx context.Context, req resource.ImportS data.GlobalInt32WithDefault = typeconvert.Int32PointerToIntPointer(r.GlobalInt32WithDefault.ValueInt32Pointer()) } if data.GlobalInt32WithDefault == nil { - resp.Diagnostics.AddError("Missing required field", `The field global_int32_with_default is required but was not found in the json encoded ID.`) - return + var globalInt32WithDefaultDefault int = 12 + data.GlobalInt32WithDefault = &globalInt32WithDefaultDefault } } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("global_int32_with_default"), data.GlobalInt32WithDefault)...) @@ -1036,8 +1036,8 @@ func (r *XGlobalsResource) ImportState(ctx context.Context, req resource.ImportS data.GlobalInt64WithDefault = r.GlobalInt64WithDefault.ValueInt64Pointer() } if data.GlobalInt64WithDefault == nil { - resp.Diagnostics.AddError("Missing required field", `The field global_int64_with_default is required but was not found in the json encoded ID.`) - return + var globalInt64WithDefaultDefault int64 = 34 + data.GlobalInt64WithDefault = &globalInt64WithDefaultDefault } } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("global_int64_with_default"), data.GlobalInt64WithDefault)...) @@ -1056,8 +1056,8 @@ func (r *XGlobalsResource) ImportState(ctx context.Context, req resource.ImportS data.GlobalIntegerWithDefault = r.GlobalIntegerWithDefault.ValueInt64Pointer() } if data.GlobalIntegerWithDefault == nil { - resp.Diagnostics.AddError("Missing required field", `The field global_integer_with_default is required but was not found in the json encoded ID.`) - return + var globalIntegerWithDefaultDefault int64 = 56 + data.GlobalIntegerWithDefault = &globalIntegerWithDefaultDefault } } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("global_integer_with_default"), data.GlobalIntegerWithDefault)...) @@ -1076,8 +1076,8 @@ func (r *XGlobalsResource) ImportState(ctx context.Context, req resource.ImportS data.GlobalNumberWithDefault = r.GlobalNumberWithDefault.ValueFloat64Pointer() } if data.GlobalNumberWithDefault == nil { - resp.Diagnostics.AddError("Missing required field", `The field global_number_with_default is required but was not found in the json encoded ID.`) - return + var globalNumberWithDefaultDefault float64 = 5.6 + data.GlobalNumberWithDefault = &globalNumberWithDefaultDefault } } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("global_number_with_default"), data.GlobalNumberWithDefault)...) @@ -1096,8 +1096,8 @@ func (r *XGlobalsResource) ImportState(ctx context.Context, req resource.ImportS data.GlobalStringWithDefault = r.GlobalStringWithDefault.ValueStringPointer() } if data.GlobalStringWithDefault == nil { - resp.Diagnostics.AddError("Missing required field", `The field global_string_with_default is required but was not found in the json encoded ID.`) - return + var globalStringWithDefaultDefault string = `DEFAULT` + data.GlobalStringWithDefault = &globalStringWithDefaultDefault } } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("global_string_with_default"), data.GlobalStringWithDefault)...) diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createimportdefaultedid.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createimportdefaultedid.go new file mode 100644 index 00000000..401732c9 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createimportdefaultedid.go @@ -0,0 +1,126 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "encoding/json" + "fmt" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/internal/utils" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" + "net/http" +) + +// CreateImportDefaultedIDTier - Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID +type CreateImportDefaultedIDTier string + +const ( + CreateImportDefaultedIDTierBasic CreateImportDefaultedIDTier = "basic" + CreateImportDefaultedIDTierPremium CreateImportDefaultedIDTier = "premium" +) + +func (e CreateImportDefaultedIDTier) ToPointer() *CreateImportDefaultedIDTier { + return &e +} +func (e *CreateImportDefaultedIDTier) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "basic": + fallthrough + case "premium": + *e = CreateImportDefaultedIDTier(v) + return nil + default: + return fmt.Errorf("invalid value for CreateImportDefaultedIDTier: %v", v) + } +} + +type CreateImportDefaultedIDRequest struct { + // Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID + Workspace string `default:"default-workspace" pathParam:"style=simple,explode=false,name=workspace"` + // Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID + Tier CreateImportDefaultedIDTier `default:"basic" pathParam:"style=simple,explode=false,name=tier"` + // Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID + Region string `default:"oas-region" pathParam:"style=simple,explode=false,name=region"` + ImportDefaultedIDRequest shared.ImportDefaultedIDRequest `request:"mediaType=application/json"` +} + +func (c CreateImportDefaultedIDRequest) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(c, "", false) +} + +func (c *CreateImportDefaultedIDRequest) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &c, "", false, nil); err != nil { + return err + } + return nil +} + +func (c *CreateImportDefaultedIDRequest) GetWorkspace() string { + if c == nil { + return "" + } + return c.Workspace +} + +func (c *CreateImportDefaultedIDRequest) GetTier() CreateImportDefaultedIDTier { + if c == nil { + return CreateImportDefaultedIDTier("") + } + return c.Tier +} + +func (c *CreateImportDefaultedIDRequest) GetRegion() string { + if c == nil { + return "" + } + return c.Region +} + +func (c *CreateImportDefaultedIDRequest) GetImportDefaultedIDRequest() shared.ImportDefaultedIDRequest { + if c == nil { + return shared.ImportDefaultedIDRequest{} + } + return c.ImportDefaultedIDRequest +} + +type CreateImportDefaultedIDResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response + // OK + ImportDefaultedIDResponse *shared.ImportDefaultedIDResponse +} + +func (c *CreateImportDefaultedIDResponse) GetContentType() string { + if c == nil { + return "" + } + return c.ContentType +} + +func (c *CreateImportDefaultedIDResponse) GetStatusCode() int { + if c == nil { + return 0 + } + return c.StatusCode +} + +func (c *CreateImportDefaultedIDResponse) GetRawResponse() *http.Response { + if c == nil { + return nil + } + return c.RawResponse +} + +func (c *CreateImportDefaultedIDResponse) GetImportDefaultedIDResponse() *shared.ImportDefaultedIDResponse { + if c == nil { + return nil + } + return c.ImportDefaultedIDResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteimportdefaultedid.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteimportdefaultedid.go new file mode 100644 index 00000000..72dbc108 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteimportdefaultedid.go @@ -0,0 +1,116 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "encoding/json" + "fmt" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/internal/utils" + "net/http" +) + +// DeleteImportDefaultedIDTier - Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID +type DeleteImportDefaultedIDTier string + +const ( + DeleteImportDefaultedIDTierBasic DeleteImportDefaultedIDTier = "basic" + DeleteImportDefaultedIDTierPremium DeleteImportDefaultedIDTier = "premium" +) + +func (e DeleteImportDefaultedIDTier) ToPointer() *DeleteImportDefaultedIDTier { + return &e +} +func (e *DeleteImportDefaultedIDTier) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "basic": + fallthrough + case "premium": + *e = DeleteImportDefaultedIDTier(v) + return nil + default: + return fmt.Errorf("invalid value for DeleteImportDefaultedIDTier: %v", v) + } +} + +type DeleteImportDefaultedIDRequest struct { + // Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID + Workspace string `default:"default-workspace" pathParam:"style=simple,explode=false,name=workspace"` + // Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID + Tier DeleteImportDefaultedIDTier `default:"basic" pathParam:"style=simple,explode=false,name=tier"` + // Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID + Region string `default:"oas-region" pathParam:"style=simple,explode=false,name=region"` + ID string `pathParam:"style=simple,explode=false,name=id"` +} + +func (d DeleteImportDefaultedIDRequest) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(d, "", false) +} + +func (d *DeleteImportDefaultedIDRequest) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &d, "", false, nil); err != nil { + return err + } + return nil +} + +func (d *DeleteImportDefaultedIDRequest) GetWorkspace() string { + if d == nil { + return "" + } + return d.Workspace +} + +func (d *DeleteImportDefaultedIDRequest) GetTier() DeleteImportDefaultedIDTier { + if d == nil { + return DeleteImportDefaultedIDTier("") + } + return d.Tier +} + +func (d *DeleteImportDefaultedIDRequest) GetRegion() string { + if d == nil { + return "" + } + return d.Region +} + +func (d *DeleteImportDefaultedIDRequest) GetID() string { + if d == nil { + return "" + } + return d.ID +} + +type DeleteImportDefaultedIDResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response +} + +func (d *DeleteImportDefaultedIDResponse) GetContentType() string { + if d == nil { + return "" + } + return d.ContentType +} + +func (d *DeleteImportDefaultedIDResponse) GetStatusCode() int { + if d == nil { + return 0 + } + return d.StatusCode +} + +func (d *DeleteImportDefaultedIDResponse) GetRawResponse() *http.Response { + if d == nil { + return nil + } + return d.RawResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getimportdefaultedid.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getimportdefaultedid.go new file mode 100644 index 00000000..72ae7f4c --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getimportdefaultedid.go @@ -0,0 +1,126 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "encoding/json" + "fmt" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/internal/utils" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" + "net/http" +) + +// GetImportDefaultedIDTier - Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID +type GetImportDefaultedIDTier string + +const ( + GetImportDefaultedIDTierBasic GetImportDefaultedIDTier = "basic" + GetImportDefaultedIDTierPremium GetImportDefaultedIDTier = "premium" +) + +func (e GetImportDefaultedIDTier) ToPointer() *GetImportDefaultedIDTier { + return &e +} +func (e *GetImportDefaultedIDTier) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "basic": + fallthrough + case "premium": + *e = GetImportDefaultedIDTier(v) + return nil + default: + return fmt.Errorf("invalid value for GetImportDefaultedIDTier: %v", v) + } +} + +type GetImportDefaultedIDRequest struct { + // Path parameter with a schema default, which import should apply when the field is omitted from the JSON import ID + Workspace string `default:"default-workspace" pathParam:"style=simple,explode=false,name=workspace"` + // Enum path parameter with a schema default, which import should apply through the enum's underlying type when the field is omitted from the JSON import ID + Tier GetImportDefaultedIDTier `default:"basic" pathParam:"style=simple,explode=false,name=tier"` + // Path parameter with both a custom default extension and an OAS default, where import should apply the custom default like the schema does when the field is omitted from the JSON import ID + Region string `default:"oas-region" pathParam:"style=simple,explode=false,name=region"` + ID string `pathParam:"style=simple,explode=false,name=id"` +} + +func (g GetImportDefaultedIDRequest) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(g, "", false) +} + +func (g *GetImportDefaultedIDRequest) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &g, "", false, nil); err != nil { + return err + } + return nil +} + +func (g *GetImportDefaultedIDRequest) GetWorkspace() string { + if g == nil { + return "" + } + return g.Workspace +} + +func (g *GetImportDefaultedIDRequest) GetTier() GetImportDefaultedIDTier { + if g == nil { + return GetImportDefaultedIDTier("") + } + return g.Tier +} + +func (g *GetImportDefaultedIDRequest) GetRegion() string { + if g == nil { + return "" + } + return g.Region +} + +func (g *GetImportDefaultedIDRequest) GetID() string { + if g == nil { + return "" + } + return g.ID +} + +type GetImportDefaultedIDResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response + // OK + ImportDefaultedIDResponse *shared.ImportDefaultedIDResponse +} + +func (g *GetImportDefaultedIDResponse) GetContentType() string { + if g == nil { + return "" + } + return g.ContentType +} + +func (g *GetImportDefaultedIDResponse) GetStatusCode() int { + if g == nil { + return 0 + } + return g.StatusCode +} + +func (g *GetImportDefaultedIDResponse) GetRawResponse() *http.Response { + if g == nil { + return nil + } + return g.RawResponse +} + +func (g *GetImportDefaultedIDResponse) GetImportDefaultedIDResponse() *shared.ImportDefaultedIDResponse { + if g == nil { + return nil + } + return g.ImportDefaultedIDResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/shared/importdefaultedidrequest.go b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/importdefaultedidrequest.go new file mode 100644 index 00000000..5fcc1ca2 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/importdefaultedidrequest.go @@ -0,0 +1,14 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +type ImportDefaultedIDRequest struct { + RequestBodyProperty *string `json:"requestBodyProperty,omitempty"` +} + +func (i *ImportDefaultedIDRequest) GetRequestBodyProperty() *string { + if i == nil { + return nil + } + return i.RequestBodyProperty +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/shared/importdefaultedidresponse.go b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/importdefaultedidresponse.go new file mode 100644 index 00000000..80aaa314 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/importdefaultedidresponse.go @@ -0,0 +1,30 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +type ImportDefaultedIDResponse struct { + ID *string `json:"id,omitempty"` + Workspace *string `json:"workspace,omitempty"` + RequestBodyProperty *string `json:"requestBodyProperty,omitempty"` +} + +func (i *ImportDefaultedIDResponse) GetID() *string { + if i == nil { + return nil + } + return i.ID +} + +func (i *ImportDefaultedIDResponse) GetWorkspace() *string { + if i == nil { + return nil + } + return i.Workspace +} + +func (i *ImportDefaultedIDResponse) GetRequestBodyProperty() *string { + if i == nil { + return nil + } + return i.RequestBodyProperty +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/sdk.go b/zSDKs/terraform-provider-testing/internal/sdk/sdk.go index d0b12433..4dc8e6c7 100644 --- a/zSDKs/terraform-provider-testing/internal/sdk/sdk.go +++ b/zSDKs/terraform-provider-testing/internal/sdk/sdk.go @@ -2599,6 +2599,385 @@ func (s *SDK) UpdateFrameworkType(ctx context.Context, request operations.Update } +// CreateImportDefaultedID - Create a new import defaulted id resource, whose read path includes a parameter with a schema default +func (s *SDK) CreateImportDefaultedID(ctx context.Context, request operations.CreateImportDefaultedIDRequest, opts ...operations.Option) (*operations.CreateImportDefaultedIDResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := utils.GenerateURL(ctx, baseURL, "/v0/import-defaulted-id/{workspace}/{tier}/{region}", request, nil) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "create-import-defaulted-id", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "ImportDefaultedIDRequest", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "POST", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + if reqContentType != "" { + req.Header.Set("Content-Type", reqContentType) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.CreateImportDefaultedIDResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + + var out shared.ImportDefaultedIDResponse + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.ImportDefaultedIDResponse = &out + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// DeleteImportDefaultedID - Delete an import defaulted id resource +func (s *SDK) DeleteImportDefaultedID(ctx context.Context, request operations.DeleteImportDefaultedIDRequest, opts ...operations.Option) (*operations.DeleteImportDefaultedIDResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := utils.GenerateURL(ctx, baseURL, "/v0/import-defaulted-id/{workspace}/{tier}/{region}/{id}", request, nil) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "delete-import-defaulted-id", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "DELETE", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "*/*") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.DeleteImportDefaultedIDResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + utils.DrainBody(httpRes) + case httpRes.StatusCode == 404: + utils.DrainBody(httpRes) + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// GetImportDefaultedID - Get an import defaulted id resource +func (s *SDK) GetImportDefaultedID(ctx context.Context, request operations.GetImportDefaultedIDRequest, opts ...operations.Option) (*operations.GetImportDefaultedIDResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := utils.GenerateURL(ctx, baseURL, "/v0/import-defaulted-id/{workspace}/{tier}/{region}/{id}", request, nil) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "get-import-defaulted-id", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.GetImportDefaultedIDResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + + var out shared.ImportDefaultedIDResponse + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.ImportDefaultedIDResponse = &out + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode == 404: + utils.DrainBody(httpRes) + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + // CreateImportIDEnumString - Create a new import id enum string resource, which contains a required enum string identifier for import func (s *SDK) CreateImportIDEnumString(ctx context.Context, request shared.ImportIDEnumStringRequest, opts ...operations.Option) (*operations.CreateImportIDEnumStringResponse, error) { o := operations.Options{}