diff --git a/.changesets/1789466351-99ef89f9.yaml b/.changesets/1789466351-99ef89f9.yaml new file mode 100644 index 00000000..74c30d10 --- /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 in ImportState when omitted from the JSON import ID +author: AshGodfrey +date: "2026-09-15" diff --git a/templates/templates/terraform/includes/generateImportState.ts b/templates/templates/terraform/includes/generateImportState.ts index d70838fc..9175767a 100644 --- a/templates/templates/terraform/includes/generateImportState.ts +++ b/templates/templates/terraform/includes/generateImportState.ts @@ -221,6 +221,50 @@ function genIsZeroValue( return undefined; } +function templateImportDefaultLiteral(field: FieldDef): string | undefined { + return templateImportDefaultValue(field.Type, field.Default?.Value); +} + +function templateImportDefaultValue( + typeDef: TypeDef, + value: unknown, +): string | undefined { + if (value === undefined || value === null || value === "null") { + return undefined; + } + + switch (typeDef.Type.toString()) { + case "enum": + return typeDef.Enum + ? templateImportDefaultValue(typeDef.Enum.Type, value) + : undefined; + case "string": + return typeof value === "string" + ? templateBuiltinString(value) + : undefined; + case "boolean": + return typeof value === "boolean" ? String(value) : undefined; + case "int32": + case "integer": + return typeof value === "number" && Number.isInteger(value) + ? String(value) + : undefined; + case "float32": + case "number": + return typeof value === "number" ? String(value) : undefined; + default: + return undefined; + } +} + +function isImportPointerField(field: FieldDef): boolean { + return ( + field.Optional || + field.Nullable || + templateImportDefaultLiteral(field) !== undefined + ); +} + function validateAndSet( valSymbol: string, hierarchy: string[], @@ -257,10 +301,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 defaultLiteral = templateImportDefaultLiteral(field); const frameworkType = FrameworkTypeFromFieldDef(field); const isGlobalField = curHierarchy.length === 1 && sanitizedFieldName in globalFields; @@ -276,11 +321,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 +332,7 @@ function validateAndSet( sanitizedFieldName, field.Type, true, - field.Optional || field.Nullable, + isPointer, curSymbol, `r.${sanitizedFieldName}`, false, @@ -302,22 +343,38 @@ 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); - 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}'\`)`, + if (defaultLiteral !== undefined) { + const defaultVar = getPluralizedVarSymbolName( + symbolManager, + sanitizedFieldName, + "Default", ); - } else { result.push( - `resp.Diagnostics.AddError("Missing required field", \`The field ${fieldName} is required but was not found in the json encoded ID.\`)`, + `var ${defaultVar} ${sanitizeType( + field.Type, + false, + "", + )} = ${defaultLiteral}`, ); + result.push(`${curSymbol} = &${defaultVar}`); + } 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 +471,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..a5e6a423 100644 --- a/tests/specs/review-terraform.yaml +++ b/tests/specs/review-terraform.yaml @@ -331,6 +331,84 @@ paths: application/json: schema: $ref: '#/components/schemas/FrameworkTypeResponse' + /v0/import-defaulted-id/{workspace}/{tier}: + 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 + 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}/{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: 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 +9226,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..d850157e 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: fdb2b1d51412b3b292dd97709ae315d1 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:984159a4ad493cd956f36875c77f1934bd23dca8 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:8255a86de0e316845728e93da80a267748e9e7f5 + examples/resources/testing_import_defaulted_id/import.sh: + last_write_checksum: sha1:c7421154c2deb7c286303005ca84a3fb3771b8f5 + examples/resources/testing_import_defaulted_id/resource.tf: + last_write_checksum: sha1:d2c308351c209fdbe2970f765f38ab91436c0000 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:a7ec672e2723e2be31f1064360c09bfdd61b0c9e + internal/provider/importdefaultedid_data_source_sdk.go: + last_write_checksum: sha1:55467a81b3d1bf314436186dc6f6aeae392478d6 + internal/provider/importdefaultedid_resource.go: + last_write_checksum: sha1:751b5919daf274694fe3d6bd5a5de7214ea2f344 + internal/provider/importdefaultedid_resource_sdk.go: + last_write_checksum: sha1:20852518c93a97c7b61470208240d1801e07fee0 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:9ff349e019206efee165e4ea2a85ff1d02a43d51 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:f1e49d0f45a5514a09d79d34a38c309dedb5bf4a 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:f7805d9b00621a89e25af2bf0479a78730304135 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:a0f9be15814f2d63c4f4d24fc14da14edc92a687 internal/sdk/types/bigint.go: last_write_checksum: sha1:49b004005d0461fb04b846eca062b070b0360b31 internal/sdk/types/date.go: @@ -5951,4 +5977,32 @@ 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" + 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" + get-import-defaulted-id: + speakeasy-default-get-import-defaulted-id: + parameters: + path: + workspace: "default-workspace" + id: "" + tier: "basic" + 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..e157795f 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, ImportDefaultedIdRequest: ImportDefaultedIdRequest) + 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, id: string) + DeleteImportDefaultedIdTier (enum: basic, premium) +DeleteImportDefaultedIdResponse (ContentType: string, StatusCode: int32, RawResponse: response) +GetImportDefaultedIdRequest (workspace: string, tier: enum, id: 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..02e6e936 --- /dev/null +++ b/zSDKs/terraform-provider-testing/docs/data-sources/import_defaulted_id.md @@ -0,0 +1,34 @@ +--- +# 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..." + tier = "basic" + workspace = "default-workspace" +} +``` + + +## Schema + +### Required + +- `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..26459621 --- /dev/null +++ b/zSDKs/terraform-provider-testing/docs/resources/import_defaulted_id.md @@ -0,0 +1,57 @@ +--- +# 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" { + request_body_property = "...my_request_body_property..." + tier = "basic" + workspace = "default-workspace" +} +``` + + +## Schema + +### Optional + +- `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 = "..." + 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": "...", "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..38562453 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/data-sources/testing_import_defaulted_id/data-source.tf @@ -0,0 +1,5 @@ +data "testing_import_defaulted_id" "my_importdefaultedid" { + id = "...my_id..." + 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..973c17b7 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/import-by-string-id.tf @@ -0,0 +1,8 @@ +import { + to = testing_import_defaulted_id.my_testing_import_defaulted_id + id = jsonencode({ + id = "..." + 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..a91d6626 --- /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": "...", "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..b8ecf457 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_import_defaulted_id/resource.tf @@ -0,0 +1,5 @@ +resource "testing_import_defaulted_id" "my_importdefaultedid" { + 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..4a59358f --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_data_source.go @@ -0,0 +1,146 @@ +// 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"` + 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, + }, + "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..d1fb3c9a --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_data_source_sdk.go @@ -0,0 +1,42 @@ +// 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 id string + id = r.ID.ValueString() + + out := operations.GetImportDefaultedIDRequest{ + Workspace: workspace, + Tier: tier, + 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..470707b6 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource.go @@ -0,0 +1,329 @@ +// 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/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" + 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"` + 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, + }, + "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"` + 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": "...", "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.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..1fa071a0 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource_sdk.go @@ -0,0 +1,100 @@ +// 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()) + importDefaultedIDRequest, importDefaultedIDRequestDiags := r.ToSharedImportDefaultedIDRequest(ctx) + diags.Append(importDefaultedIDRequestDiags...) + + if diags.HasError() { + return nil, diags + } + + out := operations.CreateImportDefaultedIDRequest{ + Workspace: workspace, + Tier: tier, + 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 id string + id = r.ID.ValueString() + + out := operations.DeleteImportDefaultedIDRequest{ + Workspace: workspace, + Tier: tier, + 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 id string + id = r.ID.ValueString() + + out := operations.GetImportDefaultedIDRequest{ + Workspace: workspace, + Tier: tier, + 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..29055223 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/importdefaultedid_resource_test.go @@ -0,0 +1,98 @@ +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}", + }, + }, + Get: tfmockserver.Endpoints{ + { + Endpoint: "GET /v0/import-defaulted-id/{workspace}/{tier}/{id}", + }, + }, + Delete: tfmockserver.Endpoints{ + { + Endpoint: "DELETE /v0/import-defaulted-id/{workspace}/{tier}/{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("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..466fc71e --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createimportdefaultedid.go @@ -0,0 +1,117 @@ +// 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"` + 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) 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..3c9a6208 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteimportdefaultedid.go @@ -0,0 +1,107 @@ +// 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"` + 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) 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..8aa9bcc5 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getimportdefaultedid.go @@ -0,0 +1,117 @@ +// 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"` + 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) 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..f67b93c6 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}", 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}/{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}/{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{}