From 6a16358810e85890a289191233ab6565b7173d36 Mon Sep 17 00:00:00 2001 From: "api-clients-generation-pipeline[bot]" <54105614+api-clients-generation-pipeline[bot]@users.noreply.github.com> Date: Tue, 23 Mar 2021 15:32:28 +0100 Subject: [PATCH] Move templates in clients (#804) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * renaming for openapi-generator * add helper function to generate openapi yaml/json file * Rename projects from swagger-codegen master branch * Add OpenAPI spec 3.0 support (beta) Co-authored-by: Akihito Nakano Co-authored-by: Jeremie Bresson Co-authored-by: Jim Schubert Co-authored-by: Martin Delille Co-authored-by: Tomasz Prus Co-authored-by: William Cheng * Merge branch 'swagger-codegen_renamed' into 'master' (#183) * Added vendorExtensions.x-isPrimitive. (#7991) * Added vendorExtensions.x-isPrimitive. Switch template for constructFromObject. * Reflect review indication. * [typescript-angular] AOT-compatible API client (via ng-packagr and ngc) (#7984) * typescript-angular: uses ng-packagr for the build see https://github.com/swagger-api/swagger-codegen/issues/6722 see https://github.com/swagger-api/swagger-codegen/pull/6735/ * this should make everybody happy: Angular 2/4/5 AOT support - uses ngc when targeting Angular 2 (as seen in https://github.com/swagger-api/swagger-codegen/pull/6735) - uses ng-packagr 1 when targeting Angular 4 - uses ng-packagr 2 when targeting Angular 5 * removes bogus import * cleans / updates Petstore samples, adds a new sample for Angular 5 * typo in README * fixes broken travis build. adds pom.xml files again This reverts commit 471d248a2e9b5d8eed10c71644c222c053e007b0. * makes usage of `dist` more clear and i feel generally better when `npm run build` is called explicitly. - for ng-packagr 2 is doesn't matter, since the final package.json does not have any scripts - for old ng-packagr 1 it matters, scripts are copied to the final package.json which breaks installation via `npm install {{npmName}} --save` (it runs `npm run build` again) * typescript-angular: small improvements as suggested by @macjohnny * angular-typescript: updated petstore samples, 3rd try * Issue 5542, always generate pom and readme (#7977) * Issue 5542, generate pom.xml with separate parameter. InterfaceOnly=true for not generating pom.xml not works in every situation. * Issue 5542, generate pom.xml with separate parameter. InterfaceOnly=true for not generating pom.xml not works in every situation. * Issue #5542 Always generate pom.xml and README.md * [TypeScript][Angular] fix date path parameters (#7476, #7302) (#7479) * #7476, #7302: [TypeScript][Angular] fix date path parameters, fix path parameters with :.+ in it * #7476, #7302: [TypeScript][Angular] fix date path parameters, fix path parameters with :.+ in it * #7476, #7302: [TypeScript][Angular] fix date path parameters, fix path parameters with :.+ in it * #7476: generate samples * code cleanup * #7476: improve variable description * #7302: revert character skipping, since it will now have the same parameter name in the method signature and in the api path * #7302: generate samples * typescript-angular: added Interfaces to api exports if withInterfaces is selected (#7975) * added Interfaces to api exports if withInterfaces is selected * removed import of interface classes * added gererated petstore example api.ts * Fix Issue 8014 * Adapted to work with Angular2 Http and Angular 4.3+ HttpClient * removed unnecessary (others) for ng HttpClient from Interface * Golang Client Refactor (body and model in errors, typed optional parameters) (#7987) * Return abstracted errors with model data if available. * update tests with error models. * Return error models on the abstract type. * dont leak FH * duplicate of PR #7752 for issue #7511 * Change optional parameters to structs. * update documentation * fix circleCI failure * [typescript][angular] query parameter with null value should not be set (#8033) * #7893: [typescript][angular] fix optional query parameter null value * #7893: [typescript][angular] generate samples * #7893: [typescript][angular] generate samples * Version rest-assured has been updated to 3.1.0 (#8052) * [Dart] Fixes TypeError in Dart 2 mode (#7959) * Properly convert lists to dart types * Updated sample petstore client * Fixed maps in Dart strong mode Fixed list parsing for null-elements * change parseDate in es6/APIClient (#7973) * [PHP] Improve duplicated validation logic (#7954) * Improve duplicated validation logic * Update the samples * Update go client, fix double body read (#211) * fix parameter naming in go * various fix for go petstore * update go readme, update pom go dependencies (#274) * Fix go readme, remove resty install (#280) * fix go readme, remove resty install * fix default to null in go petstore doc * update default user agent (#284) * Update wordings (#301) * update wordings * update git_push wordings * update git clone * update homepage url * update meta-codegen sample * Renamings (#252) * Merge 'master' branch of 'swagger-codegen' into 'openapi-generator' (#327) * Update Go generators' default value (#362) * udpate go client default value * update go generators' default value * Rename datatype to dataType in CodegenProperty (#69) * [Golang][client] fix RFC-3339 date-time query param (#325) * Grammar and spelling fixes (#329) * [go] Fix issue #51, change object mapping from *interface{} to map[string]interface (#60) * [Golang][client] fix undefined: localVarFile (#382) * fix undefined: localVarFile * add required formData file endpoints to 2.0 and 3.0 specs * streamline api.mustache update * update sampels * update samples * update samples * update samples bin/jaxrs-cxf-client-petstore.sh * update samples * update samples * update samples run-all-petstore * update samples * update samples * Trigger CI due to race condition * update samples * update samples * Trigger CI due to previous timeout * Trigger CI due to previous Shippable timeout * Trigger CI due to previous Shippable race condition * Minor improvement to Go client generator, move test case (#430) * move test cases to under fake endpoint * remove trailing spaces in the template * update samples * add new file * minor fix to OAS3 spec * fix cache-expires-ineffassign (#466) * add RFC-3339 formatting to parameterToString (#502) * [Golang][client] fix `formData` `file` parameter name use (#506) * support form-data file MIME `name` parameter * update test spec and Go client for form-data file name * update samples for ensure-up-to-date * update mustache template * update samples for Go client * improve assignment location * update samples * [Golang][client] Add option for standard Go generated code comment (#555) * update go generated code comment * update samples for go petstore * update code generation comment * update samples for go petstore * Trigger CI due to previous Shippable race condition * add -DwithGoCodegenComment=true option * reset samples * add withGoCodegenComment=true to bin/go-petstore-withxml.sh * update samples/.../go-petstore-withXml using -DwithGoCodegenComment=true * add xml attr support in go client (#867) * improve go code format without gofmt (#1173) * x-www-form-urlencoded-body-fix (#1187) * [go] x-www-form-urlencoded-body-fix * [go] run scripts in bin and bin/security * Add x-go-custom-tag to go-server generator (#1146) * Add x-go-custom-tag to go-server generator * update model templates to include x-go-custom-tag * [Golang][client] fix response decode error handling (#1291) * handle and return API response decode error * ensure-up-to-date * refactor go/api.mustache for easier readability * disable error reporting for TestPlaceOrder with invalid RFC 3339 `+0000` UTC offset present in Petstore test server * Issue 1766 Modified mustache files for Go to support nullable in the … (#1869) * Issue 1766 Modified mustache files for Go to support nullable in the spec v3.0+; Updated model files running .sh scripts for Go. * Add "nullable" to fake yaml * Add sample script for OAS3 * Fix output folder (openapi3) * Run bin/openapi3/go-petstore.sh * Update samples * Update jaxrs-jersey * Update python and php samples * Add bin/openapi3/go-gin-petstore-server.sh * Run bin/openapi3/go-gin-petstore-server.sh * Update bin/openapi3/go-petstore-server.sh to generate "nullable" samples * Run bin/openapi3/go-petstore-server.sh * Fix duplicated `import` * Remove API Key Authentication code for go when cookie is used. (#1601) * [Go] Fix up json check regexp and support vendor-specific mime types (#2322) * [Go] Fix up mimetype regexps * [Go] Support vendor-specific JSON mime types * [Go] Tidy up unmarshalling content type checks * [Go] Generate sample clients * [go] support decoding plain string responses (#2414) For the following spec: ``` yaml responses: "200": description: Pong. content: text/plain: schema: type: string ``` The generated client currently fails with `undefined response type`. In this scenario, `v interface{}` is a string pointer which can be populated regardless of the content-type. * [#2441] Update documentation mustache templates for proper linting. (#2458) * [#2441] Update documentation mustache files for PHP client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] Issues with generated markdown files as reported by markdownlint for node.js are: - MD001 heading-increment/header-increment - Heading levels should only increment by one level at a time - MD002 first-heading-h1/first-header-h1 - First heading should be a top level heading - MD007 ul-indent - Unordered list indentation - MD009 no-trailing-spaces - Trailing spaces - MD010 no-hard-tabs - Hard tabs - MD011 no-reversed-links - Reversed link syntax - MD025 single-h1 - Multiple top level headings in the same document - MD031 blanks-around-fences - Fenced code blocks should be surrounded by blank lines - MD032 blanks-around-lists - Lists should be surrounded by blank lines - MD040 fenced-code-language - Fenced code blocks should have a language specified - MD041 first-line-h1 - First line in file should be a top level heading * [#2441] Update documentation mustache files for ruby client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] Issues with generated markdown files as reported by markdownlint for node.js are: - MD001 heading-increment/header-increment - Heading levels should only increment by one level at a time - MD002 first-heading-h1/first-header-h1 - First heading should be a top level heading - MD007 ul-indent - Unordered list indentation - MD009 no-trailing-spaces - Trailing spaces - MD010 no-hard-tabs - Hard tabs - MD011 no-reversed-links - Reversed link syntax - MD025 single-h1 - Multiple top level headings in the same document - MD031 blanks-around-fences - Fenced code blocks should be surrounded by blank lines - MD032 blanks-around-lists - Lists should be surrounded by blank lines - MD040 fenced-code-language - Fenced code blocks should have a language specified - MD041 first-line-h1 - First line in file should be a top level heading * [#2441] Update documentation mustache files for javascript client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] Issues with generated markdown files as reported by markdownlint for node.js are: - MD001 heading-increment/header-increment - Heading levels should only increment by one level at a time - MD002 first-heading-h1/first-header-h1 - First heading should be a top level heading - MD007 ul-indent - Unordered list indentation - MD009 no-trailing-spaces - Trailing spaces - MD010 no-hard-tabs - Hard tabs - MD011 no-reversed-links - Reversed link syntax - MD025 single-h1 - Multiple top level headings in the same document - MD031 blanks-around-fences - Fenced code blocks should be surrounded by blank lines - MD032 blanks-around-lists - Lists should be surrounded by blank lines - MD040 fenced-code-language - Fenced code blocks should have a language specified - MD041 first-line-h1 - First line in file should be a top level heading * [#2441] Update documentation mustache files for Java client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] Issues with generated markdown files as reported by markdownlint for node.js are: - MD001 heading-increment/header-increment - Heading levels should only increment by one level at a time - MD002 first-heading-h1/first-header-h1 - First heading should be a top level heading - MD007 ul-indent - Unordered list indentation - MD009 no-trailing-spaces - Trailing spaces - MD010 no-hard-tabs - Hard tabs - MD011 no-reversed-links - Reversed link syntax - MD025 single-h1 - Multiple top level headings in the same document - MD031 blanks-around-fences - Fenced code blocks should be surrounded by blank lines - MD032 blanks-around-lists - Lists should be surrounded by blank lines - MD040 fenced-code-language - Fenced code blocks should have a language specified - MD041 first-line-h1 - First line in file should be a top level heading * [#2441] Update documentation mustache files for GO client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] Issues with generated markdown files as reported by markdownlint for node.js are: - MD001 heading-increment/header-increment - Heading levels should only increment by one level at a time - MD002 first-heading-h1/first-header-h1 - First heading should be a top level heading - MD007 ul-indent - Unordered list indentation - MD009 no-trailing-spaces - Trailing spaces - MD010 no-hard-tabs - Hard tabs - MD011 no-reversed-links - Reversed link syntax - MD025 single-h1 - Multiple top level headings in the same document - MD031 blanks-around-fences - Fenced code blocks should be surrounded by blank lines - MD032 blanks-around-lists - Lists should be surrounded by blank lines - MD040 fenced-code-language - Fenced code blocks should have a language specified - MD041 first-line-h1 - First line in file should be a top level heading * [#2441] Update documentation mustache files for Rust client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] Issues with generated markdown files as reported by markdownlint for node.js are: - MD001 heading-increment/header-increment - Heading levels should only increment by one level at a time - MD002 first-heading-h1/first-header-h1 - First heading should be a top level heading - MD007 ul-indent - Unordered list indentation - MD009 no-trailing-spaces - Trailing spaces - MD010 no-hard-tabs - Hard tabs - MD011 no-reversed-links - Reversed link syntax - MD025 single-h1 - Multiple top level headings in the same document - MD031 blanks-around-fences - Fenced code blocks should be surrounded by blank lines - MD032 blanks-around-lists - Lists should be surrounded by blank lines - MD040 fenced-code-language - Fenced code blocks should have a language specified - MD041 first-line-h1 - First line in file should be a top level heading * [#2441] Update documentation mustache files for C# client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] Issues with generated markdown files as reported by markdownlint for node.js are: - MD001 heading-increment/header-increment - Heading levels should only increment by one level at a time - MD002 first-heading-h1/first-header-h1 - First heading should be a top level heading - MD007 ul-indent - Unordered list indentation - MD009 no-trailing-spaces - Trailing spaces - MD010 no-hard-tabs - Hard tabs - MD011 no-reversed-links - Reversed link syntax - MD025 single-h1 - Multiple top level headings in the same document - MD031 blanks-around-fences - Fenced code blocks should be surrounded by blank lines - MD032 blanks-around-lists - Lists should be surrounded by blank lines - MD040 fenced-code-language - Fenced code blocks should have a language specified - MD041 first-line-h1 - First line in file should be a top level heading * [#2441] Update documentation mustache files for Android client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] Issues with generated markdown files as reported by markdownlint for node.js are: - MD001 heading-increment/header-increment - Heading levels should only increment by one level at a time - MD002 first-heading-h1/first-header-h1 - First heading should be a top level heading - MD007 ul-indent - Unordered list indentation - MD009 no-trailing-spaces - Trailing spaces - MD010 no-hard-tabs - Hard tabs - MD011 no-reversed-links - Reversed link syntax - MD025 single-h1 - Multiple top level headings in the same document - MD031 blanks-around-fences - Fenced code blocks should be surrounded by blank lines - MD032 blanks-around-lists - Lists should be surrounded by blank lines - MD040 fenced-code-language - Fenced code blocks should have a language specified - MD041 first-line-h1 - First line in file should be a top level heading * Update README.mustache * [#2441] Update documentation mustache files for Ada client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] * [#2441] Update documentation mustache files for Apex client This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] * [#2441] Update documentation mustache files for bash This commit fixes issues with Markdown/CommonMark parsing by linting and enforcing consistent style.[#2441] * [go] fix multipart for non-file inputs (#2792) * [go] fix multipart for non-file inputs * update relevant sample client * [Golang][client] Make it possible to generate go.mod and go.sum files - fixes #2796 (#2813) * fix(golang): Check error of xml Encode (#3027) * refactor(golang): Use http provided constants for http methods (#3028) * refactor(golang): Use http constants for methods * regenerate samples * fix: Only import strings when needed * regenerate samples * Only import fmt and strings when needed * regenerate samples * [Golang][client] Allow generating go client code as a submodule. (#3012) * [Go][Client] Use configured Scheme and Host in requests (#3115) * [Go][Client] Ensure test errors don't crash Previously we did not interrupt execution of a test case when an error was returned from an API call. This was causing the tests to crash as soon as we try to dereference the response. We now fail the tests as soon as the first API error is received. * [Go][Client] Use configured Scheme and Host in requests Previously we were simply setting the Host header and completely ignoring the configured scheme. * [go] Serialize multipart array of complex objects as JSON (#2965) * Serialize multipart array of complex objects as JSON * Update sample client * Update sample client * [Golang][Client] Fix collectionFormat=multi request bug (#3390) * fix parameter-collectionformat-multi * update template to tabs * Import Go package with leading underscore (#3634) * escape import with underscore in go client * revert changes to test spec * [Go]URLEncode path parameters (#3643) * URLEncode path parameters * update samples * Use correct module naming * Guarantee a unique name for the constants that represent enum values (#3644) * Guarantee a unique name for the constants that represent enum values * update samples * Use all-caps * [Go] add option to use class as enum prefix (#3675) * add option to use class as enum prefix * update doc * fix go test * update go xml petstore * fix format * Support custom git repository (#3757) * add gitHost param to GeneratorSettings and related * parameterize gitHost in READMEs * parameterize gitHost in go.mod * parameterize gitHost in git_push * update petstore samples * run ./bin/utils/export_docs_generators.sh * run meta-codehen.sh * Revert "run meta-codehen.sh" This reverts commit d6d579f6159186531257cdfdd73b9caf9e9ffeba. * Revert "run ./bin/utils/export_docs_generators.sh" This reverts commit 1b81538198d4319fd1b4e97447303e3cc0e8dc99. * Revert "update petstore samples" This reverts commit f513add88396707f6991ae2e4920359583ec88f1. * run ensure-up-to-date * Better Go code format (#3819) * better varible naming * better comments * better code format for go experimental client * better comment, update samples * Fix readonly with isReadOnly (#4102) * fix readonly * update samples * fix enum which is not string of Go (#4077) * [Go] Fix go.mod and go.sum for 1.13 (#4084) The openapi-generator-cli currently creates an invalid go.mod file, according to the go1.13 compiler. This change uses the correct pseudo version without upgrading or modifying either dependency. It also adds several missing go.sum dependencies that will break when the toolchain is run in -mod=readonly mode. * Do not check status code for default response (#3322) * Do not check status code for default response * Updated generated code/docs Because Circle CI said > Please run 'bin/utils/ensure-up-to-date' locally and commit > changes (UNCOMMITTED CHANGES ERROR) * Add newline between function signature of operation and summary of operation (#4112) * Add newline after function signature * update Petstore * [go] Add newline after function signature * update petstore * [Go] Upgrade dependencies (#4126) antihax/optional#1 added module support, and was tagged as a stable release. This change consumes that tag, and updates the psuedo-version for golang.org/x/oauth2. * [Golang] Allow retrieving the underlying configuration for APIClient (#3976) * Allow retrieving the underlying configuration for APIClient - Needed for dynamically changing the underlying implementations and for testing - Fixes #1321 and #3412 * Added go-petstore-withXml changes suggested by circleci * Add caution note about modifying configuration while live * [Go] Bypass object decode in case of empty body (#4546) Fixes #4545 Change-Id: Ic724843713f60f996ed72326ad6ef6762ec2e713 * Add an option to prefix Go struct with the classname (#4564) * add option to prefix struct with classname * update usage * fix test * update doc * Add support for dumping request and response in Go generated clients (#4566) * Add support for dumping request and response in Go generated clients The following change adds a new configuration setting, which controls whether clients want to dump the HTTP request and response. Useful when debugging API calls and clients. * samples: Update Go samples with XML * Use log.Logger when dumping HTTP request and response in Go client * Add debug flag support for go-experimental generator (#4649) * Add debug flag for go-experimental generator * Check for errors before dumping the response in Go generator * samples/openapi3: update samples for Go generators * [Go] Add multiple servers support to Go(-experimental) client (#4635) * [Go] Add multiple servers support to Go-experimental client * [Go] Use same configuration in go and go-experimental * [Go] Use Replace -1 instead of ReplaceAll * [Go] Fix typo and add bound check * [Go] Regenerate missing templates * [go] Fix multi-value path params in go (#4664) * Fix multi-value path params in go * update oas v3 go petstore sample * [REQ][GO] add awsv4 signature support (#4784) * [REQ][GO] add awsv4 signature support for client OpenAPI format does not support AWS Signature method. This commit add support for AWSv4 signature in GO client generation by adding "withAWSV4Signature" option. "withAWSV4Signature" option is false by default. Signed-off-by: Jérome Jutteau * [REQ][GO] update samples for awsv4 signature support Signed-off-by: Jérome Jutteau * [go][client] fix when schema have multiple servers (#4901) * [go] Fix multiple go compilation errors and enable go integration test in pom.xml (#5075) * fix go compilation error for properties of type map and array * fix go compilation error for properties of type date and datetime * add missing shell script to bin/utils/ensure-up-to-date * add missing shell script to bin/utils/ensure-up-to-date * add missing shell script to bin/utils/ensure-up-to-date * fix issue with 'date' type * fix time import problem * Add missing pom.xml files for golang * Add missing unit test files for golang * Add missing unit test files for golang. Must use class name prefix for enums * Fix unit tests for go-experimental in OAS3 * Fix unit tests for go-experimental in OAS3 * Add code comments in codegen * Fix compilation errors of generated go code * Fix compilation errors of generated go code * remove antihax from go-experimental, it is no longer used * copy python testfile for ut purpose * add error checkout in unit tests * add unit tests * add code comments * move test foo.png file to correct location * run samples scripts * run samples scripts * Switch to predominant use of appDescriptionWithNewLines in README.mustache (#5109) Descriptions tend to get lengthy and can include multiple lines. New lines are important to markdown formatting/syntax and can't just be ignored. Resolves https://github.com/OpenAPITools/openapi-generator/issues/3704 * [Golang] Add support allOf inheritance with embedded go structs (#4934) * Golang: generate embedded structs and set supportsInheritance to true * Run bin/go-experimental-petstore.sh * [templates] Update templates vendor ext standards (#5295) * [templates] Update to vendor extension standard keys * Fix missed value in Java template, also implements=>x-implements. Evaluate Haskell Client changes * Fix missing accept/content-type update for vendor extension format * [go-experimental][go][client] Remove unreachable code in go client API methods (#5611) * [go-experimental][go][client] Remove unreachable code in go client API methods * Properly regenerate all samples * Sync master to 5.0.x (#5968) * Change the Model template (#5222) * Add a link to Xero blog post (#5426) * Removal of Encoding in the Query-Params in order to prevent double Encoding. (#5255) This way letting WebClient do its Job in encoding the URL. * update java webclient sample * [kotlin][client] Add Jackson as serialization library (#5236) * [kotlin][client] Add Jackson as serialization library * [kotlin][client] Add kotlin-client-jackson.sh to kotlin-client-all.sh * update kotlin client samples * update doc Co-authored-by: William Cheng * include kotlin jackson in CI tests (#5438) * [Ruby] Add error output (#5428) * Add error output to the log so that we can make sure why the error occurred * Fix forbidden method invocation using default charsets * Update usage.md (#5443) * fix NPE for enum (#5445) * [Java][WebClient] better code format (#5433) * better code format for java webclient * prefix local varaible with localVar * fix issue with online service (#5461) * Support for additionalProperties in the C generator "Client: C" solves #5395 (#5440) * Support for additionalProperties in the C generator. * Support for additionalProperties in the C generator. * [docs] Enable Algolia search (#5472) * Fix #5420 add headers from configuration object (#5422) * Fix #5420 add headers from configuration object * Add baseOptions undefined checking #5420 * Update the samples and replace array to object #5420 * Update sample * [typescript] Clean up modelPropertyNaming across generators (#5427) * [typescript] Clean up modelPropertyNaming across generators Fixes https://github.com/OpenAPITools/openapi-generator/issues/2976 Generators without runtime models conversion use "original" property naming by default. It's still possible to change it via cli options Generators with runtime conversion keep using "camelCase" * Refactoring: use enum instead of string for modelPropertyNaming * Restore the original camelCase for var names, decouple it from property names * Swap toParamName and toVarName logic (looks like I've mistaken them) * Regenerate docs * Remove a no longer used private method * Added support for msvc builds in cpp-qt5-client generator (#5468) * Added support for msvc builds Moved GCC-specific compile flags to non msvc builds, and added equivalent flags for msvc. * CMakeLists condition cleanup * [all] Move feature set setter (#5460) When I originally implemented the feature set code, I added the getter/setter on DefaultCodegen and CodegenConfig as well as on GeneratorMetadata. GeneratorMetadata also includes the library variation features. When I went to add library-specific features, I realized the discrepancy. This removes the public setter from DefaultCodegen/CodegenConfig, and adds a protected modifyFeatureSet which accepts a lambda and hides the builder logic away in the method. This will be a breaking change for anyone who's created a custom generator in 4.2.3, so the impact is very limited. * [Swift5] small improvements to Objc compatibility (#5410) * [swift] make some small improvements * [swift][client] revert model to use allVars * PostProcessModelProperty with allVars * PostProcessModelProperty with vars * [swift] improve objc interoperability * [swift] fix swift4 for CI to pass * [swift] improve objc interoperability * [swift] improve objc interoperability * Swift - try to fix build * [swift] remove pods from git * [scala] [template] scala sttp client (#5429) * scala-sttp-client template * invoker for sttp fixed and tests added * clean up pet api test from redunant comments * docs updated * fix artefact name, model comments and redunant generic * code optimization * cross scala versions 2.11 2.12 2.13 * date serializers extracted and joda enabled as default * basic and bearer authorization added, apikey in query supported * [Ruby] Fix obsolete configuration of Rubocop and Rubocop's warns (#5417) (#5474) * fix obsolute configuration in generated .rubocop.yml * fix style of `expect` with block in generated ruby client's test code * update sample of ruby client * [scala] strip model class name for all scala generators (#5439) * stripped parameter enabled for all scala based generators * scala samples updated * docs generators updated * fix scalatra. regenerated by openapi3 script. manually removed enum default value from scalatra example due bug in schema extraction * [Scala][sttp] various improvements (#5475) * various improvements to scala sttp * update ScalaSttpClientCodegen.java * add windows batch file * test scala sttp in jdk8 * fix tempalte directory * Use the dataType if the baseType is not set (#5372) * Use the dataType if the baseType is not set * add tests for passing enum as parameter * updated requirements file in samples * Update spec to explicitly name objects and prevent `inline_object` * use the correct scripts to generate samples (`bin/openapi3/python-flask*`) * [python] Adds python oneOf/anyOf models + tests (#5341) * Adds oneOf + anyOf schemas, models and tests to python-experimental * Adds setUpClass and tearDownClass * Removes newline in method_init_shared.mustache * Regenerated v3 spec sample for python-experimental * Fxes test for discard_unknown_keys * Moves new models into existing spec, regen python-exp and go-exp * Also fix python-exp windows file * fix CVE-2020-8130 (#5483) * [go] Add Ptr method to const enum values (#5257) * fix rubocop warns in Ruby client's custom spec (#5488) * [C-libcurl] The name in API parameter should not be escaped even though it includes a C key word. (#5487) * [go-experimental] Support aliasing of API keys (#4940) * [go-experimental] Support aliasing of API keys * Use {{.}} inside condition * Use name instead of keyParamName for lookup * x-lookup to x-auth-id-alias * [java] Support aliasing of API keys (#4966) * [java] Support aliasing of API keys * Rebuild Java Jersey2 sample client * x-lookup to x-auth-id-alias * Regenerated * [cli][gradle] Validate now uses parseOptions w/setResolve (#5471) * [cli] Validate now uses parseOptions w/setResolve The validate command now uses ParseOptions#setResolve(true) to match how we parse in CodegenConfigurator and online's Generate. Without this option, the OpenAPI 3 parser skips the "resolve" block, which made lead to validations in the command not matching validations during generation. * [gradle] Validate now uses parseOptions w/setResolve The Graldle validate command now uses ParseOptions#setResolve(true) to match how we parse in CodegenConfigurator and online's Generate. Without this option, the OpenAPI 3 parser skips the "resolve" block, which made lead to validations in the command not matching validations during generation. * [kotlin]Fix ktor doesn't generate nullable types (#5258) * If not required, need `? = null` * run ./bin/kotlin-server-petstore.sh * Added `?` when value is `required` and `isNullable` * Rerun ./bin/kotlin-server-petstore.sh. But No differences * [C++] Add an option to allow having lowercase variables in models, Pistache: allow using reservedWords in models (#5434) * [C++][Pistache] Use reserved words to replace incorrect names discard old decision to truncate reservedWords * [C++][Pistache] Update struct model to use name instead of baseName * [C++][Pistache] Update Petstore sample * [C++] Add option to have lowercase variables * [C++] Update generated docs * [BUG] [JAVA | Spring] Cookie in parameter is not correctly generated (#5393) * Cookie in parameter is not correctly generated * gh-5386: Fix cookie parameter in * gh-5386: Fix cookie parameter in * gh-5386: Update test file * gh-5386: Fix cookie parameter in * gh-5386: Fix cookie parameter in * gh-5386: Regenerate samples * gh-5386: Fix test * Added Spring CookieValue tests Co-authored-by: Gonzalo * Add missing `@Generated` annotation. (#5384) The annotation is present on other generated files when using jaxrs-spec, but it missing on model classes. * [scala] [template] scala model property style (#5486) * Model property naming style generic for scala * scala templates based on abstractScala regererated * docs generators updated * property format tests * add Agoda as the user (#5494) * Hide timestamp in Scala Play server samples (#5495) * hide timestamp in scala play server output * add chameleon82 to scala tech committee * Add a link to tech blog tech.medpeer.co.jp (#5498) * Add links to blog posts about OpenAPI Generator (#5508) * Typescript array alias array (#4981) * Add failing tests for typescript type declaration * Refactor array and map child type string fallback * Add unaliasSchema to typescript getTypeDeclaration * TypeScriptRxjs: Use Blob as file type declaration This was inadvertantly changed in https://github.com/OpenAPITools/openapi-generator/pull/5266 * [core] Sanitize/underscore/camelize cache expiry (#5484) The helper methods for sanitize/underscore/camelize were recently updated to cache values in static maps. This would lead to a memory leak in hosted environments as the maps had no cleanup/expiry. This moves those cached entries to Caffeine caches with expiry based on last access to allow the edge-case performance improvement gains on very large documents, without the memory leak in hosted or embedded environments. * Update README.md * Add a link to the conference paper (#5510) * Add a link to the conference paper * fix author list * [Slim4] Add Data Mocker middleware (#4978) * [Slim4] Store response schemas * [Slim4] Add Data Mocker middleware * [Slim4] Enhance Slim router * [Slim4] Enhance config * [Slim4] Fix data format key in object mocking * [Slim4] Add tests for Data Mocker middleware * [Slim4] Add Mock feature documentation * [Slim4] Refresh samples * [Java][Spring][Spring-Cloud] Fix #5144 - Use conditional package declaration to avoid unnecessary dependencies (#5145) * FIX: Use conditional package declaration to avoid unnecessary dependencies * DEV: Adjusted sample ClientConfiguration.java for async spring-cloud * fix(php): no need to serialize collections, Guzzle does that, fix #2292 (#3984) * fix(php): only serialize collections if !explode, Guzzle handles the rest, fix #2292 * fix(php): update petstore samples Co-authored-by: Mahdi Dibaiee * [php] replace $collectionFormat with $style (#5517) * php - remove $collectionFormat * update php openapi3 petstore sample * [BUG][scala][template] scala generate java.math.BigDecimal instead of scala type (#5514) * [BUG] scala generate java.math.BigDecimal instead of scala type * update docs/generators * [PHP] complete support for form style (#5519) * [BUG][PHP] Parameter property style not fully implemented (related to comment on PR #3984) * [AUTOGENERATED][PHP] Sample Files * update jackson dependency to newer version (#5527) * Fix Swift4 CI tests (#5540) * comment out swift 4 order tests * comment out store tests * Test Dart petstore client in CircleCI (#5544) * test dart2 in circle ci (jdk7) * fix tests * update package * fix dart installation * Add serialization of ModelComposed (#5551) * Fixes kwargs typos, removes E501s (#5552) * Update generic model to support nullable properties (#5568) * [DOC] Add link to integration test wiki in CONTRIBUTING.md (#5570) * Add link to integration test wiki * Add link to integration test wiki * [Kotlin][client] fix file upload (#5548) * [kotlin] fix file upload * [kotlin] fix file upload * [kotlin] fix file upload * [kotlin][client] fix jackson integration * [kotlin] fix file upload * [kotlin] fix file upload * update doc * [Java] Fix exception when OAuth2 token URL is a relative URL (#5535) * Add support for case when OAuth2 token URL is a relative URL * Add support for case when OAuth2 token URL is a relative URL * run scripts under bin * [Java] fix runtime exception when there are multiple auth methods (#5530) * fix runtime exception when there are multiple auth methods * Refactor a bit so that it does not cause conflict with relative url token branch * [markdown] Fix broken links when generating markdown (#5569) * [markdown] Fix broken links when generating markdown The `api.mustache` file generates links to the markdown model files. These links were previously brokeen. Additionally, the defaultPackage for markdown is "/Models", so this looked pretty in the heading for model files. So this prefix has been stripped from the header in `model.mustache`. * Re-generate Petstore samples for markdown * typescript-angular: fix zone-js version for angular 8 (#5585) * Add a link to the slide (#5590) * [Swift] fix URLSession file upload (#5546) * [swift5] - fix URLSession file upload * [swift5] - fix URLSession file upload * [swift5] fix file upload * [swift5] - fix URLSession file upload * [swift] add unit tests for file upload * [swift] update samples copyright * [swift] add option for API prefix (#5567) * [swift] add option for API prefix * [swift] update docs * [haskell-http-client] update stack; exclude problem time versions (#5589) * [go-experimental] Do not generate HTTP signature unit test for every generated SDK (#5588) * Do not generate HTTP signature unit test for every generated SDK * Add golang 1.14 to CI environment * fix unit test issues * remove script commands that were commented out * add support for ed25519 private keys * PR to solve 2 open issues on enums: #5091 and #4293 (#5477) * PR to solve 2 open issues on enums: Issue 5091 needs to generate enums also when the enum is directly in a param to a API call, instead than in a model. I did that by copying and adapting enum code from *model* to *api* Issue 4293 needs to decorate enums, for when enum names or enum values are repeated over the yaml definition. * PR to solve 2 open issues on enums: Issue 5091 needs to generate enums also when the enum is directly in a param to a API call, instead than in a model. I did that by copying and adapting enum code from *model* to *api* Issue 4293 needs to decorate enums, for when enum names or enum values are repeated over the yaml definition. * Enums decorated: with {{projectName}}_{{classVarName}}_{{enumName}}_ in the models, with {{projectName}}_{{classVarName}}_{{enumName}}_ in the operations. * Changes to the c client: - Removed white space. - Removed ToJSON and FromJSON function for the enums, since they are not used - Sanitized project name in the .java file. For example, this solves a problem with the issue #2338, where the yaml file had title: "Skycoin REST API." * Changes to the c client: - Removed white space. - Removed ToJSON and FromJSON function for the enums, since they are not used - Sanitized project name in the .java file. For example, this solves a problem with the issue #2338, where the yaml file had title: "Skycoin REST API." * Adds parseFlattenSpec (#5526) * Adds parseFlattenSpec, updates tests and helper functions * Adds parseSPec invocation inside parseFlattenSpec * Scala-Akka: Add missing body to PATCH requests (#5605) * NodeJS - Adds missing keyword (#5606) * [jaxrs-cxf-cdi] Support PATCH httpMethod (#5574) Update the required CXF version to 3.1.2 since PATCH support appeared with this version. Add the cxf PATCH annotation to the imports so that the generated code when defining a PATCH api compiles. * fix default value for abstract scala and scalatra server impl (#5578) * [Java] Generated API class has wrong dataType and does not compile Issue (#5331) * add unit test assertion * add check for composed schema * add support for x-allOf-name * change x-allOf-name to x-all-of-name * Add more troubleshooting information * Add more troubleshooting information * Add more troubleshooting information * Add more troubleshooting information * [swift5] stop hiding network error (#5603) * [swift5] stop hiding network error * [swift5] stop hiding network error * [scala][templates] java 8 dates support (#5291) * [scala][akka-http-client] java8 dates support * scala-akka readme doc updated * DateSerializers renamed * rename serializers * move date-library option to abstractScala * generators docs updated * enum defined for date libraries * Backport to scala-http-client * fix scala-akka-client date serializers * fix typo in docs * switch scala templates to java8 (jsr-310) date library by default * update scala samples with java8 date library * update scala generators docs with java8 default date library * fix scala-play-server generator cli options as only java8 dateLibrary supported * fix scalaz DateTimeCodecs template to support java8 * scalaz ci test againt java7 removed as it generate scala 2.11.8 client which is java8 based * update doc * Adding Response Interceptor (#5500) * added Response interceptor for native clients * added Response interceptor for native clients * [k6] Add blog post about using the k6 generator (#5608) * [Kotlin] Remove kotlin-reflect dependency when not needed (#5502) * Remove kotlin-reflect dependency when using CodeGen * Update Kotlin tests * Regenerated unit test samples * Remove newline in generated build.gradle files * [typescript-fetch] add interfaces, withInterfaces (#5612) * typescript-fetch: interfaces, first draft * fix name in description * [scala] Regenerate akka sample (#5622) * scala-version 2.11.12 (#5618) * micheleISEP->michelealbano (#5625) * [Powershell] refactor the client generator (#5629) * add api client * add local variables * add configuration * add header/query/form parameter support * add partial header * add auth, fix parameters type * fix accept, content type * url query string * fix path, header * remove dep on C# client * fix method naming with package name * fix object * convert result from json * better response handling * remove tostring method * fix model doc * fix default module * generate api test files * better api, model tests * fix add pet * add appveyor * fix accept, content type * add petstore tests * fix form parameters * test delete * better file handling (upload) * better code sample * add package version, better doc * delete unused files * fix header parameters * clean up api client * update samples * support query parameter * better method and parameter naming * minor formatting change * better doc, fix cookie parameter * better doc * add api prefix support * better api nam prefix option * fix configuration * throw errors for required parameter * fix authentication * add try catch block to sample code * rename model * use debug, clean up comment * revise code * move bin script * update doc * add new file * better map support * [PowerShell] minor improvements and bug fixes (#5635) * add output type, minor format fix * minor test improvement * Port client updates to server (#5634) * Revert "scala-version 2.11.12 (#5618)" This reverts commit 6b984a926a0f99120a4ad80cef73bee19f8614cd. * update release date * Handle negative response from the server (#5649) * Fix integration tests (Travis, CircleCI) (#5672) * fix php tests * fix scala tests * update ts angular v6 rest * fix user create test * fix spring cloud test * comment out user delete * fix angular v7 tests * fix user test * fix tests * fix go exp tests * commented out delete user tests * comment out delete user tests in go openapi 3 * fix clojure tests * [PowerShell] Fixes typo (#5648) * Solving issue #5623 and supporting bools for C client label:"Client: C" (#5624) * Removed stray "printf"s in modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java * Support for booleans in C client * Update README.md * Change to C API mustache files to solve issue #5623 * Debugging of C's modle-body.mustache, as suggested by ityuhui * Final changes suggested by ityuhui * [PowerShell] Fix map type (#5638) * fix map type * remove output type, fix appveyor * test macos * comment out failing scala test * fix typo: configuration * Revert "comment out failing scala test" This reverts commit 1dcf84ffcbb7ab520938ae7c75d60a8329f71478. * [powershell-experimental] Protects against stackoverflow when OAS spec has circular references (#5646) * protects against stackoverflow when OAS spec has circular references * protects against stackoverflow when OAS spec has circular references * Adds configuration option to skip certificate check. Fixes a typo. Fixes an issue which was restricting from cookie to get consumed (#5657) * [k6] bugfixes to improve the output script (#5614) * [k6] Skip appDescription escaping * [k6] Fix variable identifier in output * [k6] Fix bug with reserved words handling * [C][Client] Check the pointer before deleting operation to avoid core dump label:"Client C" (#5626) * [C-libcurl] Check the pointer before deleting operation to avoid core dump * [C-libcurl] Check the pointer before deleting operation, update sample * [kotlin][client] Add Jackson to interface properties and remove extra line feed (#5459) * [kotlin][client] Ensure Jackson annotations are consistent with interface vars * [kotlin][client] Rebuild samples * [kotlin][client] Some kotlin client enhancements - Don't use JsonFormat for Date objects, this should be controlled via a custom serializer/deserializer or a turning on and off serialization features of Jackson. I've updated the jacksonObjectMapper config to write the dates as strings, which I think was intended in the original commit. https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/SerializationFeature.html#WRITE_DATES_AS_TIMESTAMPS https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/cfg/MapperConfig.html#getDateFormat-- - Dont' use @JsonFormat(shape = JsonFormat.Shape.OBJECT) for enums. This causes Enums to be formatted as objects with an internal "value" field. In reality, OpenAPI enums are just strings without properties and should be treated as a string. https://www.baeldung.com/jackson-serialize-enums#2-enum-as-json-object - Add's Kotlin use site annotation @get: to JsonProperty for parent interface properties. Otherwise Kotlin will warn: "This annotation is not applicable to target 'member property without backing field or delegate'" - Add's JsonTypeInfo annotations to interfaces for inheritance. This was copied verbatim from the kotlin-spring generator. https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/kotlin-spring/typeInfoAnnotation.mustache * [kotlin][client] Rebuild kotlin samples * Remove scala version in parent pom (#5647) * [asciidoc] Allow the inclusion of additional documentation to t… (#5260) * [asccidoc] Allow the inclusion of additional documentation to the asccidoc generated Resolves #5228 * [jaxrs-reasteasy-eap] Fix invalid Bean Validation annotations for Longs (#5659) * fix issue #5658 * update samples * [PowerShell] Test powershell petstore client in Appveyor (#5674) * remove scala version in parent pom * test ps petstore in appveyor * fix command * build and import * fix import module * fix import * skip module import * run multiple commands * move to test script * test ps exit * fix exit * check last status code * clean tests * exit last code * add import * change dir * skip build failure * fix check * trigger build failure * fail fast * restore c# test * new line comment * add powershell exp to ensure up to date script * [PowerShell][Experimental] Better docstring (#5688) * add docstring to powershell module * add doc string * Nodejs express js packages update (#5675) * Updated to new nodejs packages, depending heavily on express-openapi-validator. Requires quite a change in code. Updated the business-logic in the controllers/Controller.js file. Logger now records also timestamp of events. Files are uploaded according to definition in config.js file * Removed commented-out code; Changed openApi document extensions to suit new express-openapi-validator definition; multipart and file uploading is supported now; Automatic response returns the values the were sent in the request * fixed README documentation, fixed a mistage in package.json/mustache * added generated files that were created when running the ./bin/test file * [go-experimental] Fix nullable support (#5414) * Fix nullable support in go-experimental client * Fix support for models with parents and container fields * Make sure that oneOf interfaces serialize properly even if they're required (non-pointers) on other models * Spaces => tabs * Regenerate samples * Make some methods of nullables pointer-receivers, add tests * Improve the Get/Set logic to make usage more convenient * Address review * [kotlin][client] make base path globally configurable (#5450) * [kotlin][client] make base path configurable * [kotlin][client] update pet project * [kotlin][client] set default base path * [kotlin][client] set default base path * [kotlin][client] set default base path * Add michelealbano to C technical committee (#5692) * [Go][Experimental] Rename extensions from x-basetype to x-go-base-type (#5691) * rename go vendor extension * update go exp petstore samples oas3 * comment out powershell petstore in uptodate script * remove processing of http_signature_test.mustache (#5696) * Fix generation of oneOf interfaces for oneOf usage in properties (#5400) * Fix generation of oneOf interfaces for oneOf usage in properties * Only generate oneOf interface models when oneOf is defined * use basic parsing (#5702) * [python/asyncio] explicitly close client session via async context manager (#5621) * [gradle] Include engine option for handlebars generation (#5686) * [codegen][Go] Fix compilation error of generated go code when schema is free form object (#5391) * Fix code generation for free-form objects in go-experimental * Execute scripts in bin directory * Add more use cases for open-ended types * Add more use cases for open-ended types * Add more use cases for open-ended types * add code comments * Better name for test properties * handle scenario when type is arbitrary * handle interface{} scenario * handle interface{} scenario * add helper function isAnyType * isAnyType function * implementation of isAnyType function * fix javadoc issue * handle interface{} scenario * use equals comparison instead of == * merge from master * Add code documentation * add code comments, remove unused min/max attribute, fix equals method * Handle 'anytype' use case * add code comments * override postProcessModelProperty to set vendor extension * Use vendorExtensions.x-golang-is-container * fix compilation error of generated code * fix compilation error of generated code * fix compilation error of generated code * [Java] Update version of maven-surefire-plugin (#5509) * use more recent version of maven-surefire-plugin * use more recent version of maven-surefire-plugin * higher debug level for troubleshooting ci issue * temporarily increase debug log to help troubleshoot * Use local instance of pet store service for unit test purpose * Add more logging to troubleshoot unit test failures * Add more logging to troubleshoot unit test failures * Add more logging to troubleshoot unit test failures * Add more logging to troubleshoot unit test failures * Add more logging to troubleshoot unit test failures * use random ID for Java unit test instead of fixed id * add code comments and specify URL for java unit test * reenable quiet argument * fix java unit test issues * fix java unit test issues * Revert "fix java unit test issues" This reverts commit e8508416ff0f2aeb568e3f916b013dc967390f74. * fix java unit test issues * Generator for JavaScript/Apollo Client (#5645) Co-authored-by: William Cheng * Add yutaka0m to Kotlin Technical Committee (#5716) * Add Scala client scripts to ensure-uptodate process (#5712) * add scala client to ensure-upto-date * new scala-akka petstore oas3 folder * regenerate scala akka oas2 petstore * remove script * Minor improvments to JS apollo generator (#5714) * minor improvments to js apollo generator * comment out apollo * [Rust Server] Handle text/xml correctly (#5660) * [Rust Server] Handle text/xml correctly Treat application/xml the same as text/xml as per RFC 7303 * [Rust Server] Add test for text/xml * Update samples * 4.3.0 release (#5721) * update samples (#5722) * 5211 - Use allVars instead of vars for Kotlin client (#5396) * [C++] [Qt5] fixed cpp-client-qt5 HttpRequestWorker requests crashing on timeout... (#5651) * - fixed cpp-client-qt5 HttpRequestWorker requests crashing on timeout when they have actually NOT timed out (were calling back into a deleted struct). * #minor fixes after review * Regenerate changed files Co-authored-by: valentin Bisson Co-authored-by: etherealjoy * Fix SSL setting in checkout script (#5725) * fix ssl setting in checkout script * add check for sbt-openapi-generator * [C] fix decode funtion (#5642) * fix function names and add parameter to return decoded bytes length from base64decode function * format base64decode function to avoid unnecessary malloc and fix wrong length assigning * update the pointer assigning for some reason var++ / *var++ cannot be done on int *var, hence making a local variable which is incremented and at the end it is assigned to the pointer. * Update bump.sh to go SNAPSHOT to version (#5727) * Fix CI failures (#5734) * update ci to use petstore 1.0.4 * comment out test * comment out test * comment out update user test * comment out more tests * use latest petstore * comment out updatePetWithForm * comment out update pet test * fix file path in release_version_update_docs (#5724) * better appveyor test (#5739) * better readme, type mapping, new option (#5740) * Remove warning for unused camel case vendor extension for Qt5 client and server (#5731) * [PS][Experimental] Add multiple server support (#5741) * code comment * add get host setting * add multiple server support * add default headers support (#5746) * [C][Client] Support SSL client authentication for the c client (#5719) * [C][Client] Support SSL client authentication * [C][Client] Support SSL client authentication, update sample * [kotlin] Fix #5247 incorrect enum parameter type for arrays (#5435) * [Erlang-Server] security definition context changes don't propagate to handler (#5751) * Map Merge Context & Params handler requires context and params to be merged before returned to user defined request_handler. * post build & shell script * Delete VERSION * [PS][PowerShell] fix passthru, use switch instead of bool (#5768) * fix passthru, use switch * remove line * comment out kotlin vertx server test (#5767) * add support for common verbs (#5771) * fix request.on_complete message when tempfile is nil (#5745) * fix request.on_complete message when tempfile is nil * update faraday client sample * add openapi3 client samples * use prepare instead of new (#5773) * use Initialize instead of prepare (#5777) * add map example (#5778) * [PS][Experimental] Better common verb handling (#5783) * better common verb handling * better debugging * add option to customize common verb * [cli][docker] Better expose version/sha information of builds (#5736) * [cli] Some CLI improvements… * Introduce --version * Introduce --help * Add --sha to version command for short SHA display * Output Version and SHA details * In new --version output, display repo and doc site Additional cleanup to suppress warnings and code quality. * [docker] Adds labels for metadata This adds image labels to store metadata on the online and cli docker images, using standard labels: * org.opencontainers.image.created * org.opencontainers.image.revision * org.opencontainers.image.title * org.opencontainers.image.version These can be inspected via 'docker inspect IMAGE_NAME' and may be useful in tooling/automation or bug reports submitted by users. For more details on these labels, see: https://github.com/opencontainers/image-spec/blob/master/annotations.md * Include version --full for equiv to --version * [cli] Add --global-property for -D replacement (#5687) -D option has been deprecated as it was previously used to: * Pass "system properties" * Pass additional properties This was confusing because we already have --additional-properties and because Java System Properties are passed as -D before program arguments. Confusion around the -D option had existed for some time, but when we introduced the thread-safe GlobalSettings to avoid overwriting Java System Properties, we created a hard break from Java System Properties in the generator. This also disconnected the previous "system properties" from accepting additional properties. Once these newly deprecated methods are removed, we will have a clear separation of concerns between: * Java System Properties * Global generator properties (used as workflow context) * Additional properties (used as generator options) This commit marks multiple places for cleanup in 5.0. These will be breaking changes, and lower effort to break in 5.0 with deprecation warnings now rather than adding sibling properties throughout the code and potentially introducing logic errors. * [dart-dio] Fixes --model-name-suffix having no effect (#5669) Fixes #5409 * [go-experimental][go][client] Remove unreachable code in go client API methods (#5611) * [go-experimental][go][client] Remove unreachable code in go client API methods * Properly regenerate all samples * please add openVALIDATION Project to readme (#5534) * added openVALIDATION Project to readme * Update README.md Co-Authored-By: Akihito Nakano Co-authored-by: Akihito Nakano * [Csharp-client] Complex form parameters are not serialized as application/json (#5787) * [csharp-client] Complex form parameters are now correctly serialized as json. Reference: http://spec.openapis.org/oas/v3.0.3#special-considerations-for-multipart-content * Updated bin/windows csharp sample generation scripts to point to the correct directories * Updated csharp samples Co-authored-by: Olivier Leonard * fix scala-akka java8 serializers (#5742) * fix scala-akka java8 serializers * regenerate samples for akka-http * [typescript-axios][client] Unnecessary imports occurs when using withSeparateModelsAndApi (#5797) * add ts-ignore * add petstore sample * use write verbose in auth, better api doc (#5804) * [PS][Experimental] add withHttpInfo support, fix "null" return (#5811) * add with http support * use full name in tests * using full name in test * skip type check * [PS][Experimental] Add tests for array of object in response (#5814) * debugging array response * fix find pet tests * better tests to ignore order * [codegen] Use once(LOGGER) to reduce amount of identical warning messages (#5808) * Warn once instead of many times when the log statement does not have contextual information * Warn once instead of many times when the log statement does not have contextual information * make name cache configurabl (#5775) * [codegen] Cachesize config seconds (#5816) * make name cache configurable * Address review comments * [Python-experimental] Documentation enhancement for oneOf schema and minor err msg improvement (#5791) * Add documentation to generated code * Improve error message * Improve documentation * Improve documentation * Improve documentation * Improve documentation * Improve documentation * Improve documentation * Run sample scripts * Address review comments * Address review comments * Fix problem in python error message * rename hostsetting, validate base url (#5821) * fix array return (#5822) * Scala akka-http server (#5758) * Scala akka-http server base implementation * [scala-akka-http-server] petStore samples * Improved the formatting of generated files * Updated scala-akka-http server samples * [scala-akka-http-server] the groupId, artifactId and artifactVersion default value are used as intended. * Fixed the default operation not being correctly generated on parameterless operations * Added build.sbt.mustache supporting file * Updated scala-akka-http server samples * ScalaAkkaHttpServer: Fixed a String.format call to use Locale.ROOT for locale * [scala-akka-http-server] Fixed defaultValue being escaped during generation * Added scala-akka-http.md * Replaced all "⇒" character with "=>" to retain compatibility with scala 2.13 * [scala-akka-http] Added a config option akkaHttpVersion It's set in the generated build.sbt. * Updated scala-akka-http server samples * [scala-akka-http] More accurate akkaHttpVersion parsing * Updated scala-akka-http.md * [scala-akka-http] Changed the akka-http version check to fix the generation of StringDirectives * Updated scala-akka-http samples * updated scala-akka-http.md Co-authored-by: Olivier Leonard * Minor improvements to scala akka server (#5823) * minor improvements to scala akka server * add samples * update doc * Update swagger parser to 2.0.19 (#5413) * update swagger parser to 2.0.18 * fix online server exception * Revert "fix online server exception" This reverts commit fe3cb5221f362c00b176fa81411eaf368f0e446d. * update parser to 2.0.19 * [jaxrs-cxf-cdi] fix allOf equals and hashCode (#5756) When generating model that use allOf, the equals and hashCode methods must take the parent class into account. * [BUG] [KOTLIN] Fix default value generation for Kotlin Strings (#5776) * fix default value generation for kotlin * add updated pet templates * Revert "add updated pet templates" This reverts commit 7e8168ad * regen pet store projects code * tests for models for C-libcurl generator (#5699) * First try to generate unit tests for the models of the C-libcurl client. Models into models are not supported yet. * Added unit tests for the modules of the C-libcurl client to the git repository. * Support for objects having other objects as properties, for the C-libcurl client generator * Proper formatting of generated code * use allVars to cover all properties (#5835) * support enum in parameters (#5838) * [C++] [Qt5] [Client] fixed cpp-client-qt5 HttpRequestWorker contentCompression variables initialization (#5834) When contentCompression is not enabled, the variables isRequestCompressionEnabled and isResponseCompressionEnabled in HttpRequestWorker are not being initialized. Without initialization the compress function could be called and the request content could be an empty QByteArray instead of original request body. * minor fix to http basic auth (#5839) * Scala akka http server - normalization of some vendor extensions (#5829) * [scala-akka-http-server] Normalized vendor extension "paths" to "x-paths" * [scala-akka-http-server] Normalized vendor extension "hasDefaultValue", "isDefault", "specificMarshallers", "fileParams", "nonFileParams" Co-authored-by: Olivier Leonard * Add Bouill to the Scala technical committee (#5843) * C client generator improvements to support petstore. Solves #5836 (#5837) * C client generator improvement to support: openapi-generator/modules/openapi-generator/src/test/resources/3_0/petstore.yaml * Improvements to the C client generator: - moved base64* from apiClient.c to binary.h/binary.c - changed CR/LF to LF in binary.h/binary.c * C client generator: better support for base64encode / base64decode * Add openapi.yaml file to Java clients (#5765) * Add openapi.yaml file to Java client * Move supporting template file to Java root * Update petstore clients * [codegen] Fix 'super.HashCode' for oneOf and allOf Implementations (retry) (#5830) * Added hasVars after completion of all model post-processing (#5587) * Post ensure-up-to-date * Update to check the size of vars and not assume non-null * update mysql samples * Add default case to handle response code (#5825) * add default case to handle response code * fix default response code * add test for isDefault * fix user id in scala tc * Fix for Issue #4840 [BUG][JAVA][spring-mvc] Generated Code for Map of Maps Return Type does not compile (#5240) * add parent for allOf only (#5851) * Add pythonSrcRoot option to python servers (aiohttp/flask/blueplanet) to support src/ layout projects [and reenable/fix all python server tests] (#5423) * python server: Add pythonSrcRoot option This will allow the python project to be in a subdirectory (as specified in pythonSrcRoot). That could mean following the src layout with sources under src/ or lib/. Multi-language projects might use a sub directory like python/, or whatever makes sense for the project. By default, the pythonSrcRoot is "", meaning the existing behavior is the default. * python server: update template files to support pythonSrcRoot * python server: update docs to add pythonSrcRoot option * python server: add pythonSrcRoot sample script * python server: build sample srclayout project * [Python] copy test files preserving history * [Python] Make a conflict to preserve file copy history * [Python] customize pom.xml for src layout tests * [Python] add python-aiohttp-srclayout tests * [Python] Fix server tests by updating requirements Reverts the PR that disabled python2 server tests: https://github.com/OpenAPITools/openapi-generator/pull/4949 Reverts commits that disabled python3 server tests: 9adfedbfbb45c7059e64b3d9a285710bded4fb62 17ee990baaa80585242c7a07d64e2be4888fcfd0 Issue about the python 3 tests: https://github.com/OpenAPITools/openapi-generator/issues/5235 I couldn't find an issue about the python2 tests being disabled. I'm guessing build errors like the following were the trigger: https://travis-ci.org/github/OpenAPITools/openapi-generator/builds/634238181 Let's see what breaks! * [Python] Copy setup.py to python-aiohttp * [Python] Save history while copying setup.py to python-aiohttp * [Python] Add aiohttp server setup.py * [Python] Fix python server tests with src layout * [Python] bump Flask-Testing version * [Python] Pin pyyaml for py2.7 flask server * [Python] simplify flask server requirements * consolidate server tests * [Python] rebuild python server samples * [Python] Fix python server requirements for older pythons Documented minimum python version for our aiohttp server is 3.5. Documented minimum python version for our flask server is 3.4. Connexion 2.3 is the last version to support python 3.4 and 3.5, so fix the version pinning to correctly select <=2.3 for these EOL python versions. Newer pythons should get the latest if possible as there many relevant bug fixes. Werkzeug also needs to be pinned for these old versions in the aiohttp server just like for the flask server. 3.4 and 3.5 are EOL. We really should increase the minimum supported version, but that is for another PR to do. * stop error globally (#5858) * [PS][Experimental] Add validations to model (#5842) * add validations to model * better error message * improve validation * Updates to allow the setting of the dateTime format string (#5763) * [PS] Select Content-Type in the response (#5872) * better return type handling * update tempalte * better documentation * fix greater than * various enhancement to ps exp generator (#5875) * [C#] dependency upgrade (#5870) * Updating packages version (#5313) * Add support to RestSharp version 106.10.1 Restsharp 106.10.1 needs the Content Lenght as a parameter to AddFile method * Updating RestSharp Version Updating RestSharp Version * Update netcore_project.mustache * Update netcore_testproject.mustache * Update Project.mustache * Updating packages version Updating packages version * Updating packages version Updating packages version * Updating packages version Updating packages version * Updating packages version Updating packages version * Updating packages version Updating packages version * Updating packages version Updating packages version * Execute task async obsolete Use ExecuteAsync instead * update csharp samples Co-authored-by: William Cheng * [csharp] Library upgrade fix (#5848) * On .net45 framework, Restsharp version is updated to 106.10.1 Otherwise, it stays on version 105.1.0 * Added additionalProperties for library versions and target frameworks * Removed unused properties * Added an additional property to test for a specific version of RestSharp * Updated csharp samples * Fixed nuspec.mustache to use library specific additional properties * Updated csharp samples * Updating CI/samples.ci csharp petstore test project file. * Updated csharp.md Co-authored-by: Olivier Leonard * [csharp-client] Restored tests on csharp samples (#5879) * Restored tests on csharp samples * Restored a reference to the file used to test file uploads Co-authored-by: Olivier Leonard * update samples Co-authored-by: Igor Quirino Co-authored-by: Bouillie <34162532+Bouillie@users.noreply.github.com> Co-authored-by: Olivier Leonard * [Csharp-client] Complex form parameters are not serialized as application/json (#5849) * [csharp-client] Complex form parameters are now correctly serialized as json. * Updated csharp samples Co-authored-by: Olivier Leonard * docs: removes Nico from technical committee (#5883) * [PS] better handle special variables (#5885) * add variable * fix reserved words * update ps doc * [PS] add file post-processing to the PowerShell generator (#5864) * add post process to ps generator * add import * fix merge issue * consolidate header selection functions (#5889) * [Java-client] Add maven-compiler-plugin in pom.xml and enable linter checks by default (#5866) * Add maven-compiler-plugin plugin in Java pom.xml and enable linter checks by default * Add maven-compiler-plugin plugin in Java pom.xml and enable linter checks by default * Update enum.mustache (#5793) https://github.com/OpenAPITools/openapi-generator/issues/5792 * Update modelGeneric.mustache (#5378) * Update modelGeneric.mustache If maxlength is specified for a property type enum it there should be .ToString() appended before length check * ran the csharp petstore bar and updated the file Co-authored-by: Shweta Shukla * Fix Scala sttp generator packages (#5890) * Fix Scala sttp generator packages * Change package to parameterised * [Dart] Fix "basic" auth method and Add Bearer token support (#5743) * added auth check and lint * fixed basic auth condition * Added bearer auth * updated samples * update dart petstore samples Co-authored-by: William Cheng * Add date time format annotation on pojo for model query parameters (#5437) * Add date time format annotation on pojo for model query parameters * Regenetare samples * update spring samples Co-authored-by: William Cheng * [mysql] Add basic SQL queries (#5757) * Add basic SQL queries template * Add namedParametersEnabled option * Move model related SQLs into Model folder * Update README template * Refresh samples * [enhancement] [jaxrs-spec] Add builders to models (#4930) * Update formatting in jaxrs-spec POJOs * Add generateBuilders option * Update formatting in jaxrs-spec POJOs * Disable the builders generation by default * Ensure samples are up-to-date * Revert newline change * Run ensure-up-to-date * update doc * fix merge conflicts Co-authored-by: Artem Shubovych Co-authored-by: William Cheng * Update generated build files for REST Assured (#5873) * REST Assured 4.3.0 * Jackson 2.10.3 * Gson 2.8.6, GSON-Fire 1.8.4 * Okio 1.17.5 * Joda-Time 2.10.5 * ThreeTenBP 1.4.3 * Added missing dependencies for Bean Validation * Added missing dependencies for `@Generated` annotation * Refresh REST Assured sample project * [Java][Feign] Bug fix in @Param annotation (#5250) * FIX-5249 fix @Param annotation for Feign-client code generation Use paramName instead of baseName in order to make mapping in @Headers section fit the param-value. * update samples * FIX-5249 fix @Param annotation for Feign-client code generation Use paramName instead of baseName in order to make mapping in @Headers section fit the param-value. Co-authored-by: Christoph Preißner Co-authored-by: William Cheng * [Java] Increase java compiler stack size to handle large files (#5901) * increase java compiler stack size to handle large files * increase java compiler stack size to handle large files * Added emineo to list of companies on website (#5905) * add emineo to the list * [swift5] fix warning (#5900) * update bitwise config (#5904) * [Java] Discriminator lookup should not be case insensitive by default (#5894) * Add 'discriminatorCaseSensitive' property * Discriminator value lookup should not be case insensitive * fix typo * run scripts * execute ./bin/utils/export_docs_generators.sh * fix discriminator mapping, add code comments * minor fix to users.yml * Add a link to optim blog post (#5922) * [Java] Fix inclusive max validation (#5908) Co-authored-by: erikmolin * add bearer auth support to csharp netcore (#5921) * [Python][aiohttp] create venv as rule (#5913) * create venv as rule * create venv as rule II * Fix for Result Model Name collision (#5923) * Fix for Result Model Name collision * Run Scripts Co-authored-by: Sebastian Ohm * [Dart] Remove content type from header when content type is not specified (#5752) * accept empty content type * fixed test * updated samples * additional comment out * update dependency for java client (#5926) * Update axios dependency to the new minor version 0.19.0 (#5867) * Update axios dependency to 0.19.0 Axios (version 0.18.0) used by typescript-axios generator is more than two years old (released in Feb 2018). Axios 0.19.2 released earlier this year contains a lot of fixes and functionality, I recommend updating to 0.19.2. * Ran ./bin/typescript-axios-petstore-all.sh to update package.json in ./samples Co-authored-by: Chandra Yalangi * fixed README/doc of bearer auth support for csharp-netcore (#5931) * fix duplicated semi-colon in c# model (#5934) * [Python-experimental] Use DER encoding for ECDSA signatures, add parameter to configure hash algorithm (#5924) * Use DER encoding for ECDSA signatures * Use DER encoding for ECDSA signatures * Use DER encoding for ECDSA signatures * Use DER encoding for ECDSA signatures * fix python unit tests for http message signature * Fix error message * format python code * format python code * [Python-experimental] Fix TypeError: unhashable type: 'list' (#5810) * handle scenario when value is a list, fix TypeError: unhashable type: 'list' * Add __hash__ function * use list instead of set * use list instead of set * use list instead of set * use list instead of set * use list instead of set * use list instead of set * [python/asyncio] fix passing proxy parameters to aiohttp (#5943) * [C][Client]Fix data lost when libcurl write-data callback function is called multiple times (#5828) * [C][Client]Fix the defect of data lost when libcurl write-data callback function (configured by CURLOPT_WRITEFUNCTION) is called multiple times. * [C][Client]Fix data lost when libcurl write-data callback function is called multiple times (Reset count) * [typescript-axios][client] Allow apiKey type Promise. (#5953) * change apiKey type * recreate sample * Add YITU Technology to the user list (#5967) * add yitu to the user list * use yitu technology * Use model as body param for generateAliasAsModel (#4569) * generateAliasAsModel: Use model name as body param * Update samples * resolve merge conflicts in the core generator files * fix merge conflicts in pom.xml * Resolve Elm merge conflicts * [Rust Server] Fix up merge conflicts * Update samples * [Rust Server] Add debug log for rust-server-petstore.sh * update samples * update more samples * fix dart openapi-generator version * remove deprecated c# files * update meta codegen * fix port in pom.xml * fix port in sample * update jaxrs cxf version Co-authored-by: sunn <33183834+etherealjoy@users.noreply.github.com> Co-authored-by: dwlabcube <46682038+dwlabcube@users.noreply.github.com> Co-authored-by: Herve DARRITCHON Co-authored-by: Akihito Nakano Co-authored-by: Johnny Peck Co-authored-by: Michele Albano Co-authored-by: Jim Schubert Co-authored-by: Nikita Co-authored-by: Alexey Makhrov Co-authored-by: val Co-authored-by: Bruno Coelho <4brunu@users.noreply.github.com> Co-authored-by: Aleksandr Nekrasov Co-authored-by: Akira Tanimura Co-authored-by: Justin Co-authored-by: Justin Black Co-authored-by: Jiri Kuncar Co-authored-by: Hui Yu Co-authored-by: Yutaka Miyamae <48900426+yutaka0m@users.noreply.github.com> Co-authored-by: Mateusz Szychowski (Muttley) Co-authored-by: Jorge Rodriguez Co-authored-by: Gonzalo Co-authored-by: ChristianCiach Co-authored-by: Bodo Graumann Co-authored-by: Yuriy Belenko Co-authored-by: Daniel Klessing Co-authored-by: copypasta-g <53397163+copypasta-g@users.noreply.github.com> Co-authored-by: Mahdi Dibaiee Co-authored-by: Sebastien Rosset Co-authored-by: siada Co-authored-by: Samuel Hoffstaetter Co-authored-by: Esteban Gehring Co-authored-by: Jon Schoning Co-authored-by: Marcin Kubala Co-authored-by: anoohya-n <51289018+anoohya-n@users.noreply.github.com> Co-authored-by: Antoine Reilles Co-authored-by: Clemens Angermann Co-authored-by: Mostafa Moradian Co-authored-by: Adam Co-authored-by: Lars Hvam Co-authored-by: sullis Co-authored-by: Vikrant Balyan Co-authored-by: Matt Traynham Co-authored-by: LEZIER-S2 <60382243+LEZIER-S2@users.noreply.github.com> Co-authored-by: Thomas Enderle Co-authored-by: YishTish Co-authored-by: Slavek Kabrda Co-authored-by: Tomasz Prus Co-authored-by: Erica Kastner Co-authored-by: Richard Whitehouse Co-authored-by: valentin Bisson Co-authored-by: etherealjoy Co-authored-by: Hemant Zope <42613258+zhemant@users.noreply.github.com> Co-authored-by: Even André Fiskvik Co-authored-by: ehansen31 Co-authored-by: Timur Platonov Co-authored-by: Josh Burton Co-authored-by: Ilja leyberman <7ilya@gmx.de> Co-authored-by: Bouillie <34162532+Bouillie@users.noreply.github.com> Co-authored-by: Olivier Leonard Co-authored-by: tanmen Co-authored-by: Alex Buchkovsky Co-authored-by: Natan Laverde Co-authored-by: Nicholas Muesch Co-authored-by: jburgess <11861789+jburgess@users.noreply.github.com> Co-authored-by: emileonhardt <40421857+emileonhardt@users.noreply.github.com> Co-authored-by: Jacob Floyd Co-authored-by: Igor Quirino Co-authored-by: Nico König Co-authored-by: https://gitlab.com/selankon Co-authored-by: Shweta Shukla <25539662+shwetashukla@users.noreply.github.com> Co-authored-by: Shweta Shukla Co-authored-by: Bartek Kowalik Co-authored-by: Shinya Sugmoto <34866626+gasugesu@users.noreply.github.com> Co-authored-by: Artem Shubovych Co-authored-by: Artem Shubovych Co-authored-by: Jochen Schalanda Co-authored-by: Chr1st0ph Co-authored-by: Christoph Preißner Co-authored-by: Erikmolin Co-authored-by: erikmolin Co-authored-by: Nicolas Homble Co-authored-by: Sebastian <63457660+sebohdev@users.noreply.github.com> Co-authored-by: Sebastian Ohm Co-authored-by: chandra-gh <63366477+chandra-gh@users.noreply.github.com> Co-authored-by: Chandra Yalangi Co-authored-by: Fabian Freund Co-authored-by: Erik Timmers * Revert "Sync master to 5.0.x (#5968)" This reverts commit 90dd7a03418ff4554ae8351b325eb86ee5794e92. * File return type fix (#5644) * file return type fix * Update client.mustache * go: use PathEscape instead of QueryEscape to escape path params (#6618) * [Go] support problem details HTTP API (#6793) Based on https://tools.ietf.org/html/draft-ietf-appsawg-http-problem-00, the content-type would be `application/problem+json` * Update to reset httpRepsonse.Body (#6948) * Update to reset httpRepsonse.Body such that is available to client consumers via the returned httpResponse variable. * update samples Co-authored-by: William Cheng * fix http bear auth documentation for go clinets (#7312) * [Go]: Interface definitions for api functions (#5914) Introduces a new "generateInterfaces" option, allowing for better testability of generated clients * add aws v4 signature support to go-experimental (#7326) * [Go] replace `go` generator with `go-experimental` generator (#7337) * replace go with go-experimental * update samples * extends with abstract go class * rearrange * remove deprecated * minor fix * remove go deprecated samples * update pom, clean up samples * mark generator as deprecated * [Go] minor format change, deprecate "withGoCodegenComment" option (#7375) * use tab in comment, remove withGoCodegenComment * deprecated option * [go][client] Fix API docs example generation (#7489) * [go][client] Fix API docs example * Generate samples * fix comment typo (#7605) * Unifies naming for isMap in Schema class properties (#7640) * Updates isMapModel + isMapContainer -> isMap * Removes git conflict characters * remove github.com/antihax/optional from go.sum (#7692) * Unifies naming for isArray in Schema class properties (#7691) * Updates key java files * Adds all lingering isArray fixes * Adds two files * Reverts two cs files * Fixes lingering isListContainer + isArrayModel references * Some ensure up to date updates * update doc to include proxy instruction (#7749) * Removes secondaryParam and hasMore (#7882) * Removes secondaryParam and hasMore * Fixes tests * Only uses bodyParam in groovy template * Fix a few issues with go examples generation (#7873) * Fix a few issues with go examples generation This fixes a bunch of issues seen when generating go examples, namely - Numbers aren't casted to the right type - The time import is missing - Enums are treated as regular models * Rebuild more samples * Use examples properly * Handle multiple instances in the same doc * Fix wrong array closure * Handle model arrays * Fix file and enum namespace * Regenerate samples * Handle maps of complex types * Handle oneOf * Fix padding * Fix enum doc * Removes links to basic types in arrays * Remove links to basic types in maps * Fix enum links * Minor indent fix * Handle review comments * Fixes to go API documentation generation (#7963) * More fixes to go doc generation * Regenerate samples * Fix indent * Remove additonal bracket on time objects * [Go] Fixes missing return statement (#8072) (#8090) * [GO][Client] return GenericOpenAPIError instead of error in Execute() (#8137) * error to GenericOpenAPIError * reformatted files * reformat files * spaces to tabs * update petstore examples * remove extra brackets * update sample generation * update go test cases * update openapi3 go tests * edit test samples * update documentation * Revert "[GO][Client] return GenericOpenAPIError instead of error in Execute() (#8137)" (#8427) This reverts commit 1562afea3980484a7f1819c4f51b0d53a44a009f. * [Go] Fix response body (#8439) * fix go response body * add missing import * [Go][Client] Secret key content string in http signing support (#8570) * accept private key content string * sample update * Add comments to new methods * update samples with comments * Update modules/openapi-generator/src/main/resources/go/signing.mustache Co-authored-by: Jiri Kuncar * Update modules/openapi-generator/src/main/resources/go/signing.mustache Co-authored-by: Jiri Kuncar * Update signing.mustache * update sample comments * Update modules/openapi-generator/src/main/resources/go/signing.mustache Co-authored-by: Sebastien Rosset * Update modules/openapi-generator/src/main/resources/go/signing.mustache Co-authored-by: Sebastien Rosset * update empty checks for privateKey Co-authored-by: Vikrant Balyan Co-authored-by: Jiri Kuncar Co-authored-by: Sebastien Rosset * Fix generated go client cannot upload file (#8393) * go client send **io.File body * run generate-samples for Go upload fix * [Go] bug fix (breaking), minor code format enhancement (#8715) * go minor code format enhnacement * fix required vars in the model new * remove comma * Add additional AWS v4 signature parameters to go client generator (#8706) * [GO] use latest available oauth2 version (#8764) * [GO] use latest available oauth2 version * update samples Co-authored-by: William Cheng * Apply template-patches/go-experimental-0003-custom-license-header.patch * Apply template-patches/go-experimental-0005-unstable-operations.patch * Apply template-patches/go-experimental-0006-operation-id-header.patch * Apply template-patches/go-experimental-0007-user-agent.patch * Apply template-patches/go-experimental-0008-code-example.patch * Apply template-patches/go-experimental-0009-export-request-methods.patch * Apply template-patches/go-experimental-redact-auth-debug-logs.patch * Apply template-patches/go-validate-enum-values.patch * Apply template-patches/go-examples-with-dd-site.patch * Move templates * Regenerate client from commit 7e667f1 of spec repo Co-authored-by: wing328 Co-authored-by: Jeremie Bresson Co-authored-by: Akihito Nakano Co-authored-by: Jim Schubert Co-authored-by: Martin Delille Co-authored-by: Tomasz Prus Co-authored-by: antihax Co-authored-by: John Wang Co-authored-by: Ville Skyttä Co-authored-by: ilk <984504+ilk@users.noreply.github.com> Co-authored-by: Matthias Ramsauer Co-authored-by: Andrew Co-authored-by: alex-korobko Co-authored-by: Diego Mascialino Co-authored-by: Jimmi Dyson Co-authored-by: Bilal Amarni Co-authored-by: Alok Prateek Co-authored-by: Thiago Arrais Co-authored-by: Slavek Kabrda Co-authored-by: Michael Cristina Co-authored-by: Slavek Kabrda Co-authored-by: Johan Brandhorst Co-authored-by: Kris Raney Co-authored-by: Quim Muntal Co-authored-by: Akira Tanimura Co-authored-by: Colin Arnott Co-authored-by: Hippolyte HENRY Co-authored-by: Colin Arnott Co-authored-by: Arvind Thirunarayanan Co-authored-by: dukov Co-authored-by: Marin Atanasov Nikolov Co-authored-by: Jiri Kuncar Co-authored-by: Michal Hornický Co-authored-by: Jérôme Co-authored-by: Tomasz Jakub Rup Co-authored-by: Sebastien Rosset Co-authored-by: LoveIsGrief Co-authored-by: sunn <33183834+etherealjoy@users.noreply.github.com> Co-authored-by: dwlabcube <46682038+dwlabcube@users.noreply.github.com> Co-authored-by: Herve DARRITCHON Co-authored-by: Johnny Peck Co-authored-by: Michele Albano Co-authored-by: Nikita Co-authored-by: Alexey Makhrov Co-authored-by: val Co-authored-by: Bruno Coelho <4brunu@users.noreply.github.com> Co-authored-by: Aleksandr Nekrasov Co-authored-by: Justin Co-authored-by: Justin Black Co-authored-by: Hui Yu Co-authored-by: Yutaka Miyamae <48900426+yutaka0m@users.noreply.github.com> Co-authored-by: Mateusz Szychowski (Muttley) Co-authored-by: Jorge Rodriguez Co-authored-by: Gonzalo Co-authored-by: ChristianCiach Co-authored-by: Bodo Graumann Co-authored-by: Yuriy Belenko Co-authored-by: Daniel Klessing Co-authored-by: copypasta-g <53397163+copypasta-g@users.noreply.github.com> Co-authored-by: Mahdi Dibaiee Co-authored-by: siada Co-authored-by: Samuel Hoffstaetter Co-authored-by: Esteban Gehring Co-authored-by: Jon Schoning Co-authored-by: Marcin Kubala Co-authored-by: anoohya-n <51289018+anoohya-n@users.noreply.github.com> Co-authored-by: Antoine Reilles Co-authored-by: Clemens Angermann Co-authored-by: Mostafa Moradian Co-authored-by: Adam Co-authored-by: Lars Hvam Co-authored-by: sullis Co-authored-by: Vikrant Balyan Co-authored-by: Matt Traynham Co-authored-by: LEZIER-S2 <60382243+LEZIER-S2@users.noreply.github.com> Co-authored-by: Thomas Enderle Co-authored-by: YishTish Co-authored-by: Erica Kastner Co-authored-by: Richard Whitehouse Co-authored-by: valentin Bisson Co-authored-by: etherealjoy Co-authored-by: Hemant Zope <42613258+zhemant@users.noreply.github.com> Co-authored-by: Even André Fiskvik Co-authored-by: ehansen31 Co-authored-by: Timur Platonov Co-authored-by: Josh Burton Co-authored-by: Ilja leyberman <7ilya@gmx.de> Co-authored-by: Bouillie <34162532+Bouillie@users.noreply.github.com> Co-authored-by: Olivier Leonard Co-authored-by: tanmen Co-authored-by: Alex Buchkovsky Co-authored-by: Natan Laverde Co-authored-by: Nicholas Muesch Co-authored-by: jburgess <11861789+jburgess@users.noreply.github.com> Co-authored-by: emileonhardt <40421857+emileonhardt@users.noreply.github.com> Co-authored-by: Jacob Floyd Co-authored-by: Igor Quirino Co-authored-by: Nico König Co-authored-by: https://gitlab.com/selankon Co-authored-by: Shweta Shukla <25539662+shwetashukla@users.noreply.github.com> Co-authored-by: Shweta Shukla Co-authored-by: Bartek Kowalik Co-authored-by: Shinya Sugmoto <34866626+gasugesu@users.noreply.github.com> Co-authored-by: Artem Shubovych Co-authored-by: Artem Shubovych Co-authored-by: Jochen Schalanda Co-authored-by: Chr1st0ph Co-authored-by: Christoph Preißner Co-authored-by: Erikmolin Co-authored-by: erikmolin Co-authored-by: Nicolas Homble Co-authored-by: Sebastian <63457660+sebohdev@users.noreply.github.com> Co-authored-by: Sebastian Ohm Co-authored-by: chandra-gh <63366477+chandra-gh@users.noreply.github.com> Co-authored-by: Chandra Yalangi Co-authored-by: Fabian Freund Co-authored-by: Erik Timmers Co-authored-by: minenok-tutu Co-authored-by: Ben Drucker Co-authored-by: QP Hou Co-authored-by: Nathan Mische Co-authored-by: QP Hou Co-authored-by: Vlastimil Šenfeld Co-authored-by: Thomas Hervé Co-authored-by: fuxs Co-authored-by: Aanisha Mishra Co-authored-by: David Hontecillas Co-authored-by: Kamil Piotrowski Co-authored-by: Adrien CABARBAYE Co-authored-by: api-clients-generation-pipeline[bot] <54105614+api-clients-generation-pipeline[bot]@users.noreply.github.com> Co-authored-by: ci.datadog-api-spec --- .apigentools-info | 8 +- .generator/templates/.travis.yml | 8 + .generator/templates/README.mustache | 221 +++++++ .generator/templates/api.mustache | 394 ++++++++++++ .generator/templates/api_doc.mustache | 134 +++++ .generator/templates/client.mustache | 598 +++++++++++++++++++ .generator/templates/configuration.mustache | 374 ++++++++++++ .generator/templates/git_push.sh.mustache | 58 ++ .generator/templates/gitignore.mustache | 24 + .generator/templates/go.mod.mustache | 10 + .generator/templates/go.sum | 13 + .generator/templates/model.mustache | 20 + .generator/templates/model_anyof.mustache | 76 +++ .generator/templates/model_doc.mustache | 97 +++ .generator/templates/model_enum.mustache | 100 ++++ .generator/templates/model_oneof.mustache | 109 ++++ .generator/templates/model_simple.mustache | 391 ++++++++++++ .generator/templates/nullable_model.mustache | 35 ++ .generator/templates/openapi.mustache | 1 + .generator/templates/partial_header.mustache | 9 + .generator/templates/response.mustache | 38 ++ .generator/templates/signing.mustache | 430 +++++++++++++ .generator/templates/utils.mustache | 319 ++++++++++ 23 files changed, 3463 insertions(+), 4 deletions(-) create mode 100644 .generator/templates/.travis.yml create mode 100644 .generator/templates/README.mustache create mode 100644 .generator/templates/api.mustache create mode 100644 .generator/templates/api_doc.mustache create mode 100644 .generator/templates/client.mustache create mode 100644 .generator/templates/configuration.mustache create mode 100755 .generator/templates/git_push.sh.mustache create mode 100644 .generator/templates/gitignore.mustache create mode 100644 .generator/templates/go.mod.mustache create mode 100644 .generator/templates/go.sum create mode 100644 .generator/templates/model.mustache create mode 100644 .generator/templates/model_anyof.mustache create mode 100644 .generator/templates/model_doc.mustache create mode 100644 .generator/templates/model_enum.mustache create mode 100644 .generator/templates/model_oneof.mustache create mode 100644 .generator/templates/model_simple.mustache create mode 100644 .generator/templates/nullable_model.mustache create mode 100644 .generator/templates/openapi.mustache create mode 100644 .generator/templates/partial_header.mustache create mode 100644 .generator/templates/response.mustache create mode 100644 .generator/templates/signing.mustache create mode 100644 .generator/templates/utils.mustache diff --git a/.apigentools-info b/.apigentools-info index 93e58ec8db2..48882359e77 100644 --- a/.apigentools-info +++ b/.apigentools-info @@ -4,13 +4,13 @@ "spec_versions": { "v1": { "apigentools_version": "1.4.1.dev6", - "regenerated": "2021-03-23 10:51:41.342590", - "spec_repo_commit": "34cf37f" + "regenerated": "2021-03-23 14:02:27.115937", + "spec_repo_commit": "7e667f1" }, "v2": { "apigentools_version": "1.4.1.dev6", - "regenerated": "2021-03-23 10:51:49.967652", - "spec_repo_commit": "34cf37f" + "regenerated": "2021-03-23 14:02:34.801926", + "spec_repo_commit": "7e667f1" } } } \ No newline at end of file diff --git a/.generator/templates/.travis.yml b/.generator/templates/.travis.yml new file mode 100644 index 00000000000..f5cb2ce9a5a --- /dev/null +++ b/.generator/templates/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/.generator/templates/README.mustache b/.generator/templates/README.mustache new file mode 100644 index 00000000000..4e9577633d4 --- /dev/null +++ b/.generator/templates/README.mustache @@ -0,0 +1,221 @@ +# Go API client for {{packageName}} + +{{#appDescriptionWithNewLines}} +{{{appDescriptionWithNewLines}}} +{{/appDescriptionWithNewLines}} + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Installation + +Install the following dependencies: + +```shell +go get github.com/stretchr/testify/assert +go get golang.org/x/oauth2 +go get golang.org/x/net/context +``` + +Put the package under your project folder and add the following in import: + +```golang +import sw "./{{packageName}}" +``` + +To use a proxy, set the environment variable `HTTP_PROXY`: + +```golang +os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") +``` + +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identifield by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. + +``` +ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^authMethods}} Endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}} + +### {{{name}}} + +{{#isApiKey}} +- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} + +Note, each API key must be added to a map of `map[string]APIKey` where the key is: {{keyParamName}} and passed in as the auth context for each request. + +{{/isApiKey}} +{{#isBasic}} +{{#isBasicBearer}} +- **Type**: HTTP Bearer token authentication + +Example + +```golang +auth := context.WithValue(context.Background(), sw.ContextAccessToken, "BEARERTOKENSTRING") +r, err := client.Service.Operation(auth, args) +``` + +{{/isBasicBearer}} +{{#isBasicBasic}} +- **Type**: HTTP basic authentication + +Example + +```golang +auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{ + UserName: "username", + Password: "password", +}) +r, err := client.Service.Operation(auth, args) +``` + +{{/isBasicBasic}} +{{#isHttpSignature}} +- **Type**: HTTP signature authentication + +Example + +```golang + authConfig := sw.HttpSignatureAuth{ + KeyId: "my-key-id", + PrivateKeyPath: "rsa.pem", + Passphrase: "my-passphrase", + SigningScheme: sw.HttpSigningSchemeHs2019, + SignedHeaders: []string{ + sw.HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. + sw.HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. + "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. + "Date", // The date and time at which the message was originated. + "Content-Type", // The Media type of the body of the request. + "Digest", // A cryptographic digest of the request body. + }, + SigningAlgorithm: sw.HttpSigningAlgorithmRsaPSS, + SignatureMaxValidity: 5 * time.Minute, + } + var authCtx context.Context + var err error + if authCtx, err = authConfig.ContextWithValue(context.Background()); err != nil { + // Process error + } + r, err = client.Service.Operation(auth, args) + +``` +{{/isHttpSignature}} +{{/isBasic}} +{{#isOAuth}} + +- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} + +Example + +```golang +auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING") +r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automatically refresh tokens and perform user authentication. + +```golang +import "golang.org/x/oauth2" + +/* Perform OAuth2 round trip request and obtain a token */ + +tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) +auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) +r, err := client.Service.Operation(auth, args) +``` + +{{/isOAuth}} +{{/authMethods}} + +## Documentation for Utility Methods + +Due to the fact that model structure members are all pointers, this package contains +a number of utility functions to easily obtain pointers to values of basic types. +Each of these functions takes a value of the given basic type and returns a pointer to it: + +* `PtrBool` +* `PtrInt` +* `PtrInt32` +* `PtrInt64` +* `PtrFloat` +* `PtrFloat32` +* `PtrFloat64` +* `PtrString` +* `PtrTime` + +## Author + +{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}} +{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/.generator/templates/api.mustache b/.generator/templates/api.mustache new file mode 100644 index 00000000000..215fef248a5 --- /dev/null +++ b/.generator/templates/api.mustache @@ -0,0 +1,394 @@ +{{>partial_header}} +package {{packageName}} + +{{#operations}} +import ( + "bytes" + _context "context" + _fmt "fmt" + _ioutil "io/ioutil" + _log "log" + _nethttp "net/http" + _neturl "net/url" +{{#imports}} "{{import}}" +{{/imports}} +) + +// Linger please +var ( + _ _context.Context +) +{{#generateInterfaces}} + +type {{classname}} interface { + {{#operation}} + + /* + * {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}} + {{#notes}} + * {{{unescapedNotes}}} + {{/notes}} + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}} + * @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}} + * @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request + */ + {{{nickname}}}(ctx _context.Context{{#pathParams}}, {{paramName}} {{{dataType}}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request + + /* + * {{nickname}}Execute executes the request{{#returnType}} + * @return {{{.}}}{{/returnType}} + */ + {{nickname}}Execute(r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error) + {{/operation}} +} +{{/generateInterfaces}} + +// {{classname}}Service {{classname}} service +type {{classname}}Service service +{{#operation}} + +type {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request struct { + ctx _context.Context{{#generateInterfaces}} + ApiService {{classname}} +{{/generateInterfaces}}{{^generateInterfaces}} + ApiService *{{classname}}Service +{{/generateInterfaces}} +{{#allParams}} + {{paramName}} {{^isPathParam}}*{{/isPathParam}}{{{dataType}}} +{{/allParams}} +} +{{#allParams}}{{^isPathParam}} +func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) {{vendorExtensions.x-export-param-name}}({{paramName}} {{{dataType}}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request { + r.{{paramName}} = &{{paramName}} + return r +}{{/isPathParam}}{{/allParams}} + +func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error) { + return r.ApiService.{{nickname}}Execute(r) +} + +/* + * {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}} +{{#notes}} + * {{{unescapedNotes}}} +{{/notes}} + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}} + * @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}} + * @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request + */ +func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#pathParams}}, {{paramName}} {{{dataType}}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request { + return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request{ + ApiService: a, + ctx: ctx, + {{#pathParams}} + {{paramName}}: {{paramName}}, + {{/pathParams}} + } +} + +/* + * Execute executes the request{{#returnType}} + * @return {{{.}}}{{/returnType}} + */ +func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.Method{{httpMethod}} + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + {{#returnType}} + localVarReturnValue {{{.}}} + {{/returnType}} + ) + + {{#vendorExtensions.x-unstable}} + operationId := "{{operationId}}" + if r.ApiService.client.cfg.IsUnstableOperationEnabled(operationId) { + _log.Printf("WARNING: Using unstable operation '%s'", operationId); + } else { + return {{#returnType}} localVarReturnValue, {{/returnType}}nil, GenericOpenAPIError{error: _fmt.Sprintf("Unstable operation '%s' is disabled", operationId)} + } + {{/vendorExtensions.x-unstable}} + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "{{{classname}}}Service.{{{nickname}}}") + if err != nil { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "{{{path}}}"{{#pathParams}} + localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.PathEscape(parameterToString(r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")), -1){{/pathParams}} + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + {{#allParams}} + {{#required}} + {{^isPathParam}} + if r.{{paramName}} == nil { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} is required and must be specified") + } + {{/isPathParam}} + {{#minItems}} + if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) < {{minItems}} { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minItems}} elements") + } + {{/minItems}} + {{#maxItems}} + if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) > {{maxItems}} { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxItems}} elements") + } + {{/maxItems}} + {{#minLength}} + if strlen({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) < {{minLength}} { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have at least {{minLength}} elements") + } + {{/minLength}} + {{#maxLength}} + if strlen({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) > {{maxLength}} { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must have less than {{maxLength}} elements") + } + {{/maxLength}} + {{#minimum}} + {{#isString}} + {{paramName}}Txt, err := atoi({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) + if {{paramName}}Txt < {{minimum}} { + {{/isString}} + {{^isString}} + if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} < {{minimum}} { + {{/isString}} + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must be greater than {{minimum}}") + } + {{/minimum}} + {{#maximum}} + {{#isString}} + {{paramName}}Txt, err := atoi({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) + if {{paramName}}Txt > {{maximum}} { + {{/isString}} + {{^isString}} + if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} > {{maximum}} { + {{/isString}} + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, reportError("{{paramName}} must be less than {{maximum}}") + } + {{/maximum}} + {{/required}} + {{/allParams}} + + {{#queryParams}} + {{#required}} + {{#isCollectionFormatMulti}} + { + t := *r.{{paramName}} + if reflect.TypeOf(t).Kind() == reflect.Slice { + s := reflect.ValueOf(t) + for i := 0; i < s.Len(); i++ { + localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) + } + } else { + localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) + } + } + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) + {{/isCollectionFormatMulti}} + {{/required}} + {{^required}} + if r.{{paramName}} != nil { + {{#isCollectionFormatMulti}} + t := *r.{{paramName}} + if reflect.TypeOf(t).Kind() == reflect.Slice { + s := reflect.ValueOf(t) + for i := 0; i < s.Len(); i++ { + localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) + } + } else { + localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) + } + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) + {{/isCollectionFormatMulti}} + } + {{/required}} + {{/queryParams}} + // to determine the Content-Type header +{{=<% %>=}} + localVarHTTPContentTypes := []string{<%#consumes%>"<%&mediaType%>"<%^-last%>, <%/-last%><%/consumes%>} +<%={{ }}=%> + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header +{{=<% %>=}} + localVarHTTPHeaderAccepts := []string{<%#produces%>"<%&mediaType%>"<%^-last%>, <%/-last%><%/produces%>} +<%={{ }}=%> + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + + // Set Operation-ID header for telemetry + localVarHeaderParams["DD-OPERATION-ID"] = "{{operationId}}" + +{{#headerParams}} + {{#required}} + localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}") + {{/required}} + {{^required}} + if r.{{paramName}} != nil { + localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}") + } + {{/required}} +{{/headerParams}} +{{#formParams}} +{{#isFile}} + localVarFormFileName = "{{baseName}}" +{{#required}} + localVarFile := *r.{{paramName}} +{{/required}} +{{^required}} + var localVarFile {{dataType}} + if r.{{paramName}} != nil { + localVarFile = *r.{{paramName}} + } +{{/required}} + if localVarFile != nil { + fbs, _ := _ioutil.ReadAll(localVarFile) + localVarFileBytes = fbs + localVarFileName = localVarFile.Name() + localVarFile.Close() + } +{{/isFile}} +{{^isFile}} +{{#required}} + localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) +{{/required}} +{{^required}} +{{#isModel}} + if r.{{paramName}} != nil { + paramJson, err := parameterToJson(*r.{{paramName}}) + if err != nil { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err + } + localVarFormParams.Add("{{baseName}}", paramJson) + } +{{/isModel}} +{{^isModel}} + if r.{{paramName}} != nil { + localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) + } +{{/isModel}} +{{/required}} +{{/isFile}} +{{/formParams}} +{{#bodyParams}} + // body params + localVarPostBody = r.{{paramName}} +{{/bodyParams}} +{{#authMethods}} +{{#isApiKey}} +{{^isKeyInCookie}} + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + {{#vendorExtensions.x-auth-id-alias}} + if apiKey, ok := auth["{{.}}"]; ok { + var key string + if prefix, ok := auth["{{name}}"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + {{/vendorExtensions.x-auth-id-alias}} + {{^vendorExtensions.x-auth-id-alias}} + if apiKey, ok := auth["{{name}}"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + {{/vendorExtensions.x-auth-id-alias}} + {{#isKeyInHeader}} + localVarHeaderParams["{{keyParamName}}"] = key + {{/isKeyInHeader}} + {{#isKeyInQuery}} + localVarQueryParams.Add("{{keyParamName}}", key) + {{/isKeyInQuery}} + } + } + } +{{/isKeyInCookie}} +{{/isApiKey}} +{{/authMethods}} + req, err := a.client.PrepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err + } + + localVarHTTPResponse, err := a.client.CallAPI(req) + if err != nil || localVarHTTPResponse == nil { + return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + {{#responses}} + {{#dataType}} + {{^is1xx}} + {{^is2xx}} + {{^wildcard}} + if localVarHTTPResponse.StatusCode == {{{code}}} { + {{/wildcard}} + var v {{{dataType}}} + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr + } + newErr.model = v + {{^-last}} + return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr + {{/-last}} + {{^wildcard}} + } + {{/wildcard}} + {{/is2xx}} + {{/is1xx}} + {{/dataType}} + {{/responses}} + return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr + } + + {{#returnType}} + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr + } + + {{/returnType}} + return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, nil +} +{{/operation}} +{{/operations}} diff --git a/.generator/templates/api_doc.mustache b/.generator/templates/api_doc.mustache new file mode 100644 index 00000000000..ef8e1ef953e --- /dev/null +++ b/.generator/templates/api_doc.mustache @@ -0,0 +1,134 @@ +# {{invokerPackage}}\{{classname}}{{#description}} + +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{{operationId}}} + +> {{#returnType}}{{{.}}} {{/returnType}}{{{operationId}}}(ctx{{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute() + +{{{summary}}}{{#notes}} + +{{{unespacedNotes}}}{{/notes}} + +### Example + +```go +package main + +import ( + "context" +{{#returnType}} + "encoding/json" +{{/returnType}} + "fmt" + "os" +{{#vendorExtensions.x-go-import}} +{{{vendorExtensions.x-go-import}}} +{{/vendorExtensions.x-go-import}} + {{goImportAlias}} "{{goImport}}" +) + +func main() { + {{#hasAuthMethods}} + ctx := context.WithValue( + context.Background(), + datadog.ContextAPIKeys, + map[string]datadog.APIKey{ + {{#authMethods}} + {{#isApiKey}} + {{^isKeyInCookie}} + "{{#vendorExtensions.x-auth-id-alias}}{{.}}{{/vendorExtensions.x-auth-id-alias}}{{^vendorExtensions.x-auth-id-alias}}{{name}}{{/vendorExtensions.x-auth-id-alias}}": { + Key: os.Getenv("{{#vendorExtensions.x-env-name}}{{.}}{{/vendorExtensions.x-env-name}}{{^vendorExtensions.x-env-name}}{{name}}{{/vendorExtensions.x-env-name}}"), + }, + {{/isKeyInCookie}} + {{/isApiKey}} + {{/authMethods}} + }, + ) + {{/hasAuthMethods}} + {{^hasAuthMethods}} + ctx := context.Background() + {{/hasAuthMethods}} + + if site, ok := os.LookupEnv("DD_SITE"); ok { + ctx = context.WithValue( + ctx, + datadog.ContextServerVariables, + map[string]string{"site": site}, + ) + } + + {{#allParams}} + {{paramName}} := {{{vendorExtensions.x-go-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/allParams}} + + configuration := {{goImportAlias}}.NewConfiguration() + {{#vendorExtensions.x-unstable}} + configuration.SetUnstableOperationEnabled("{{operationId}}", true) + {{/vendorExtensions.x-unstable}} + + api_client := {{goImportAlias}}.NewAPIClient(configuration) + {{#returnType}} + resp, r, err := api_client.{{classname}}.{{operationId}}(ctx{{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute() + {{/returnType}} + {{^returnType}} + r, err := api_client.{{classname}}.{{operationId}}(ctx{{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute() + {{/returnType}} + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `{{classname}}.{{operationId}}``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + {{#returnType}} + // response from `{{operationId}}`: {{{.}}} + response_content, _ := json.MarshalIndent(resp, "", " ") + fmt.Fprintf(os.Stdout, "Response from {{classname}}.{{operationId}}:\n%s\n", response_content) + {{/returnType}} +} +``` + +### Path Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#pathParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.{{/-last}}{{/pathParams}}{{#pathParams}} +**{{paramName}}** | {{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/pathParams}} + +### Other Parameters + +Other parameters are passed through a pointer to a api{{{nickname}}}Request struct via the builder pattern +{{#allParams}}{{#-last}} + +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}} +{{^isPathParam}} **{{paramName}}** | {{#isContainer}}{{#isArray}}{{#items}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**[]{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/items}}{{/isArray}}{{#isMap}}{{#items}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**map[string]{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/items}}{{/isMap}}{{/isContainer}}{{^isContainer}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/isContainer}} | {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/isPathParam}}{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/.generator/templates/client.mustache b/.generator/templates/client.mustache new file mode 100644 index 00000000000..eb8952c840a --- /dev/null +++ b/.generator/templates/client.mustache @@ -0,0 +1,598 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "log" + "mime/multipart" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" + {{#withAWSV4Signature}} + awsv4 "github.com/aws/aws-sdk-go/aws/signer/v4" + awscredentials "github.com/aws/aws-sdk-go/aws/credentials" + {{/withAWSV4Signature}} +) + +var ( + jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) + xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) +) + +// APIClient manages communication with the {{appName}} API v{{version}} +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services +{{#apiInfo}} +{{#apis}} +{{#operations}} + + {{#generateInterfaces}} + {{classname}} {{classname}} + {{/generateInterfaces}} + {{^generateInterfaces}} + {{classname}} *{{classname}}Service + {{/generateInterfaces}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + +{{#apiInfo}} + // API Services +{{#apis}} +{{#operations}} + c.{{classname}} = (*{{classname}}Service)(&c.common) +{{/operations}} +{{/apis}} +{{/apiInfo}} + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } else if t, ok := obj.(time.Time); ok { + return t.Format(time.RFC3339) + } + + return fmt.Sprintf("%v", obj) +} + +// helper for converting interface{} parameters to json strings +func parameterToJson(obj interface{}) (string, error) { + jsonBuf, err := json.Marshal(obj) + if err != nil { + return "", err + } + return string(jsonBuf), err +} + +// CallAPI do the request. +func (c *APIClient) CallAPI(request *http.Request) (*http.Response, error) { + if c.cfg.Debug { + dump, err := httputil.DumpRequestOut(request, true) + if err != nil { + return nil, err + } +{{#hasAuthMethods}} + // Strip any api keys from the response being logged + keys, ok := request.Context().Value(ContextAPIKeys).(map[string]APIKey) + if keys != nil && ok { + for _, apiKey := range keys { + valueRegex := regexp.MustCompile(fmt.Sprintf("(?m)%s",apiKey.Key)) + dump = valueRegex.ReplaceAll(dump, []byte("REDACTED")) + } + } +{{/hasAuthMethods}} + log.Printf("\n%s\n", string(dump)) + } + + resp, err := c.cfg.HTTPClient.Do(request) + if err != nil { + return resp, err + } + + if c.cfg.Debug { + dump, err := httputil.DumpResponse(resp, true) + if err != nil { + return resp, err + } + log.Printf("\n%s\n", string(dump)) + } + return resp, err +} + +// Allow modification of underlying config for alternate implementations and testing +// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior +func (c *APIClient) GetConfig() *Configuration { + return c.cfg +} + +// PrepareRequest build the request +func (c *APIClient) PrepareRequest( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + formFileName string, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form parameters and file if available. + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile(formFileName, filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + } + + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { + if body != nil { + return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") + } + body = &bytes.Buffer{} + body.WriteString(formParams.Encode()) + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Override request host, if applicable + if c.cfg.Host != "" { + url.Host = c.cfg.Host + } + + // Override request scheme, if applicable + if c.cfg.Scheme != "" { + url.Scheme = c.cfg.Scheme + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer "+auth) + } + + {{#withAWSV4Signature}} + // AWS Signature v4 Authentication + if auth, ok := ctx.Value(ContextAWSv4).(AWSv4); ok { + creds := awscredentials.NewStaticCredentials(auth.AccessKey, auth.SecretKey, auth.SessionToken) + signer := awsv4.NewSigner(creds) + var reader *strings.Reader + if body == nil { + reader = strings.NewReader("") + } else { + reader = strings.NewReader(body.String()) + } + + // Define default values for region and service to maintain backward compatibility + region := auth.Region + if region == "" { + region = "eu-west-2" + } + service := auth.Service + if service == "" { + service = "oapi" + } + + timestamp := time.Now() + _, err := signer.Sign(localVarRequest, reader, service, region, timestamp) + if err != nil { + return nil, err + } + } + {{/withAWSV4Signature}} + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } +{{#hasHttpSignatureMethods}} + if ctx != nil { + // HTTP Signature Authentication. All request headers must be set (including default headers) + // because the headers may be included in the signature. + if auth, ok := ctx.Value(ContextHttpSignatureAuth).(HttpSignatureAuth); ok { + err = SignRequest(ctx, localVarRequest, auth) + if err != nil { + return nil, err + } + } + } +{{/hasHttpSignatureMethods}} + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if len(b) == 0 { + return nil + } + if s, ok := v.(*string); ok { + *s = string(b) + return nil + } + if xmlCheck.MatchString(contentType) { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } + if jsonCheck.MatchString(contentType) { + if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas + if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined + if err = unmarshalObj.UnmarshalJSON(b); err != nil { + return err + } + } else { + return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") + } + } else if err = json.Unmarshal(b, v); err != nil { // simple model + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if fp, ok := body.(**os.File); ok { + _, err = bodyBuf.ReadFrom(*fp) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + err = xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } else { + expires = now.Add(lifetime) + } + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericOpenAPIError Provides access to the body, error and model on returned errors. +type GenericOpenAPIError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericOpenAPIError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericOpenAPIError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericOpenAPIError) Model() interface{} { + return e.model +} diff --git a/.generator/templates/configuration.mustache b/.generator/templates/configuration.mustache new file mode 100644 index 00000000000..87db1aa226d --- /dev/null +++ b/.generator/templates/configuration.mustache @@ -0,0 +1,374 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "context" + "fmt" + "log" + "net/http" + "runtime" + "strings" + + client "github.com/DataDog/datadog-api-client-go" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes an oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextBasicAuth takes BasicAuth as authentication for the request. + ContextBasicAuth = contextKey("basic") + + // ContextAccessToken takes a string oauth2 access token as authentication for the request. + ContextAccessToken = contextKey("accesstoken") + + // ContextAPIKeys takes a string apikey as authentication for the request + ContextAPIKeys = contextKey("apiKeys") + + {{#withAWSV4Signature}} + // ContextAWSv4 takes an Access Key and a Secret Key for signing AWS Signature v4 + ContextAWSv4 = contextKey("awsv4") + + {{/withAWSV4Signature}} + // ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request. + ContextHttpSignatureAuth = contextKey("httpsignature") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +{{#withAWSV4Signature}} +// AWSv4 provides AWS Signature to a request passed via context using ContextAWSv4 +// https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html +type AWSv4 struct { + AccessKey string + SecretKey string + SessionToken string + Region string + Service string +} + +{{/withAWSV4Signature}} +// ServerVariable stores the information about a server variable +type ServerVariable struct { + Description string + DefaultValue string + EnumValues []string +} + +// ServerConfiguration stores the information about a server +type ServerConfiguration struct { + URL string + Description string + Variables map[string]ServerVariable +} + +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + +// Configuration stores the configuration of the API client +type Configuration struct { + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client + unstableOperations map[string]bool +} + +// NewConfiguration returns a new Configuration object +func NewConfiguration() *Configuration { + cfg := &Configuration{ + DefaultHeader: make(map[string]string), + UserAgent: getUserAgent(), + Debug: false, + {{#servers}} + {{#-first}} + Servers: ServerConfigurations{ + {{/-first}} + { + URL: "{{{url}}}", + Description: "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + Variables: map[string]ServerVariable{ + {{/-first}} + "{{{name}}}": ServerVariable{ + Description: "{{{description}}}{{^description}}No description provided{{/description}}", + DefaultValue: "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + EnumValues: []string{ + {{/-first}} + "{{{.}}}", + {{#-last}} + }, + {{/-last}} + {{/enumValues}} + }, + {{#-last}} + }, + {{/-last}} + {{/variables}} + }, + {{#-last}} + }, + {{/-last}} + {{/servers}} + {{#apiInfo}} + OperationServers: map[string]ServerConfigurations{ + {{#apis}} + {{#operations}} + {{#operation}} + {{#servers}} + {{#-first}} + "{{{classname}}}Service.{{{nickname}}}": { + {{/-first}} + { + URL: "{{{url}}}", + Description: "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + Variables: map[string]ServerVariable{ + {{/-first}} + "{{{name}}}": ServerVariable{ + Description: "{{{description}}}{{^description}}No description provided{{/description}}", + DefaultValue: "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + EnumValues: []string{ + {{/-first}} + "{{{.}}}", + {{#-last}} + }, + {{/-last}} + {{/enumValues}} + }, + {{#-last}} + }, + {{/-last}} + {{/variables}} + }, + {{#-last}} + }, + {{/-last}} + {{/servers}} + {{/operation}} + {{/operations}} + {{/apis}} + }, + {{/apiInfo}} + unstableOperations: map[string]bool{ + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#vendorExtensions.x-unstable}} + "{{operationId}}": false, + {{/vendorExtensions.x-unstable}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + }, + } + return cfg +} + +// AddDefaultHeader adds a new HTTP header to the default header in the request +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} + +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1) + } + server := sc[index] + url := server.URL + + // go through variables and replace placeholders + for name, variable := range server.Variables { + if value, ok := variables[name]; ok { + found := bool(len(variable.EnumValues) == 0) + for _, enumValue := range variable.EnumValues { + if value == enumValue { + found = true + } + } + if !found { + return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) + } + url = strings.Replace(url, "{"+name+"}", value, -1) + } else { + url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) + } + } + return url, nil +} + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} + +// GetUnstableOperations returns a slice with all unstable operation Ids +func (c *Configuration) GetUnstableOperations() []string { + ids := make([]string, len(c.unstableOperations)) + for id := range c.unstableOperations { + ids = append(ids, id) + } + return ids +} + +// SetUnstableOperationEnabled sets an unstable operation as enabled (true) or disabled (false) +// This function accepts operation ID as an argument - this is the name of the method on the API class, e.g. "CreateFoo" +// Returns true if the operation is marked as unstable and thus was enabled/disabled, false otherwise +func (c *Configuration) SetUnstableOperationEnabled(operation string, enabled bool) bool { + if _, ok := c.unstableOperations[operation]; ok { + c.unstableOperations[operation] = enabled + return true + } + log.Printf("WARNING: '%s' is not an unstable operation, can't enable/disable", operation) + return false +} + +// IsUnstableOperation determines whether an operation is an unstable operation. +// This function accepts operation ID as an argument - this is the name of the method on the API class, e.g. "CreateFoo" +func (c *Configuration) IsUnstableOperation(operation string) bool { + _, present := c.unstableOperations[operation] + return present +} + +// IsUnstableOperationEnabled determines whether an unstable operation is enabled. +// This function accepts operation ID as an argument - this is the name of the method on the API class, e.g. "CreateFoo" +// Returns true if the operation is unstable and it is enabled, false otherwise +func (c *Configuration) IsUnstableOperationEnabled(operation string) bool { + if enabled, present := c.unstableOperations[operation]; present { + return enabled + } else { + log.Printf("WARNING: '%s' is not an unstable operation, is always enabled", operation) + } + return false +} + +func getUserAgent() string { + return fmt.Sprintf( + "datadog-api-client-go/%s (go %s; os %s; arch %s)", + client.Version, + runtime.Version(), + runtime.GOOS, + runtime.GOARCH, + ) +} diff --git a/.generator/templates/git_push.sh.mustache b/.generator/templates/git_push.sh.mustache new file mode 100755 index 00000000000..8b3f689c912 --- /dev/null +++ b/.generator/templates/git_push.sh.mustache @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="{{{gitHost}}}" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/.generator/templates/gitignore.mustache b/.generator/templates/gitignore.mustache new file mode 100644 index 00000000000..daf913b1b34 --- /dev/null +++ b/.generator/templates/gitignore.mustache @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/.generator/templates/go.mod.mustache b/.generator/templates/go.mod.mustache new file mode 100644 index 00000000000..97fceb03a92 --- /dev/null +++ b/.generator/templates/go.mod.mustache @@ -0,0 +1,10 @@ +module {{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}} + +go 1.13 + +require ( + golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99 + {{#withAWSV4Signature}} + github.com/aws/aws-sdk-go v1.34.14 + {{/withAWSV4Signature}} +) diff --git a/.generator/templates/go.sum b/.generator/templates/go.sum new file mode 100644 index 00000000000..734252e6815 --- /dev/null +++ b/.generator/templates/go.sum @@ -0,0 +1,13 @@ +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= diff --git a/.generator/templates/model.mustache b/.generator/templates/model.mustache new file mode 100644 index 00000000000..684af1d33c6 --- /dev/null +++ b/.generator/templates/model.mustache @@ -0,0 +1,20 @@ +{{>partial_header}} +package {{packageName}} + +{{#models}} +import ( + "encoding/json" +{{#imports}} + "{{import}}" +{{/imports}} +) + +{{#model}} +{{#isEnum}} +{{>model_enum}} +{{/isEnum}} +{{^isEnum}} +{{#oneOf}}{{#-first}}{{>model_oneof}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>model_anyof}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>model_simple}}{{/anyOf}}{{/oneOf}} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/.generator/templates/model_anyof.mustache b/.generator/templates/model_anyof.mustache new file mode 100644 index 00000000000..5dfa75302f1 --- /dev/null +++ b/.generator/templates/model_anyof.mustache @@ -0,0 +1,76 @@ +// {{classname}}{{#description}} {{{description}}}{{/description}}{{^description}} struct for {{{classname}}}{{/description}} +type {{classname}} struct { + {{#anyOf}} + {{{.}}} *{{{.}}} + {{/anyOf}} +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *{{classname}}) UnmarshalJSON(data []byte) error { + var err error + {{#isNullable}} + // this object is nullable so check if the payload is null or empty string + if string(data) == "" || string(data) == "{}" { + return nil + } + + {{/isNullable}} + {{#discriminator}} + {{#mappedModels}} + {{#-first}} + // use discriminator value to speed up the lookup + var jsonDict map[string]interface{} + err := json.Unmarshal(data, &jsonDict) + if err != nil { + return fmt.Errorf("Failed to unmarshal JSON into map for the discrimintor lookup.") + } + + {{/-first}} + // check if the discriminator value is '{{{mappingName}}}' + if jsonDict["{{{propertyBaseName}}}"] == "{{{mappingName}}}" { + // try to unmarshal JSON data into {{{modelName}}} + err = json.Unmarshal(data, &dst.{{{modelName}}}); + if err == nil { + json{{{modelName}}}, _ := json.Marshal(dst.{{{modelName}}}) + if string(json{{{modelName}}}) == "{}" { // empty struct + dst.{{{modelName}}} = nil + } else { + return nil // data stored in dst.{{{modelName}}}, return on the first match + } + } else { + dst.{{{modelName}}} = nil + } + } + + {{/mappedModels}} + {{/discriminator}} + {{#anyOf}} + // try to unmarshal JSON data into {{{.}}} + err = json.Unmarshal(data, &dst.{{{.}}}); + if err == nil { + json{{{.}}}, _ := json.Marshal(dst.{{{.}}}) + if string(json{{{.}}}) == "{}" { // empty struct + dst.{{{.}}} = nil + } else { + return nil // data stored in dst.{{{.}}}, return on the first match + } + } else { + dst.{{{.}}} = nil + } + + {{/anyOf}} + return fmt.Errorf("Data failed to match schemas in anyOf({{classname}})") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *{{classname}}) MarshalJSON() ([]byte, error) { +{{#anyOf}} + if src.{{{.}}} != nil { + return json.Marshal(&src.{{{.}}}) + } + +{{/anyOf}} + return nil, nil // no data in anyOf schemas +} + +{{>nullable_model}} diff --git a/.generator/templates/model_doc.mustache b/.generator/templates/model_doc.mustache new file mode 100644 index 00000000000..439e695b1f5 --- /dev/null +++ b/.generator/templates/model_doc.mustache @@ -0,0 +1,97 @@ +{{#models}}{{#model}}# {{classname}} + +{{^isEnum}} +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vendorExtensions.x-is-one-of-interface}} +**{{classname}}Interface** | **interface { {{#discriminator}}{{propertyGetter}}() {{propertyType}}{{/discriminator}} }** | An interface that can hold any of the proper implementing types | +{{/vendorExtensions.x-is-one-of-interface}} +{{^vendorExtensions.x-is-one-of-interface}} +{{#vars}}**{{name}}** | {{^required}}Pointer to {{/required}}{{#isContainer}}{{#isArray}}{{#items}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**[]{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{dataType}}.md){{/isFile}}{{/isPrimitiveType}}{{/items}}{{/isArray}}{{#isMap}}{{#items}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**map[string]{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/items}}{{/isMap}}{{/isContainer}}{{^isContainer}}{{^isPrimitiveType}}{{^isFile}}{{^isDateTime}}[{{/isDateTime}}{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}{{^isDateTime}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isDateTime}}{{/isFile}}{{/isPrimitiveType}}{{/isContainer}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} +{{/vendorExtensions.x-is-one-of-interface}} + +## Methods + +{{^vendorExtensions.x-is-one-of-interface}} +### New{{classname}} + +`func New{{classname}}({{#vars}}{{#required}}{{nameInCamelCase}} {{dataType}}, {{/required}}{{/vars}}) *{{classname}}` + +New{{classname}} instantiates a new {{classname}} object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### New{{classname}}WithDefaults + +`func New{{classname}}WithDefaults() *{{classname}}` + +New{{classname}}WithDefaults instantiates a new {{classname}} object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +{{#vars}} +### Get{{name}} + +`func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}}` + +Get{{name}} returns the {{name}} field if non-nil, zero value otherwise. + +### Get{{name}}Ok + +`func (o *{{classname}}) Get{{name}}Ok() (*{{vendorExtensions.x-go-base-type}}, bool)` + +Get{{name}}Ok returns a tuple with the {{name}} field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### Set{{name}} + +`func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}})` + +Set{{name}} sets {{name}} field to given value. + +{{^required}} +### Has{{name}} + +`func (o *{{classname}}) Has{{name}}() bool` + +Has{{name}} returns a boolean if a field has been set. +{{/required}} + +{{#isNullable}} +### Set{{name}}Nil + +`func (o *{{classname}}) Set{{name}}Nil(b bool)` + + Set{{name}}Nil sets the value for {{name}} to be an explicit nil + +### Unset{{name}} +`func (o *{{classname}}) Unset{{name}}()` + +Unset{{name}} ensures that no value is present for {{name}}, not even an explicit nil +{{/isNullable}} +{{/vars}} +{{#vendorExtensions.x-implements}} + +### As{{{.}}} + +`func (s *{{classname}}) As{{{.}}}() {{{.}}}` + +Convenience method to wrap this instance of {{classname}} in {{{.}}} +{{/vendorExtensions.x-implements}} +{{/vendorExtensions.x-is-one-of-interface}} +{{/isEnum}} +{{#isEnum}} +## Enum + +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} +{{/isEnum}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/.generator/templates/model_enum.mustache b/.generator/templates/model_enum.mustache new file mode 100644 index 00000000000..11dfbfc7d33 --- /dev/null +++ b/.generator/templates/model_enum.mustache @@ -0,0 +1,100 @@ +// {{{classname}}} {{#description}}{{{.}}}{{/description}}{{^description}}the model '{{{classname}}}'{{/description}} +type {{{classname}}} {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}} + +// List of {{{name}}} +const ( + {{#allowableValues}} + {{#enumVars}} + {{^-first}} + {{/-first}} + {{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = {{{value}}} + {{/enumVars}} + {{/allowableValues}} +) + +var allowed{{{classname}}}EnumValues = []{{{classname}}}{ + {{#allowableValues}} + {{#enumVars}} + {{{value}}}, + {{/enumVars}} + {{/allowableValues}} +} + +func (v *{{{classname}}}) UnmarshalJSON(src []byte) error { + var value {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}} + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := {{{classname}}}(value) + for _, existing := range allowed{{{classname}}}EnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid {{classname}}", value) +} + +// New{{{classname}}}FromValue returns a pointer to a valid {{{classname}}} +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func New{{{classname}}}FromValue(v {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}}) (*{{{classname}}}, error) { + ev := {{{classname}}}(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for {{{classname}}}: valid values are %v", v, allowed{{{classname}}}EnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v {{{classname}}}) IsValid() bool { + for _, existing := range allowed{{{classname}}}EnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to {{{name}}} value +func (v {{{classname}}}) Ptr() *{{{classname}}} { + return &v +} + +type Nullable{{{classname}}} struct { + value *{{{classname}}} + isSet bool +} + +func (v Nullable{{classname}}) Get() *{{classname}} { + return v.value +} + +func (v *Nullable{{classname}}) Set(val *{{classname}}) { + v.value = val + v.isSet = true +} + +func (v Nullable{{classname}}) IsSet() bool { + return v.isSet +} + +func (v *Nullable{{classname}}) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullable{{classname}}(val *{{classname}}) *Nullable{{classname}} { + return &Nullable{{classname}}{value: val, isSet: true} +} + +func (v Nullable{{{classname}}}) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *Nullable{{{classname}}}) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/.generator/templates/model_oneof.mustache b/.generator/templates/model_oneof.mustache new file mode 100644 index 00000000000..a0322e34074 --- /dev/null +++ b/.generator/templates/model_oneof.mustache @@ -0,0 +1,109 @@ +// {{classname}} - {{#description}}{{{description}}}{{/description}}{{^description}}struct for {{{classname}}}{{/description}} +type {{classname}} struct { + {{#oneOf}} + {{{.}}} *{{{.}}} + {{/oneOf}} +} + +{{#oneOf}} +// {{{.}}}As{{classname}} is a convenience function that returns {{{.}}} wrapped in {{classname}} +func {{{.}}}As{{classname}}(v *{{{.}}}) {{classname}} { + return {{classname}}{ {{{.}}}: v} +} + +{{/oneOf}} + +// Unmarshal JSON data into one of the pointers in the struct +func (dst *{{classname}}) UnmarshalJSON(data []byte) error { + var err error + {{#isNullable}} + // this object is nullable so check if the payload is null or empty string + if string(data) == "" || string(data) == "{}" { + return nil + } + + {{/isNullable}} + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + {{#mappedModels}} + {{#-first}} + // use discriminator value to speed up the lookup + var jsonDict map[string]interface{} + err = json.Unmarshal(data, &jsonDict) + if err != nil { + return fmt.Errorf("Failed to unmarshal JSON into map for the discrimintor lookup.") + } + + {{/-first}} + // check if the discriminator value is '{{{mappingName}}}' + if jsonDict["{{{propertyBaseName}}}"] == "{{{mappingName}}}" { + // try to unmarshal JSON data into {{{modelName}}} + err = json.Unmarshal(data, &dst.{{{modelName}}}) + if err == nil { + return nil // data stored in dst.{{{modelName}}}, return on the first match + } else { + dst.{{{modelName}}} = nil + return fmt.Errorf("Failed to unmarshal {{classname}} as {{{modelName}}}: %s", err.Error()) + } + } + + {{/mappedModels}} + {{/discriminator}} + return nil + {{/useOneOfDiscriminatorLookup}} + {{^useOneOfDiscriminatorLookup}} + match := 0 + {{#oneOf}} + // try to unmarshal data into {{{.}}} + err = json.Unmarshal(data, &dst.{{{.}}}) + if err == nil { + json{{{.}}}, _ := json.Marshal(dst.{{{.}}}) + if string(json{{{.}}}) == "{}" { // empty struct + dst.{{{.}}} = nil + } else { + match++ + } + } else { + dst.{{{.}}} = nil + } + + {{/oneOf}} + if match > 1 { // more than 1 match + // reset to nil + {{#oneOf}} + dst.{{{.}}} = nil + {{/oneOf}} + + return fmt.Errorf("Data matches more than one schema in oneOf({{classname}})") + } else if match == 1 { + return nil // exactly one match + } else { // no match + return fmt.Errorf("Data failed to match schemas in oneOf({{classname}})") + } + {{/useOneOfDiscriminatorLookup}} +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src {{classname}}) MarshalJSON() ([]byte, error) { +{{#oneOf}} + if src.{{{.}}} != nil { + return json.Marshal(&src.{{{.}}}) + } + +{{/oneOf}} + return nil, nil // no data in oneOf schemas +} + +// Get the actual instance +func (obj *{{classname}}) GetActualInstance() (interface{}) { +{{#oneOf}} + if obj.{{{.}}} != nil { + return obj.{{{.}}} + } + +{{/oneOf}} + // all schemas are nil + return nil +} + +{{>nullable_model}} diff --git a/.generator/templates/model_simple.mustache b/.generator/templates/model_simple.mustache new file mode 100644 index 00000000000..da651274308 --- /dev/null +++ b/.generator/templates/model_simple.mustache @@ -0,0 +1,391 @@ +// {{classname}}{{#description}} {{{description}}}{{/description}}{{^description}} struct for {{{classname}}}{{/description}} +type {{classname}} struct { +{{#parent}} +{{^isMap}} +{{^isArray}} + {{{parent}}} +{{/isArray}} +{{/isMap}} +{{#isArray}} + Items {{{parent}}} +{{/isArray}} +{{/parent}} +{{#vars}} +{{^-first}} +{{/-first}} +{{#description}} + // {{{description}}} +{{/description}} + {{name}} {{^required}}{{^isNullable}}*{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` +{{/vars}} +{{#isAdditionalPropertiesTrue}} + AdditionalProperties map[string]interface{} +{{/isAdditionalPropertiesTrue}} +} + +{{#isAdditionalPropertiesTrue}} +type _{{{classname}}} {{{classname}}} + +{{/isAdditionalPropertiesTrue}} +// New{{classname}} instantiates a new {{classname}} object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func New{{classname}}({{#requiredVars}}{{nameInCamelCase}} {{dataType}}{{^-last}}, {{/-last}}{{/requiredVars}}) *{{classname}} { + this := {{classname}}{} +{{#allVars}} +{{#required}} + this.{{name}} = {{nameInCamelCase}} +{{/required}} +{{^required}} +{{#defaultValue}} +{{^vendorExtensions.x-golang-is-container}} +{{#isNullable}} + var {{nameInCamelCase}} {{{datatypeWithEnum}}} = {{{.}}} + this.{{name}} = *New{{{dataType}}}(&{{nameInCamelCase}}) +{{/isNullable}} +{{^isNullable}} + var {{nameInCamelCase}} {{{dataType}}} = {{{.}}} + this.{{name}} = &{{nameInCamelCase}} +{{/isNullable}} +{{/vendorExtensions.x-golang-is-container}} +{{/defaultValue}} +{{/required}} +{{/allVars}} + return &this +} + +// New{{classname}}WithDefaults instantiates a new {{classname}} object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func New{{classname}}WithDefaults() *{{classname}} { + this := {{classname}}{} +{{#vars}} +{{#defaultValue}} +{{^vendorExtensions.x-golang-is-container}} +{{#isNullable}} +{{!we use datatypeWithEnum here, since it will represent the non-nullable name of the datatype, e.g. int64 for NullableInt64}} + var {{nameInCamelCase}} {{{datatypeWithEnum}}} = {{{.}}} + this.{{name}} = *New{{{dataType}}}(&{{nameInCamelCase}}) +{{/isNullable}} +{{^isNullable}} + var {{nameInCamelCase}} {{{dataType}}} = {{{.}}} + this.{{name}} = {{^required}}&{{/required}}{{nameInCamelCase}} +{{/isNullable}} +{{/vendorExtensions.x-golang-is-container}} +{{/defaultValue}} +{{/vars}} + return &this +} + +{{#vars}} +{{#required}} +// Get{{name}} returns the {{name}} field value +{{#isNullable}} +// If the value is explicit nil, the zero value for {{vendorExtensions.x-go-base-type}} will be returned +{{/isNullable}} +func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}} { + if o == nil{{#isNullable}}{{^vendorExtensions.x-golang-is-container}} || o.{{name}}.Get() == nil{{/vendorExtensions.x-golang-is-container}}{{/isNullable}} { + var ret {{vendorExtensions.x-go-base-type}} + return ret + } + +{{#isNullable}} +{{#vendorExtensions.x-golang-is-container}} + return o.{{name}} +{{/vendorExtensions.x-golang-is-container}} +{{^vendorExtensions.x-golang-is-container}} + return *o.{{name}}.Get() +{{/vendorExtensions.x-golang-is-container}} +{{/isNullable}} +{{^isNullable}} + return o.{{name}} +{{/isNullable}} +} + +// Get{{name}}Ok returns a tuple with the {{name}} field value +// and a boolean to check if the value has been set. +{{#isNullable}} +// NOTE: If the value is an explicit nil, `nil, true` will be returned +{{/isNullable}} +func (o *{{classname}}) Get{{name}}Ok() (*{{vendorExtensions.x-go-base-type}}, bool) { + if o == nil {{#isNullable}}{{#vendorExtensions.x-golang-is-container}}|| o.{{name}} == nil{{/vendorExtensions.x-golang-is-container}}{{/isNullable}} { + return nil, false + } +{{#isNullable}} +{{#vendorExtensions.x-golang-is-container}} + return &o.{{name}}, true +{{/vendorExtensions.x-golang-is-container}} +{{^vendorExtensions.x-golang-is-container}} + return o.{{name}}.Get(), o.{{name}}.IsSet() +{{/vendorExtensions.x-golang-is-container}} +{{/isNullable}} +{{^isNullable}} + return &o.{{name}}, true +{{/isNullable}} +} + +// Set{{name}} sets field value +func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) { +{{#isNullable}} +{{#vendorExtensions.x-golang-is-container}} + o.{{name}} = v +{{/vendorExtensions.x-golang-is-container}} +{{^vendorExtensions.x-golang-is-container}} + o.{{name}}.Set(&v) +{{/vendorExtensions.x-golang-is-container}} +{{/isNullable}} +{{^isNullable}} + o.{{name}} = v +{{/isNullable}} +} + +{{/required}} +{{^required}} +// Get{{name}} returns the {{name}} field value if set, zero value otherwise{{#isNullable}} (both if not set or set to explicit null){{/isNullable}}. +func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}} { + if o == nil {{^isNullable}}|| o.{{name}} == nil{{/isNullable}}{{#isNullable}}{{^vendorExtensions.x-golang-is-container}}|| o.{{name}}.Get() == nil{{/vendorExtensions.x-golang-is-container}}{{/isNullable}} { + var ret {{vendorExtensions.x-go-base-type}} + return ret + } +{{#isNullable}} +{{#vendorExtensions.x-golang-is-container}} + return o.{{name}} +{{/vendorExtensions.x-golang-is-container}} +{{^vendorExtensions.x-golang-is-container}} + return *o.{{name}}.Get() +{{/vendorExtensions.x-golang-is-container}} +{{/isNullable}} +{{^isNullable}} + return *o.{{name}} +{{/isNullable}} +} + +// Get{{name}}Ok returns a tuple with the {{name}} field value if set, nil otherwise +// and a boolean to check if the value has been set. +{{#isNullable}} +// NOTE: If the value is an explicit nil, `nil, true` will be returned +{{/isNullable}} +func (o *{{classname}}) Get{{name}}Ok() (*{{vendorExtensions.x-go-base-type}}, bool) { + if o == nil {{^isNullable}}|| o.{{name}} == nil{{/isNullable}}{{#isNullable}}{{#vendorExtensions.x-golang-is-container}}|| o.{{name}} == nil{{/vendorExtensions.x-golang-is-container}}{{/isNullable}} { + return nil, false + } +{{#isNullable}} +{{#vendorExtensions.x-golang-is-container}} + return &o.{{name}}, true +{{/vendorExtensions.x-golang-is-container}} +{{^vendorExtensions.x-golang-is-container}} + return o.{{name}}.Get(), o.{{name}}.IsSet() +{{/vendorExtensions.x-golang-is-container}} +{{/isNullable}} +{{^isNullable}} + return o.{{name}}, true +{{/isNullable}} +} + +// Has{{name}} returns a boolean if a field has been set. +func (o *{{classname}}) Has{{name}}() bool { + if o != nil && {{^isNullable}}o.{{name}} != nil{{/isNullable}}{{#isNullable}}{{#vendorExtensions.x-golang-is-container}}o.{{name}} != nil{{/vendorExtensions.x-golang-is-container}}{{^vendorExtensions.x-golang-is-container}}o.{{name}}.IsSet(){{/vendorExtensions.x-golang-is-container}}{{/isNullable}} { + return true + } + + return false +} + +// Set{{name}} gets a reference to the given {{dataType}} and assigns it to the {{name}} field. +func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) { +{{#isNullable}} +{{#vendorExtensions.x-golang-is-container}} + o.{{name}} = v +{{/vendorExtensions.x-golang-is-container}} +{{^vendorExtensions.x-golang-is-container}} + o.{{name}}.Set(&v) +{{/vendorExtensions.x-golang-is-container}} +{{/isNullable}} +{{^isNullable}} + o.{{name}} = &v +{{/isNullable}} +} +{{#isNullable}} +{{^vendorExtensions.x-golang-is-container}} +// Set{{name}}Nil sets the value for {{name}} to be an explicit nil +func (o *{{classname}}) Set{{name}}Nil() { + o.{{name}}.Set(nil) +} + +// Unset{{name}} ensures that no value is present for {{name}}, not even an explicit nil +func (o *{{classname}}) Unset{{name}}() { + o.{{name}}.Unset() +} +{{/vendorExtensions.x-golang-is-container}} +{{/isNullable}} + +{{/required}} +{{/vars}} +func (o {{classname}}) MarshalJSON() ([]byte, error) { + toSerialize := {{#isArray}}make([]interface{}, len(o.Items)){{/isArray}}{{^isArray}}map[string]interface{}{}{{/isArray}} + {{#parent}} + {{^isMap}} + {{^isArray}} + serialized{{parent}}, err{{parent}} := json.Marshal(o.{{parent}}) + if err{{parent}} != nil { + return []byte{}, err{{parent}} + } + err{{parent}} = json.Unmarshal([]byte(serialized{{parent}}), &toSerialize) + if err{{parent}} != nil { + return []byte{}, err{{parent}} + } + {{/isArray}} + {{/isMap}} + {{#isArray}} + for i, item := range o.Items { + toSerialize[i] = item + } + {{/isArray}} + {{/parent}} + {{#vars}} + {{! if argument is nullable, only serialize it if it is set}} + {{#isNullable}} + {{#vendorExtensions.x-golang-is-container}} + {{! support for container fields is not ideal at this point because of lack of Nullable* types}} + if o.{{name}} != nil { + toSerialize["{{baseName}}"] = o.{{name}} + } + {{/vendorExtensions.x-golang-is-container}} + {{^vendorExtensions.x-golang-is-container}} + if {{#required}}true{{/required}}{{^required}}o.{{name}}.IsSet(){{/required}} { + toSerialize["{{baseName}}"] = o.{{name}}.Get() + } + {{/vendorExtensions.x-golang-is-container}} + {{/isNullable}} + {{! if argument is not nullable, don't set it if it is nil}} + {{^isNullable}} + if {{#required}}true{{/required}}{{^required}}o.{{name}} != nil{{/required}} { + toSerialize["{{baseName}}"] = o.{{name}} + } + {{/isNullable}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + {{/isAdditionalPropertiesTrue}} + return json.Marshal(toSerialize) +} + +{{#isAdditionalPropertiesTrue}} +func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { +{{#parent}} +{{^isMap}} + type {{classname}}WithoutEmbeddedStruct struct { + {{#vars}} + {{^-first}} + {{/-first}} + {{#description}} + // {{{description}}} + {{/description}} + {{name}} {{^required}}{{^isNullable}}*{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` + {{/vars}} + } + + var{{{classname}}}WithoutEmbeddedStruct := {{{classname}}}WithoutEmbeddedStruct{} + + err = json.Unmarshal(bytes, &var{{{classname}}}WithoutEmbeddedStruct) + if err == nil { + var{{{classname}}} := _{{{classname}}}{} + {{#vars}} + var{{{classname}}}.{{{name}}} = var{{{classname}}}WithoutEmbeddedStruct.{{{name}}} + {{/vars}} + *o = {{{classname}}}(var{{{classname}}}) + } else { + return err + } + + var{{{classname}}} := _{{{classname}}}{} + + err = json.Unmarshal(bytes, &var{{{classname}}}) + if err == nil { + o.{{{parent}}} = var{{{classname}}}.{{{parent}}} + } else { + return err + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + {{#vars}} + delete(additionalProperties, "{{{baseName}}}") + {{/vars}} + + // remove fields from embedded structs + reflect{{{parent}}} := reflect.ValueOf(o.{{{parent}}}) + for i := 0; i < reflect{{{parent}}}.Type().NumField(); i++ { + t := reflect{{{parent}}}.Type().Field(i) + + if jsonTag := t.Tag.Get("json"); jsonTag != "" { + fieldName := "" + if commaIdx := strings.Index(jsonTag, ","); commaIdx > 0 { + fieldName = jsonTag[:commaIdx] + } else { + fieldName = jsonTag + } + if fieldName != "AdditionalProperties" { + delete(additionalProperties, fieldName) + } + } + } + + o.AdditionalProperties = additionalProperties + } + + return err +{{/isMap}} +{{#isMap}} + var{{{classname}}} := _{{{classname}}}{} + + if err = json.Unmarshal(bytes, &var{{{classname}}}); err == nil { + *o = {{{classname}}}(var{{{classname}}}) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + {{#vars}} + delete(additionalProperties, "{{{baseName}}}") + {{/vars}} + o.AdditionalProperties = additionalProperties + } + + return err +{{/isMap}} +{{/parent}} +{{^parent}} + var{{{classname}}} := _{{{classname}}}{} + + if err = json.Unmarshal(bytes, &var{{{classname}}}); err == nil { + *o = {{{classname}}}(var{{{classname}}}) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + {{#vars}} + delete(additionalProperties, "{{{baseName}}}") + {{/vars}} + o.AdditionalProperties = additionalProperties + } + + return err +{{/parent}} +} + +{{/isAdditionalPropertiesTrue}} +{{#isArray}} +func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { + return json.Unmarshal(bytes, &o.Items) +} + +{{/isArray}} +{{>nullable_model}} diff --git a/.generator/templates/nullable_model.mustache b/.generator/templates/nullable_model.mustache new file mode 100644 index 00000000000..20d35769130 --- /dev/null +++ b/.generator/templates/nullable_model.mustache @@ -0,0 +1,35 @@ +type Nullable{{{classname}}} struct { + value *{{{classname}}} + isSet bool +} + +func (v Nullable{{classname}}) Get() *{{classname}} { + return v.value +} + +func (v *Nullable{{classname}}) Set(val *{{classname}}) { + v.value = val + v.isSet = true +} + +func (v Nullable{{classname}}) IsSet() bool { + return v.isSet +} + +func (v *Nullable{{classname}}) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullable{{classname}}(val *{{classname}}) *Nullable{{classname}} { + return &Nullable{{classname}}{value: val, isSet: true} +} + +func (v Nullable{{{classname}}}) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *Nullable{{{classname}}}) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/.generator/templates/openapi.mustache b/.generator/templates/openapi.mustache new file mode 100644 index 00000000000..51ebafb0187 --- /dev/null +++ b/.generator/templates/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/.generator/templates/partial_header.mustache b/.generator/templates/partial_header.mustache new file mode 100644 index 00000000000..94c9ae11b74 --- /dev/null +++ b/.generator/templates/partial_header.mustache @@ -0,0 +1,9 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2019-Present Datadog, Inc. + */ +{{#withGoCodegenComment}} + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. +{{/withGoCodegenComment}} diff --git a/.generator/templates/response.mustache b/.generator/templates/response.mustache new file mode 100644 index 00000000000..1a8765bae8f --- /dev/null +++ b/.generator/templates/response.mustache @@ -0,0 +1,38 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "net/http" +) + +// APIResponse stores the API response returned by the server. +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the OpenAPI operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +// NewAPIResponse returns a new APIResonse object. +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/.generator/templates/signing.mustache b/.generator/templates/signing.mustache new file mode 100644 index 00000000000..22477a06f38 --- /dev/null +++ b/.generator/templates/signing.mustache @@ -0,0 +1,430 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "bytes" + "context" + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/textproto" + "os" + "strings" + "time" +) + +const ( + // Constants for HTTP signature parameters. + // The '(request-target)' parameter concatenates the lowercased :method, an + // ASCII space, and the :path pseudo-headers. + HttpSignatureParameterRequestTarget string = "(request-target)" + // The '(created)' parameter expresses when the signature was + // created. The value MUST be a Unix timestamp integer value. + HttpSignatureParameterCreated string = "(created)" + // The '(expires)' parameter expresses when the signature ceases to + // be valid. The value MUST be a Unix timestamp integer value. + HttpSignatureParameterExpires string = "(expires)" +) + +const ( + // Constants for HTTP headers. + // The 'Host' header, as defined in RFC 2616, section 14.23. + HttpHeaderHost string = "Host" + // The 'Date' header. + HttpHeaderDate string = "Date" + // The digest header, as defined in RFC 3230, section 4.3.2. + HttpHeaderDigest string = "Digest" + // The HTTP Authorization header, as defined in RFC 7235, section 4.2. + HttpHeaderAuthorization string = "Authorization" +) + +const ( + // Specifies the Digital Signature Algorithm is derived from metadata + // associated with 'keyId'. Supported DSA algorithms are RSASSA-PKCS1-v1_5, + // RSASSA-PSS, and ECDSA. + // The hash is SHA-512. + // This is the default value. + HttpSigningSchemeHs2019 string = "hs2019" + // Use RSASSA-PKCS1-v1_5 with SHA-512 hash. Deprecated. + HttpSigningSchemeRsaSha512 string = "rsa-sha512" + // Use RSASSA-PKCS1-v1_5 with SHA-256 hash. Deprecated. + HttpSigningSchemeRsaSha256 string = "rsa-sha256" + + // RFC 8017 section 7.2 + // Calculate the message signature using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5. + // PKCSV1_5 is deterministic. The same message and key will produce an identical + // signature value each time. + HttpSigningAlgorithmRsaPKCS1v15 string = "RSASSA-PKCS1-v1_5" + // Calculate the message signature using probabilistic signature scheme RSASSA-PSS. + // PSS is randomized and will produce a different signature value each time. + HttpSigningAlgorithmRsaPSS string = "RSASSA-PSS" +) + +var supportedSigningSchemes = map[string]bool{ + HttpSigningSchemeHs2019: true, + HttpSigningSchemeRsaSha512: true, + HttpSigningSchemeRsaSha256: true, +} + + +// HttpSignatureAuth provides HTTP signature authentication to a request passed +// via context using ContextHttpSignatureAuth. +// An 'Authorization' header is calculated by creating a hash of select headers, +// and optionally the body of the HTTP request, then signing the hash value using +// a private key which is available to the client. +// +// SignedHeaders specifies the list of HTTP headers that are included when generating +// the message signature. +// The two special signature headers '(request-target)' and '(created)' SHOULD be +// included in SignedHeaders. +// The '(created)' header expresses when the signature was created. +// The '(request-target)' header is a concatenation of the lowercased :method, an +// ASCII space, and the :path pseudo-headers. +// +// For example, SignedHeaders can be set to: +// (request-target) (created) date host digest +// +// When SignedHeaders is not specified, the client defaults to a single value, '(created)', +// in the list of HTTP headers. +// When SignedHeaders contains the 'Digest' value, the client performs the following operations: +// 1. Calculate a digest of request body, as specified in RFC3230, section 4.3.2. +// 2. Set the 'Digest' header in the request body. +// 3. Include the 'Digest' header and value in the HTTP signature. +type HttpSignatureAuth struct { + KeyId string // A key identifier. + PrivateKeyPath string // The path to the private key. + Passphrase string // The passphrase to decrypt the private key, if the key is encrypted. + SigningScheme string // The signature scheme, when signing HTTP requests. Supported value is 'hs2019'. + // The signature algorithm, when signing HTTP requests. + // Supported values are RSASSA-PKCS1-v1_5, RSASSA-PSS. + SigningAlgorithm string + SignedHeaders []string // A list of HTTP headers included when generating the signature for the message. + // SignatureMaxValidity specifies the maximum duration of the signature validity. + // The value is used to set the '(expires)' signature parameter in the HTTP request. + // '(expires)' is set to '(created)' plus the value of the SignatureMaxValidity field. + // To specify the '(expires)' signature parameter, set 'SignatureMaxValidity' and add '(expires)' to 'SignedHeaders'. + SignatureMaxValidity time.Duration + privateKey crypto.PrivateKey // The private key used to sign HTTP requests. +} + +// SetPrivateKey accepts a private key string and sets it. +func (h *HttpSignatureAuth) SetPrivateKey(privateKey string) error { + return h.parsePrivateKey([]byte(privateKey)) +} + +// ContextWithValue validates the HttpSignatureAuth configuration parameters and returns a context +// suitable for HTTP signature. An error is returned if the HttpSignatureAuth configuration parameters +// are invalid. +func (h *HttpSignatureAuth) ContextWithValue(ctx context.Context) (context.Context, error) { + if h.KeyId == "" { + return nil, fmt.Errorf("Key ID must be specified") + } + if h.PrivateKeyPath == "" && h.privateKey == nil { + return nil, fmt.Errorf("Private key path must be specified") + } + if _, ok := supportedSigningSchemes[h.SigningScheme]; !ok { + return nil, fmt.Errorf("Invalid signing scheme: '%v'", h.SigningScheme) + } + m := make(map[string]bool) + for _, h := range h.SignedHeaders { + if strings.ToLower(h) == strings.ToLower(HttpHeaderAuthorization) { + return nil, fmt.Errorf("Signed headers cannot include the 'Authorization' header") + } + m[h] = true + } + if len(m) != len(h.SignedHeaders) { + return nil, fmt.Errorf("List of signed headers cannot have duplicate names") + } + if h.SignatureMaxValidity < 0 { + return nil, fmt.Errorf("Signature max validity must be a positive value") + } + if err := h.loadPrivateKey(); err != nil { + return nil, err + } + return context.WithValue(ctx, ContextHttpSignatureAuth, *h), nil +} + +// GetPublicKey returns the public key associated with this HTTP signature configuration. +func (h *HttpSignatureAuth) GetPublicKey() (crypto.PublicKey, error) { + if h.privateKey == nil { + if err := h.loadPrivateKey(); err != nil { + return nil, err + } + } + switch key := h.privateKey.(type) { + case *rsa.PrivateKey: + return key.Public(), nil + case *ecdsa.PrivateKey: + return key.Public(), nil + default: + // Do not change '%T' to anything else such as '%v'! + // The value of the private key must not be returned. + return nil, fmt.Errorf("Unsupported key: %T", h.privateKey) + } +} + +// loadPrivateKey reads the private key from the file specified in the HttpSignatureAuth. +// The key is loaded only when privateKey is not already set. +func (h *HttpSignatureAuth) loadPrivateKey() (err error) { + if h.privateKey != nil { + return nil + } + var file *os.File + file, err = os.Open(h.PrivateKeyPath) + if err != nil { + return fmt.Errorf("Cannot load private key '%s'. Error: %v", h.PrivateKeyPath, err) + } + defer func() { + err = file.Close() + }() + var priv []byte + priv, err = ioutil.ReadAll(file) + if err != nil { + return err + } + return h.parsePrivateKey(priv) +} + +// parsePrivateKey decodes privateKey byte array to crypto.PrivateKey type. +func (h *HttpSignatureAuth) parsePrivateKey(priv []byte) error { + pemBlock, _ := pem.Decode(priv) + if pemBlock == nil { + // No PEM data has been found. + return fmt.Errorf("File '%s' does not contain PEM data", h.PrivateKeyPath) + } + var privKey []byte + var err error + if x509.IsEncryptedPEMBlock(pemBlock) { + // The PEM data is encrypted. + privKey, err = x509.DecryptPEMBlock(pemBlock, []byte(h.Passphrase)) + if err != nil { + // Failed to decrypt PEM block. Because of deficiencies in the encrypted-PEM format, + // it's not always possibleto detect an incorrect password. + return err + } + } else { + privKey = pemBlock.Bytes + } + switch pemBlock.Type { + case "RSA PRIVATE KEY": + if h.privateKey, err = x509.ParsePKCS1PrivateKey(privKey); err != nil { + return err + } + case "EC PRIVATE KEY", "PRIVATE KEY": + // https://tools.ietf.org/html/rfc5915 section 4. + if h.privateKey, err = x509.ParsePKCS8PrivateKey(privKey); err != nil { + return err + } + default: + return fmt.Errorf("Key '%s' is not supported", pemBlock.Type) + } + return nil +} + +// SignRequest signs the request using HTTP signature. +// See https://datatracker.ietf.org/doc/draft-cavage-http-signatures/ +// +// Do not add, remove or change headers that are included in the SignedHeaders +// after SignRequest has been invoked; this is because the header values are +// included in the signature. Any subsequent alteration will cause a signature +// verification failure. +// If there are multiple instances of the same header field, all +// header field values associated with the header field MUST be +// concatenated, separated by a ASCII comma and an ASCII space +// ', ', and used in the order in which they will appear in the +// transmitted HTTP message. +func SignRequest( + ctx context.Context, + r *http.Request, + auth HttpSignatureAuth) error { + + if auth.privateKey == nil { + return fmt.Errorf("Private key is not set") + } + now := time.Now() + date := now.UTC().Format(http.TimeFormat) + // The 'created' field expresses when the signature was created. + // The value MUST be a Unix timestamp integer value. See 'HTTP signature' section 2.1.4. + created := now.Unix() + + var h crypto.Hash + var err error + var prefix string + var expiresUnix float64 + + if auth.SignatureMaxValidity < 0 { + return fmt.Errorf("Signature validity must be a positive value") + } + if auth.SignatureMaxValidity > 0 { + e := now.Add(auth.SignatureMaxValidity) + expiresUnix = float64(e.Unix()) + float64(e.Nanosecond()) / float64(time.Second) + } + // Determine the cryptographic hash to be used for the signature and the body digest. + switch auth.SigningScheme { + case HttpSigningSchemeRsaSha512, HttpSigningSchemeHs2019: + h = crypto.SHA512 + prefix = "SHA-512=" + case HttpSigningSchemeRsaSha256: + // This is deprecated and should no longer be used. + h = crypto.SHA256 + prefix = "SHA-256=" + default: + return fmt.Errorf("Unsupported signature scheme: %v", auth.SigningScheme) + } + if !h.Available() { + return fmt.Errorf("Hash '%v' is not available", h) + } + + // Build the "(request-target)" signature header. + var sb bytes.Buffer + fmt.Fprintf(&sb, "%s %s", strings.ToLower(r.Method), r.URL.EscapedPath()) + if r.URL.RawQuery != "" { + // The ":path" pseudo-header field includes the path and query parts + // of the target URI (the "path-absolute" production and optionally a + // '?' character followed by the "query" production (see Sections 3.3 + // and 3.4 of [RFC3986] + fmt.Fprintf(&sb, "?%s", r.URL.RawQuery) + } + requestTarget := sb.String() + sb.Reset() + + // Build the string to be signed. + signedHeaders := auth.SignedHeaders + if len(signedHeaders) == 0 { + signedHeaders = []string{HttpSignatureParameterCreated} + } + // Validate the list of signed headers has no duplicates. + m := make(map[string]bool) + for _, h := range signedHeaders { + m[h] = true + } + if len(m) != len(signedHeaders) { + return fmt.Errorf("List of signed headers must not have any duplicates") + } + hasCreatedParameter := false + hasExpiresParameter := false + for i, header := range signedHeaders { + header = strings.ToLower(header) + var value string + switch header { + case strings.ToLower(HttpHeaderAuthorization): + return fmt.Errorf("Cannot include the 'Authorization' header as a signed header.") + case HttpSignatureParameterRequestTarget: + value = requestTarget + case HttpSignatureParameterCreated: + value = fmt.Sprintf("%d", created) + hasCreatedParameter = true + case HttpSignatureParameterExpires: + if auth.SignatureMaxValidity.Nanoseconds() == 0 { + return fmt.Errorf("Cannot set '(expires)' signature parameter. SignatureMaxValidity is not configured.") + } + value = fmt.Sprintf("%.3f", expiresUnix) + hasExpiresParameter = true + case "date": + value = date + r.Header.Set(HttpHeaderDate, date) + case "digest": + // Calculate the digest of the HTTP request body. + // Calculate body digest per RFC 3230 section 4.3.2 + bodyHash := h.New() + if r.Body != nil { + // Make a copy of the body io.Reader so that we can read the body to calculate the hash, + // then one more time when marshaling the request. + var body io.Reader + body, err = r.GetBody() + if err != nil { + return err + } + if _, err = io.Copy(bodyHash, body); err != nil { + return err + } + } + d := bodyHash.Sum(nil) + value = prefix + base64.StdEncoding.EncodeToString(d) + r.Header.Set(HttpHeaderDigest, value) + case "host": + value = r.Host + r.Header.Set(HttpHeaderHost, r.Host) + default: + var ok bool + var v []string + canonicalHeader := textproto.CanonicalMIMEHeaderKey(header) + if v, ok = r.Header[canonicalHeader]; !ok { + // If a header specified in the headers parameter cannot be matched with + // a provided header in the message, the implementation MUST produce an error. + return fmt.Errorf("Header '%s' does not exist in the request", canonicalHeader) + } + // If there are multiple instances of the same header field, all + // header field values associated with the header field MUST be + // concatenated, separated by a ASCII comma and an ASCII space + // `, `, and used in the order in which they will appear in the + // transmitted HTTP message. + value = strings.Join(v, ", ") + } + if i > 0 { + fmt.Fprintf(&sb, "\n") + } + fmt.Fprintf(&sb, "%s: %s", header, value) + } + if expiresUnix != 0 && !hasExpiresParameter { + return fmt.Errorf("SignatureMaxValidity is specified, but '(expired)' parameter is not present") + } + msg := []byte(sb.String()) + msgHash := h.New() + if _, err = msgHash.Write(msg); err != nil { + return err + } + d := msgHash.Sum(nil) + + var signature []byte + switch key := auth.privateKey.(type) { + case *rsa.PrivateKey: + switch auth.SigningAlgorithm { + case HttpSigningAlgorithmRsaPKCS1v15: + signature, err = rsa.SignPKCS1v15(rand.Reader, key, h, d) + case "", HttpSigningAlgorithmRsaPSS: + signature, err = rsa.SignPSS(rand.Reader, key, h, d, nil) + default: + return fmt.Errorf("Unsupported signing algorithm: '%s'", auth.SigningAlgorithm) + } + case *ecdsa.PrivateKey: + signature, err = key.Sign(rand.Reader, d, h) + case ed25519.PrivateKey: // requires go 1.13 + signature, err = key.Sign(rand.Reader, msg, crypto.Hash(0)) + default: + return fmt.Errorf("Unsupported private key") + } + if err != nil { + return err + } + + sb.Reset() + for i, header := range signedHeaders { + if i > 0 { + sb.WriteRune(' ') + } + sb.WriteString(strings.ToLower(header)) + } + headers_list := sb.String() + sb.Reset() + fmt.Fprintf(&sb, `Signature keyId="%s",algorithm="%s",`, auth.KeyId, auth.SigningScheme) + if hasCreatedParameter { + fmt.Fprintf(&sb, "created=%d,", created) + } + if hasExpiresParameter { + fmt.Fprintf(&sb, "expires=%.3f,", expiresUnix) + } + fmt.Fprintf(&sb, `headers="%s",signature="%s"`, headers_list, base64.StdEncoding.EncodeToString(signature)) + authStr := sb.String() + r.Header.Set(HttpHeaderAuthorization, authStr) + return nil +} diff --git a/.generator/templates/utils.mustache b/.generator/templates/utils.mustache new file mode 100644 index 00000000000..5ae789a996c --- /dev/null +++ b/.generator/templates/utils.mustache @@ -0,0 +1,319 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "encoding/json" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given boolean value. +func PtrBool(v bool) *bool { return &v } + +// PtrInt is a helper routine that returns a pointer to given integer value. +func PtrInt(v int) *int { return &v } + +// PtrInt32 is a helper routine that returns a pointer to given integer value. +func PtrInt32(v int32) *int32 { return &v } + +// PtrInt64 is a helper routine that returns a pointer to given integer value. +func PtrInt64(v int64) *int64 { return &v } + +// PtrFloat32 is a helper routine that returns a pointer to given float value. +func PtrFloat32(v float32) *float32 { return &v } + +// PtrFloat64 is a helper routine that returns a pointer to given float value. +func PtrFloat64(v float64) *float64 { return &v } + +// PtrString is a helper routine that returns a pointer to given string value. +func PtrString(v string) *string { return &v } + +// PtrTime is helper routine that returns a pointer to given Time value. +func PtrTime(v time.Time) *time.Time { return &v } + +type NullableBool struct { + value *bool + isSet bool +} + +func (v NullableBool) Get() *bool { + return v.value +} + +func (v *NullableBool) Set(val *bool) { + v.value = val + v.isSet = true +} + +func (v NullableBool) IsSet() bool { + return v.isSet +} + +func (v *NullableBool) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBool(val *bool) *NullableBool { + return &NullableBool{value: val, isSet: true} +} + +func (v NullableBool) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBool) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt struct { + value *int + isSet bool +} + +func (v NullableInt) Get() *int { + return v.value +} + +func (v *NullableInt) Set(val *int) { + v.value = val + v.isSet = true +} + +func (v NullableInt) IsSet() bool { + return v.isSet +} + +func (v *NullableInt) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt(val *int) *NullableInt { + return &NullableInt{value: val, isSet: true} +} + +func (v NullableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt32 struct { + value *int32 + isSet bool +} + +func (v NullableInt32) Get() *int32 { + return v.value +} + +func (v *NullableInt32) Set(val *int32) { + v.value = val + v.isSet = true +} + +func (v NullableInt32) IsSet() bool { + return v.isSet +} + +func (v *NullableInt32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt32(val *int32) *NullableInt32 { + return &NullableInt32{value: val, isSet: true} +} + +func (v NullableInt32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt64 struct { + value *int64 + isSet bool +} + +func (v NullableInt64) Get() *int64 { + return v.value +} + +func (v *NullableInt64) Set(val *int64) { + v.value = val + v.isSet = true +} + +func (v NullableInt64) IsSet() bool { + return v.isSet +} + +func (v *NullableInt64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt64(val *int64) *NullableInt64 { + return &NullableInt64{value: val, isSet: true} +} + +func (v NullableInt64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat32 struct { + value *float32 + isSet bool +} + +func (v NullableFloat32) Get() *float32 { + return v.value +} + +func (v *NullableFloat32) Set(val *float32) { + v.value = val + v.isSet = true +} + +func (v NullableFloat32) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat32(val *float32) *NullableFloat32 { + return &NullableFloat32{value: val, isSet: true} +} + +func (v NullableFloat32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat64 struct { + value *float64 + isSet bool +} + +func (v NullableFloat64) Get() *float64 { + return v.value +} + +func (v *NullableFloat64) Set(val *float64) { + v.value = val + v.isSet = true +} + +func (v NullableFloat64) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat64(val *float64) *NullableFloat64 { + return &NullableFloat64{value: val, isSet: true} +} + +func (v NullableFloat64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableString struct { + value *string + isSet bool +} + +func (v NullableString) Get() *string { + return v.value +} + +func (v *NullableString) Set(val *string) { + v.value = val + v.isSet = true +} + +func (v NullableString) IsSet() bool { + return v.isSet +} + +func (v *NullableString) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableString(val *string) *NullableString { + return &NullableString{value: val, isSet: true} +} + +func (v NullableString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableString) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableTime struct { + value *time.Time + isSet bool +} + +func (v NullableTime) Get() *time.Time { + return v.value +} + +func (v *NullableTime) Set(val *time.Time) { + v.value = val + v.isSet = true +} + +func (v NullableTime) IsSet() bool { + return v.isSet +} + +func (v *NullableTime) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTime(val *time.Time) *NullableTime { + return &NullableTime{value: val, isSet: true} +} + +func (v NullableTime) MarshalJSON() ([]byte, error) { + return v.value.MarshalJSON() +} + +func (v *NullableTime) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +}