From 504d82d96e2f99595850f7b2e949d46290bfb795 Mon Sep 17 00:00:00 2001 From: Indian-boult Date: Sat, 21 Nov 2026 10:20:09 +0530 Subject: [PATCH 1/2] generate code that compiles for array header and query parameters A header parameter whose schema is an array made the generated client call `to_string()` on a `Vec`, which does not compile. This is #822. The CLI passed the whole `Vec` type to `clap::value_parser!`, which does not compile either, as #1170 describes. The client now sends an array header in the simple style that OpenAPI 3.0.3 gives header parameters, with the items joined by commas, and the httpmock extension matches an array header against the same joined value. The CLI makes an array parameter a flag that may be repeated, parses each occurrence with the item type's parser, and collects the values. Scalar parameters generate the same code as before. sample_openapi/param-arrays.json has array query and header parameters, including one whose items are an enum. On main the client and CLI generated from it fail to compile with 10 errors. build_param_arrays.rs compiles the generated clients in CI. Array query parameters in httpmock are #1260, which #1261 handles, so param_arrays_httpmock stays out of the output crate like buildomat_httpmock. Fixes #822 --- progenitor-impl/src/cli.rs | 66 +++- progenitor-impl/src/httpmock.rs | 8 +- progenitor-impl/src/method.rs | 44 ++- progenitor-impl/tests/output/src/lib.rs | 5 + .../tests/output/src/param_arrays_builder.rs | 331 +++++++++++++++++ .../output/src/param_arrays_builder_tagged.rs | 332 ++++++++++++++++++ .../tests/output/src/param_arrays_cli.rs | 163 +++++++++ .../tests/output/src/param_arrays_httpmock.rs | 112 ++++++ .../output/src/param_arrays_positional.rs | 234 ++++++++++++ progenitor-impl/tests/test_output.rs | 5 + progenitor/tests/build_param_arrays.rs | 52 +++ sample_openapi/param-arrays.json | 90 +++++ 12 files changed, 1426 insertions(+), 16 deletions(-) create mode 100644 progenitor-impl/tests/output/src/param_arrays_builder.rs create mode 100644 progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs create mode 100644 progenitor-impl/tests/output/src/param_arrays_cli.rs create mode 100644 progenitor-impl/tests/output/src/param_arrays_httpmock.rs create mode 100644 progenitor-impl/tests/output/src/param_arrays_positional.rs create mode 100644 progenitor/tests/build_param_arrays.rs create mode 100644 sample_openapi/param-arrays.json diff --git a/progenitor-impl/src/cli.rs b/progenitor-impl/src/cli.rs index fb197853..31782fcf 100644 --- a/progenitor-impl/src/cli.rs +++ b/progenitor-impl/src/cli.rs @@ -445,24 +445,56 @@ impl Generator { // There should be no conflicting path or query parameters. assert!(!args.has_arg(&arg_name)); - let parser = clap_arg(&arg_name, volitionality, ¶m.description, &arg_type); + // An array parameter is a flag that may be repeated, with each + // occurrence parsed as one item. + let item_type = param + .typ + .list_item_type(typespace) + .map(|item_type_id| typespace.get_type(&item_type_id)); + + let parser = match &item_type { + Some(item_type) => clap_arg( + &arg_name, + volitionality, + ¶m.description, + item_type, + true, + ), + None => clap_arg( + &arg_name, + volitionality, + ¶m.description, + &arg_type, + false, + ), + }; let arg_fn_name = sanitize(¶m.name, Case::Snake); let arg_fn = format_ident!("{}", arg_fn_name); - let OperationParameterType::Type(arg_type_id) = ¶m.typ else { - panic!() - }; - let arg_type = typespace.get_type(arg_type_id); let arg_type_name = arg_type.ident_in(crate::TYPES_MOD); - let consumer = quote! { - if let Some(value) = - matches.get_one::<#arg_type_name>(#arg_name) - { - // clone here in case the arg type doesn't impl - // From<&T> - request = request.#arg_fn(value.clone()); + let consumer = match &item_type { + Some(item_type) => { + let item_type_name = item_type.ident_in(crate::TYPES_MOD); + quote! { + if let Some(values) = + matches.get_many::<#item_type_name>(#arg_name) + { + request = request.#arg_fn( + values.cloned().collect::<#arg_type_name>() + ); + } + } } + None => quote! { + if let Some(value) = + matches.get_one::<#arg_type_name>(#arg_name) + { + // clone here in case the arg type doesn't impl + // From<&T> + request = request.#arg_fn(value.clone()); + } + }, }; args.add_arg(arg_name, CliArg { parser, consumer }) @@ -625,6 +657,7 @@ impl Generator { volitionality, &description.map(str::to_string), &prop_type, + false, ); let prop_fn = format_ident!("{}", sanitize(name, Case::Snake)); @@ -666,12 +699,20 @@ enum Volitionality { RequiredIfNoBody, } +/// Build the clap argument for a flag. With `multiple`, `arg_type` is the item +/// type and the flag may be repeated, once per item. fn clap_arg( arg_name: &str, volitionality: Volitionality, description: &Option, arg_type: &typify::typespace::view::Type<'_, TypeId>, + multiple: bool, ) -> TokenStream { + let action = multiple.then(|| { + quote! { + .action(::clap::ArgAction::Append) + } + }); let help = description.as_ref().map(|description| { quote! { .help(#description) @@ -733,6 +774,7 @@ fn clap_arg( ::clap::Arg::new(#arg_name) .long(#arg_name) .value_parser(#value_parser) + #action #required #help } diff --git a/progenitor-impl/src/httpmock.rs b/progenitor-impl/src/httpmock.rs index e28fcf24..93740b9d 100644 --- a/progenitor-impl/src/httpmock.rs +++ b/progenitor-impl/src/httpmock.rs @@ -10,6 +10,7 @@ use crate::{ method::{ BodyContentType, HttpMethod, OperationParameter, OperationParameterKind, OperationParameterType, OperationResponse, OperationResponseKind, OperationResponseStatus, + header_value_string, }, util::{Case, sanitize}, }; @@ -177,6 +178,9 @@ impl Generator { }; let name_ident = format_ident!("{}", name); + let header_value = + header_value_string(quote! { value }, typ.list_item_type(typespace).is_some()); + let (required, handler) = match kind { OperationParameterKind::Path => { let re_fmt = method.path.as_wildcard_param(api_name); @@ -199,7 +203,7 @@ impl Generator { OperationParameterKind::Header(true) => ( true, quote! { - Self(self.0.header(#api_name, value.to_string())) + Self(self.0.header(#api_name, #header_value)) }, ), @@ -222,7 +226,7 @@ impl Generator { if let Some(value) = value.into() { Self(self.0.header( #api_name, - value.to_string() + #header_value )) } else { Self(self.0.header_missing(#api_name)) diff --git a/progenitor-impl/src/method.rs b/progenitor-impl/src/method.rs index a5eb92b4..42270c9b 100644 --- a/progenitor-impl/src/method.rs +++ b/progenitor-impl/src/method.rs @@ -108,6 +108,26 @@ pub enum OperationParameterType { RawBody, } +impl OperationParameterType { + /// The item type when this is an array or a set. Header and query + /// parameters of these types are sent, mocked and parsed from the command + /// line one item at a time. + pub(crate) fn list_item_type( + &self, + typespace: &typespace::Typespace, + ) -> Option { + let OperationParameterType::Type(type_id) = self else { + return None; + }; + match typespace.get_type(type_id).details() { + typespace::view::TypeDetails::Vec(item) | typespace::view::TypeDetails::Set(item) => { + Some(item) + } + _ => None, + } + } +} + #[derive(Debug, PartialEq, Eq)] pub enum OperationParameterKind { Path, @@ -802,19 +822,22 @@ impl Generator { OperationParameterKind::Header(required) => { let hn = ¶m.api_name; let hn_ident = format_ident!("{}", ¶m.name); + let is_list = param.typ.list_item_type(self.typespace()).is_some(); let res = if *required { + let value = header_value_string(quote! { #hn_ident }, is_list); quote! { header_map.append( #hn, - #hn_ident.to_string().try_into()? + #value.try_into()? ); } } else { + let value = header_value_string(quote! { value }, is_list); quote! { if let Some(value) = #hn_ident { header_map.append( #hn, - value.to_string().try_into()? + #value.try_into()? ); } } @@ -2140,6 +2163,23 @@ impl Construction { } } +/// The string a header parameter is sent as. OpenAPI 3.0.3 gives header +/// parameters only the simple style, which joins the items of an array with +/// commas, so `["a", "b"]` is sent as `a,b`. +pub(crate) fn header_value_string(value: TokenStream, is_list: bool) -> TokenStream { + if is_list { + quote! { + #value + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(",") + } + } else { + quote! { #value.to_string() } + } +} + fn make_doc_comment(method: &OperationMethod) -> String { let mut buf = String::new(); diff --git a/progenitor-impl/tests/output/src/lib.rs b/progenitor-impl/tests/output/src/lib.rs index 3e183e62..b8ad0475 100644 --- a/progenitor-impl/tests/output/src/lib.rs +++ b/progenitor-impl/tests/output/src/lib.rs @@ -14,6 +14,11 @@ pub mod nexus_builder_tagged; pub mod nexus_cli; pub mod nexus_httpmock; pub mod nexus_positional; +pub mod param_arrays_builder; +pub mod param_arrays_builder_tagged; +pub mod param_arrays_cli; +//pub mod param_arrays_httpmock; +pub mod param_arrays_positional; pub mod param_collision_builder; pub mod param_collision_builder_tagged; pub mod param_collision_cli; diff --git a/progenitor-impl/tests/output/src/param_arrays_builder.rs b/progenitor-impl/tests/output/src/param_arrays_builder.rs new file mode 100644 index 00000000..c5174852 --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_builder.rs @@ -0,0 +1,331 @@ +#[allow(unused_imports)] +use progenitor_client::{encode_path, ClientHooks, OperationInfo, QueryParam, RequestBuilderExt}; +#[allow(unused_imports)] +pub use progenitor_client::{ByteStream, ClientInfo, Error, ResponseValue}; +/// Items consumers will typically use such as the Client. +pub mod prelude { + pub use self::super::Client; +} + +/// Types used as operation parameters and responses. +#[allow(clippy::all)] +pub mod types { + ///`ThingKind` + #[derive( + :: serde :: Deserialize, + :: serde :: Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + schemars :: JsonSchema, + )] + pub enum ThingKind { + #[serde(rename = "widget")] + Widget, + #[serde(rename = "gadget")] + Gadget, + } + + impl ::std::fmt::Display for ThingKind { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Widget => f.write_str("widget"), + Self::Gadget => f.write_str("gadget"), + } + } + } + + impl ::std::str::FromStr for ThingKind { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "widget" => Ok(Self::Widget), + "gadget" => Ok(Self::Gadget), + _ => Err("invalid value".into()), + } + } + } + + impl ::std::convert::TryFrom<&str> for ThingKind { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + + impl ::std::convert::TryFrom<::std::string::String> for ThingKind { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + + /// Error types. + pub mod error { + /// Error from a `TryFrom` or `FromStr` implementation. + pub struct ConversionError(::std::borrow::Cow<'static, str>); + impl ::std::error::Error for ConversionError {} + impl ::std::fmt::Display for ConversionError { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> { + ::std::fmt::Display::fmt(&self.0, f) + } + } + + impl ::std::fmt::Debug for ConversionError { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> { + ::std::fmt::Debug::fmt(&self.0, f) + } + } + + impl From<&'static str> for ConversionError { + fn from(value: &'static str) -> Self { + Self(value.into()) + } + } + + impl From for ConversionError { + fn from(value: String) -> Self { + Self(value.into()) + } + } + } +} + +#[derive(Clone, Debug)] +///Client for Parameter Arrays +/// +///Header and query parameters whose schema is an array +/// +///Version: v1 +pub struct Client { + pub(crate) baseurl: String, + pub(crate) client: reqwest::Client, +} + +impl Client { + /// Create a new client. + /// + /// `baseurl` is the base URL provided to the internal + /// `reqwest::Client`, and should include a scheme and hostname, + /// as well as port and a path stem if applicable. + /// + /// Returns an error if the `reqwest::Client` cannot be built, + /// for example when the TLS backend fails to initialize. + pub fn new(baseurl: &str) -> Result { + #[cfg(not(target_arch = "wasm32"))] + let client = { + let dur = ::std::time::Duration::from_secs(15u64); + reqwest::ClientBuilder::new() + .connect_timeout(dur) + .timeout(dur) + }; + #[cfg(target_arch = "wasm32")] + let client = reqwest::ClientBuilder::new(); + Ok(Self::new_with_client(baseurl, client.build()?)) + } + + /// Construct a new client with an existing `reqwest::Client`, + /// allowing more control over its configuration. + /// + /// `baseurl` is the base URL provided to the internal + /// `reqwest::Client`, and should include a scheme and hostname, + /// as well as port and a path stem if applicable. + pub fn new_with_client(baseurl: &str, client: reqwest::Client) -> Self { + Self { + baseurl: baseurl.to_string(), + client, + } + } +} + +impl ClientInfo<()> for Client { + fn api_version() -> &'static str { + "v1" + } + + fn baseurl(&self) -> &str { + self.baseurl.as_str() + } + + fn client(&self) -> &reqwest::Client { + &self.client + } + + fn inner(&self) -> &() { + &() + } +} + +impl ClientHooks<()> for &Client {} +impl Client { + ///Sends a `GET` request to `/things` + /// + ///Arguments: + /// - `kinds`: kinds of thing to include + /// - `tags`: tags that each thing must have + /// - `x_labels`: labels for the request + /// - `x_shard_ids`: shards to read from + ///```ignore + /// let response = client.list_things() + /// .kinds(kinds) + /// .tags(tags) + /// .x_labels(x_labels) + /// .x_shard_ids(x_shard_ids) + /// .send() + /// .await; + /// ``` + pub fn list_things(&self) -> builder::ListThings<'_> { + builder::ListThings::new(self) + } +} + +/// Types for composing operation parameters. +#[allow(clippy::all)] +pub mod builder { + use super::types; + #[allow(unused_imports)] + use super::{ + encode_path, ByteStream, ClientHooks, ClientInfo, Error, OperationInfo, QueryParam, + RequestBuilderExt, ResponseValue, + }; + ///Builder for [`Client::list_things`] + /// + ///[`Client::list_things`]: super::Client::list_things + #[derive(Debug, Clone)] + pub struct ListThings<'a> { + client: &'a super::Client, + kinds: Result<::std::vec::Vec, String>, + tags: Result>, String>, + x_labels: Result>, String>, + x_shard_ids: Result<::std::vec::Vec, String>, + } + + impl<'a> ListThings<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + kinds: Err("kinds was not initialized".to_string()), + tags: Ok(None), + x_labels: Ok(None), + x_shard_ids: Err("x_shard_ids was not initialized".to_string()), + } + } + + pub fn kinds(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec>, + { + self.kinds = value.try_into().map_err(|_| { + "conversion to `:: std :: vec :: Vec < ThingKind >` for kinds failed".to_string() + }); + self + } + + pub fn tags(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec<::std::string::String>>, + { + self.tags = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: vec :: Vec < :: std :: string :: String >` for tags \ + failed" + .to_string() + }); + self + } + + pub fn x_labels(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec<::std::string::String>>, + { + self.x_labels = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: vec :: Vec < :: std :: string :: String >` for x_labels \ + failed" + .to_string() + }); + self + } + + pub fn x_shard_ids(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec>, + { + self.x_shard_ids = value.try_into().map_err(|_| { + "conversion to `:: std :: vec :: Vec < u32 >` for x_shard_ids failed".to_string() + }); + self + } + + ///Sends a `GET` request to `/things` + pub async fn send( + self, + ) -> Result>, Error<()>> { + let Self { + client, + kinds, + tags, + x_labels, + x_shard_ids, + } = self; + let kinds = kinds.map_err(Error::InvalidRequest)?; + let tags = tags.map_err(Error::InvalidRequest)?; + let x_labels = x_labels.map_err(Error::InvalidRequest)?; + let x_shard_ids = x_shard_ids.map_err(Error::InvalidRequest)?; + let url = format!("{}/things", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + if let Some(value) = x_labels { + header_map.append( + "x-labels", + value + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } + header_map.append( + "x-shard-ids", + x_shard_ids + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&QueryParam::new("kinds", &kinds)) + .query(&QueryParam::new("tags", &tags)) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_things", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response(response).await, + _ => Err(Error::UnexpectedResponse(response)), + } + } + } +} diff --git a/progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs b/progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs new file mode 100644 index 00000000..2b6f27b0 --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs @@ -0,0 +1,332 @@ +#[allow(unused_imports)] +use progenitor_client::{encode_path, ClientHooks, OperationInfo, QueryParam, RequestBuilderExt}; +#[allow(unused_imports)] +pub use progenitor_client::{ByteStream, ClientInfo, Error, ResponseValue}; +/// Items consumers will typically use such as the Client and +/// extension traits. +pub mod prelude { + #[allow(unused_imports)] + pub use super::Client; +} + +/// Types used as operation parameters and responses. +#[allow(clippy::all)] +pub mod types { + ///`ThingKind` + #[derive( + :: serde :: Deserialize, + :: serde :: Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum ThingKind { + #[serde(rename = "widget")] + Widget, + #[serde(rename = "gadget")] + Gadget, + } + + impl ::std::fmt::Display for ThingKind { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Widget => f.write_str("widget"), + Self::Gadget => f.write_str("gadget"), + } + } + } + + impl ::std::str::FromStr for ThingKind { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "widget" => Ok(Self::Widget), + "gadget" => Ok(Self::Gadget), + _ => Err("invalid value".into()), + } + } + } + + impl ::std::convert::TryFrom<&str> for ThingKind { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + + impl ::std::convert::TryFrom<::std::string::String> for ThingKind { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + + /// Error types. + pub mod error { + /// Error from a `TryFrom` or `FromStr` implementation. + pub struct ConversionError(::std::borrow::Cow<'static, str>); + impl ::std::error::Error for ConversionError {} + impl ::std::fmt::Display for ConversionError { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> { + ::std::fmt::Display::fmt(&self.0, f) + } + } + + impl ::std::fmt::Debug for ConversionError { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> { + ::std::fmt::Debug::fmt(&self.0, f) + } + } + + impl From<&'static str> for ConversionError { + fn from(value: &'static str) -> Self { + Self(value.into()) + } + } + + impl From for ConversionError { + fn from(value: String) -> Self { + Self(value.into()) + } + } + } +} + +#[derive(Clone, Debug)] +///Client for Parameter Arrays +/// +///Header and query parameters whose schema is an array +/// +///Version: v1 +pub struct Client { + pub(crate) baseurl: String, + pub(crate) client: reqwest::Client, +} + +impl Client { + /// Create a new client. + /// + /// `baseurl` is the base URL provided to the internal + /// `reqwest::Client`, and should include a scheme and hostname, + /// as well as port and a path stem if applicable. + /// + /// Returns an error if the `reqwest::Client` cannot be built, + /// for example when the TLS backend fails to initialize. + pub fn new(baseurl: &str) -> Result { + #[cfg(not(target_arch = "wasm32"))] + let client = { + let dur = ::std::time::Duration::from_secs(15u64); + reqwest::ClientBuilder::new() + .connect_timeout(dur) + .timeout(dur) + }; + #[cfg(target_arch = "wasm32")] + let client = reqwest::ClientBuilder::new(); + Ok(Self::new_with_client(baseurl, client.build()?)) + } + + /// Construct a new client with an existing `reqwest::Client`, + /// allowing more control over its configuration. + /// + /// `baseurl` is the base URL provided to the internal + /// `reqwest::Client`, and should include a scheme and hostname, + /// as well as port and a path stem if applicable. + pub fn new_with_client(baseurl: &str, client: reqwest::Client) -> Self { + Self { + baseurl: baseurl.to_string(), + client, + } + } +} + +impl ClientInfo<()> for Client { + fn api_version() -> &'static str { + "v1" + } + + fn baseurl(&self) -> &str { + self.baseurl.as_str() + } + + fn client(&self) -> &reqwest::Client { + &self.client + } + + fn inner(&self) -> &() { + &() + } +} + +impl ClientHooks<()> for &Client {} +impl Client { + ///Sends a `GET` request to `/things` + /// + ///Arguments: + /// - `kinds`: kinds of thing to include + /// - `tags`: tags that each thing must have + /// - `x_labels`: labels for the request + /// - `x_shard_ids`: shards to read from + ///```ignore + /// let response = client.list_things() + /// .kinds(kinds) + /// .tags(tags) + /// .x_labels(x_labels) + /// .x_shard_ids(x_shard_ids) + /// .send() + /// .await; + /// ``` + pub fn list_things(&self) -> builder::ListThings<'_> { + builder::ListThings::new(self) + } +} + +/// Types for composing operation parameters. +#[allow(clippy::all)] +pub mod builder { + use super::types; + #[allow(unused_imports)] + use super::{ + encode_path, ByteStream, ClientHooks, ClientInfo, Error, OperationInfo, QueryParam, + RequestBuilderExt, ResponseValue, + }; + ///Builder for [`Client::list_things`] + /// + ///[`Client::list_things`]: super::Client::list_things + #[derive(Debug, Clone)] + pub struct ListThings<'a> { + client: &'a super::Client, + kinds: Result<::std::vec::Vec, String>, + tags: Result>, String>, + x_labels: Result>, String>, + x_shard_ids: Result<::std::vec::Vec, String>, + } + + impl<'a> ListThings<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + kinds: Err("kinds was not initialized".to_string()), + tags: Ok(None), + x_labels: Ok(None), + x_shard_ids: Err("x_shard_ids was not initialized".to_string()), + } + } + + pub fn kinds(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec>, + { + self.kinds = value.try_into().map_err(|_| { + "conversion to `:: std :: vec :: Vec < ThingKind >` for kinds failed".to_string() + }); + self + } + + pub fn tags(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec<::std::string::String>>, + { + self.tags = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: vec :: Vec < :: std :: string :: String >` for tags \ + failed" + .to_string() + }); + self + } + + pub fn x_labels(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec<::std::string::String>>, + { + self.x_labels = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: vec :: Vec < :: std :: string :: String >` for x_labels \ + failed" + .to_string() + }); + self + } + + pub fn x_shard_ids(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec>, + { + self.x_shard_ids = value.try_into().map_err(|_| { + "conversion to `:: std :: vec :: Vec < u32 >` for x_shard_ids failed".to_string() + }); + self + } + + ///Sends a `GET` request to `/things` + pub async fn send( + self, + ) -> Result>, Error<()>> { + let Self { + client, + kinds, + tags, + x_labels, + x_shard_ids, + } = self; + let kinds = kinds.map_err(Error::InvalidRequest)?; + let tags = tags.map_err(Error::InvalidRequest)?; + let x_labels = x_labels.map_err(Error::InvalidRequest)?; + let x_shard_ids = x_shard_ids.map_err(Error::InvalidRequest)?; + let url = format!("{}/things", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + if let Some(value) = x_labels { + header_map.append( + "x-labels", + value + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } + header_map.append( + "x-shard-ids", + x_shard_ids + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&QueryParam::new("kinds", &kinds)) + .query(&QueryParam::new("tags", &tags)) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_things", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response(response).await, + _ => Err(Error::UnexpectedResponse(response)), + } + } + } +} diff --git a/progenitor-impl/tests/output/src/param_arrays_cli.rs b/progenitor-impl/tests/output/src/param_arrays_cli.rs new file mode 100644 index 00000000..ba24b7ee --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_cli.rs @@ -0,0 +1,163 @@ +use crate::param_arrays_builder::*; +use anyhow::Context as _; +pub struct Cli { + client: Client, + config: T, +} + +impl Cli { + pub fn new(client: Client, config: T) -> Self { + Self { client, config } + } + + pub fn get_command(cmd: CliCommand) -> ::clap::Command { + match cmd { + CliCommand::ListThings => Self::cli_list_things(), + } + } + + pub fn cli_list_things() -> ::clap::Command { + ::clap::Command::new("") + .arg( + ::clap::Arg::new("kinds") + .long("kinds") + .value_parser(::clap::builder::TypedValueParser::map( + ::clap::builder::PossibleValuesParser::new([ + types::ThingKind::Widget.to_string(), + types::ThingKind::Gadget.to_string(), + ]), + |s| types::ThingKind::try_from(s).unwrap(), + )) + .action(::clap::ArgAction::Append) + .required(true) + .help("kinds of thing to include"), + ) + .arg( + ::clap::Arg::new("tags") + .long("tags") + .value_parser(::clap::value_parser!(::std::string::String)) + .action(::clap::ArgAction::Append) + .required(false) + .help("tags that each thing must have"), + ) + .arg( + ::clap::Arg::new("x-labels") + .long("x-labels") + .value_parser(::clap::value_parser!(::std::string::String)) + .action(::clap::ArgAction::Append) + .required(false) + .help("labels for the request"), + ) + .arg( + ::clap::Arg::new("x-shard-ids") + .long("x-shard-ids") + .value_parser(::clap::value_parser!(u32)) + .action(::clap::ArgAction::Append) + .required(true) + .help("shards to read from"), + ) + } + + pub async fn execute( + &self, + cmd: CliCommand, + matches: &::clap::ArgMatches, + ) -> anyhow::Result<()> { + match cmd { + CliCommand::ListThings => self.execute_list_things(matches).await, + } + } + + pub async fn execute_list_things(&self, matches: &::clap::ArgMatches) -> anyhow::Result<()> { + let mut request = self.client.list_things(); + if let Some(values) = matches.get_many::("kinds") { + request = request.kinds( + values + .cloned() + .collect::<::std::vec::Vec>(), + ); + } + + if let Some(values) = matches.get_many::<::std::string::String>("tags") { + request = request.tags( + values + .cloned() + .collect::<::std::vec::Vec<::std::string::String>>(), + ); + } + + if let Some(values) = matches.get_many::<::std::string::String>("x-labels") { + request = request.x_labels( + values + .cloned() + .collect::<::std::vec::Vec<::std::string::String>>(), + ); + } + + if let Some(values) = matches.get_many::("x-shard-ids") { + request = request.x_shard_ids(values.cloned().collect::<::std::vec::Vec>()); + } + + self.config.execute_list_things(matches, &mut request)?; + let result = request.send().await; + match result { + Ok(r) => { + self.config.success_item(&r); + Ok(()) + } + Err(r) => { + self.config.error(&r); + Err(anyhow::Error::new(r)) + } + } + } +} + +pub trait CliConfig { + fn success_item(&self, value: &ResponseValue) + where + T: std::clone::Clone + schemars::JsonSchema + serde::Serialize + std::fmt::Debug; + fn success_no_item(&self, value: &ResponseValue<()>); + fn error(&self, value: &Error) + where + T: std::clone::Clone + schemars::JsonSchema + serde::Serialize + std::fmt::Debug; + fn list_start(&self) + where + T: std::clone::Clone + schemars::JsonSchema + serde::Serialize + std::fmt::Debug; + fn list_item(&self, value: &T) + where + T: std::clone::Clone + schemars::JsonSchema + serde::Serialize + std::fmt::Debug; + fn list_end_success(&self) + where + T: std::clone::Clone + schemars::JsonSchema + serde::Serialize + std::fmt::Debug; + fn list_end_error(&self, value: &Error) + where + T: std::clone::Clone + schemars::JsonSchema + serde::Serialize + std::fmt::Debug; + fn json_body_schema(&self) + where + T: std::clone::Clone + schemars::JsonSchema + serde::Serialize + std::fmt::Debug; + fn execute_list_things( + &self, + matches: &::clap::ArgMatches, + request: &mut builder::ListThings, + ) -> anyhow::Result<()> { + Ok(()) + } +} + +#[derive(Copy, Clone, Debug)] +pub enum CliCommand { + ListThings, +} + +impl CliCommand { + pub fn iter() -> impl Iterator { + vec![CliCommand::ListThings].into_iter() + } + + pub fn operation_id(&self) -> &'static str { + match self { + CliCommand::ListThings => "list_things", + } + } +} diff --git a/progenitor-impl/tests/output/src/param_arrays_httpmock.rs b/progenitor-impl/tests/output/src/param_arrays_httpmock.rs new file mode 100644 index 00000000..00b13005 --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_httpmock.rs @@ -0,0 +1,112 @@ +pub mod operations { + #![doc = r" [`When`](::httpmock::When) and [`Then`](::httpmock::Then)"] + #![doc = r" wrappers for each operation. Each can be converted to"] + #![doc = r" its inner type with a call to `into_inner()`. This can"] + #![doc = r" be used to explicitly deviate from permitted values."] + use crate::param_arrays_builder::*; + pub struct ListThingsWhen(::httpmock::When); + impl ListThingsWhen { + pub fn new(inner: ::httpmock::When) -> Self { + Self( + inner + .method(::httpmock::Method::GET) + .path_matches(regex::Regex::new("^/things$").unwrap()), + ) + } + + pub fn into_inner(self) -> ::httpmock::When { + self.0 + } + + pub fn kinds(self, value: &::std::vec::Vec) -> Self { + Self(self.0.query_param("kinds", value.to_string())) + } + + pub fn tags<'a, T>(self, value: T) -> Self + where + T: Into>>, + { + if let Some(value) = value.into() { + Self(self.0.query_param("tags", value.to_string())) + } else { + Self(self.0.query_param_missing("tags")) + } + } + + pub fn x_labels<'a, T>(self, value: T) -> Self + where + T: Into>>, + { + if let Some(value) = value.into() { + Self( + self.0.header( + "x-labels", + value + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(","), + ), + ) + } else { + Self(self.0.header_missing("x-labels")) + } + } + + pub fn x_shard_ids(self, value: &::std::vec::Vec) -> Self { + Self( + self.0.header( + "x-shard-ids", + value + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(","), + ), + ) + } + } + + pub struct ListThingsThen(::httpmock::Then); + impl ListThingsThen { + pub fn new(inner: ::httpmock::Then) -> Self { + Self(inner) + } + + pub fn into_inner(self) -> ::httpmock::Then { + self.0 + } + + pub fn ok(self, value: &::std::vec::Vec<::std::string::String>) -> Self { + Self( + self.0 + .status(200u16) + .header("content-type", "application/json") + .json_body_obj(value), + ) + } + } +} + +#[doc = r" An extension trait for [`MockServer`](::httpmock::MockServer) that"] +#[doc = r" adds a method for each operation. These are the equivalent of"] +#[doc = r" type-checked [`mock()`](::httpmock::MockServer::mock) calls."] +pub trait MockServerExt { + fn list_things(&self, config_fn: F) -> ::httpmock::Mock<'_> + where + F: FnOnce(operations::ListThingsWhen, operations::ListThingsThen); +} + +impl MockServerExt for ::httpmock::MockServer { + fn list_things(&self, config_fn: F) -> ::httpmock::Mock<'_> + where + F: FnOnce(operations::ListThingsWhen, operations::ListThingsThen), + { + self.mock(|when, then| { + config_fn( + operations::ListThingsWhen::new(when), + operations::ListThingsThen::new(then), + ) + }) + } +} diff --git a/progenitor-impl/tests/output/src/param_arrays_positional.rs b/progenitor-impl/tests/output/src/param_arrays_positional.rs new file mode 100644 index 00000000..642d3fbd --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_positional.rs @@ -0,0 +1,234 @@ +#[allow(unused_imports)] +use progenitor_client::{encode_path, ClientHooks, OperationInfo, QueryParam, RequestBuilderExt}; +#[allow(unused_imports)] +pub use progenitor_client::{ByteStream, ClientInfo, Error, ResponseValue}; +/// Items consumers will typically use such as the Client. +pub mod prelude { + #[allow(unused_imports)] + pub use super::Client; +} + +/// Types used as operation parameters and responses. +#[allow(clippy::all)] +pub mod types { + ///`ThingKind` + #[derive( + :: serde :: Deserialize, + :: serde :: Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum ThingKind { + #[serde(rename = "widget")] + Widget, + #[serde(rename = "gadget")] + Gadget, + } + + impl ::std::fmt::Display for ThingKind { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Widget => f.write_str("widget"), + Self::Gadget => f.write_str("gadget"), + } + } + } + + impl ::std::str::FromStr for ThingKind { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "widget" => Ok(Self::Widget), + "gadget" => Ok(Self::Gadget), + _ => Err("invalid value".into()), + } + } + } + + impl ::std::convert::TryFrom<&str> for ThingKind { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + + impl ::std::convert::TryFrom<::std::string::String> for ThingKind { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + + /// Error types. + pub mod error { + /// Error from a `TryFrom` or `FromStr` implementation. + pub struct ConversionError(::std::borrow::Cow<'static, str>); + impl ::std::error::Error for ConversionError {} + impl ::std::fmt::Display for ConversionError { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> { + ::std::fmt::Display::fmt(&self.0, f) + } + } + + impl ::std::fmt::Debug for ConversionError { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> { + ::std::fmt::Debug::fmt(&self.0, f) + } + } + + impl From<&'static str> for ConversionError { + fn from(value: &'static str) -> Self { + Self(value.into()) + } + } + + impl From for ConversionError { + fn from(value: String) -> Self { + Self(value.into()) + } + } + } +} + +#[derive(Clone, Debug)] +///Client for Parameter Arrays +/// +///Header and query parameters whose schema is an array +/// +///Version: v1 +pub struct Client { + pub(crate) baseurl: String, + pub(crate) client: reqwest::Client, +} + +impl Client { + /// Create a new client. + /// + /// `baseurl` is the base URL provided to the internal + /// `reqwest::Client`, and should include a scheme and hostname, + /// as well as port and a path stem if applicable. + /// + /// Returns an error if the `reqwest::Client` cannot be built, + /// for example when the TLS backend fails to initialize. + pub fn new(baseurl: &str) -> Result { + #[cfg(not(target_arch = "wasm32"))] + let client = { + let dur = ::std::time::Duration::from_secs(15u64); + reqwest::ClientBuilder::new() + .connect_timeout(dur) + .timeout(dur) + }; + #[cfg(target_arch = "wasm32")] + let client = reqwest::ClientBuilder::new(); + Ok(Self::new_with_client(baseurl, client.build()?)) + } + + /// Construct a new client with an existing `reqwest::Client`, + /// allowing more control over its configuration. + /// + /// `baseurl` is the base URL provided to the internal + /// `reqwest::Client`, and should include a scheme and hostname, + /// as well as port and a path stem if applicable. + pub fn new_with_client(baseurl: &str, client: reqwest::Client) -> Self { + Self { + baseurl: baseurl.to_string(), + client, + } + } +} + +impl ClientInfo<()> for Client { + fn api_version() -> &'static str { + "v1" + } + + fn baseurl(&self) -> &str { + self.baseurl.as_str() + } + + fn client(&self) -> &reqwest::Client { + &self.client + } + + fn inner(&self) -> &() { + &() + } +} + +impl ClientHooks<()> for &Client {} +#[allow(clippy::all)] +impl Client { + ///Sends a `GET` request to `/things` + /// + ///Arguments: + /// - `kinds`: kinds of thing to include + /// - `tags`: tags that each thing must have + /// - `x_labels`: labels for the request + /// - `x_shard_ids`: shards to read from + pub async fn list_things<'a>( + &'a self, + kinds: &'a ::std::vec::Vec, + tags: Option<&'a ::std::vec::Vec<::std::string::String>>, + x_labels: Option<&'a ::std::vec::Vec<::std::string::String>>, + x_shard_ids: &'a ::std::vec::Vec, + ) -> Result>, Error<()>> { + let url = format!("{}/things", self.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(Self::api_version()), + ); + if let Some(value) = x_labels { + header_map.append( + "x-labels", + value + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } + + header_map.append( + "x-shard-ids", + x_shard_ids + .iter() + .map(::std::string::ToString::to_string) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + #[allow(unused_mut)] + let mut request = self + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .query(&QueryParam::new("kinds", &kinds)) + .query(&QueryParam::new("tags", &tags)) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "list_things", + }; + self.pre(&mut request, &info).await?; + let result = self.exec(request, &info).await; + self.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response(response).await, + _ => Err(Error::UnexpectedResponse(response)), + } + } +} diff --git a/progenitor-impl/tests/test_output.rs b/progenitor-impl/tests/test_output.rs index 90383843..a3422e6a 100644 --- a/progenitor-impl/tests/test_output.rs +++ b/progenitor-impl/tests/test_output.rs @@ -164,6 +164,11 @@ fn test_param_collision() { verify_apis("param-collision.json"); } +#[test] +fn test_param_arrays() { + verify_apis("param-arrays.json"); +} + #[test] fn test_cli_gen() { verify_apis("cli-gen.json"); diff --git a/progenitor/tests/build_param_arrays.rs b/progenitor/tests/build_param_arrays.rs new file mode 100644 index 00000000..845c6575 --- /dev/null +++ b/progenitor/tests/build_param_arrays.rs @@ -0,0 +1,52 @@ +// Copyright 2026 Oxide Computer Company + +mod positional { + progenitor::generate_api!("../sample_openapi/param-arrays.json"); + + fn _ignore() { + let _ = Client::new("").unwrap().list_things( + &vec![types::ThingKind::Widget], + Some(&vec!["tag".to_string()]), + Some(&vec!["label".to_string()]), + &vec![1, 2], + ); + } +} + +mod builder_untagged { + progenitor::generate_api!( + spec = "../sample_openapi/param-arrays.json", + interface = Builder, + tags = Merged, + ); + + fn _ignore() { + let _ = Client::new("") + .unwrap() + .list_things() + .kinds(vec![types::ThingKind::Widget]) + .tags(vec!["tag".to_string()]) + .x_labels(vec!["label".to_string()]) + .x_shard_ids(vec![1, 2]) + .send(); + } +} + +mod builder_tagged { + progenitor::generate_api!( + spec = "../sample_openapi/param-arrays.json", + interface = Builder, + tags = Separate, + ); + + fn _ignore() { + let _ = Client::new("") + .unwrap() + .list_things() + .kinds(vec![types::ThingKind::Widget]) + .tags(vec!["tag".to_string()]) + .x_labels(vec!["label".to_string()]) + .x_shard_ids(vec![1, 2]) + .send(); + } +} diff --git a/sample_openapi/param-arrays.json b/sample_openapi/param-arrays.json new file mode 100644 index 00000000..f61f0b02 --- /dev/null +++ b/sample_openapi/param-arrays.json @@ -0,0 +1,90 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Parameter Arrays", + "description": "Header and query parameters whose schema is an array", + "version": "v1" + }, + "paths": { + "/things": { + "get": { + "operationId": "list_things", + "parameters": [ + { + "in": "query", + "name": "kinds", + "description": "kinds of thing to include", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ThingKind" + } + } + }, + { + "in": "query", + "name": "tags", + "description": "tags that each thing must have", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "in": "header", + "name": "x-labels", + "description": "labels for the request", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "in": "header", + "name": "x-shard-ids", + "description": "shards to read from", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "uint32" + } + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ThingKind": { + "type": "string", + "enum": [ + "widget", + "gadget" + ] + } + } + } +} From 55acf20b7d28e71f226db970beeb666d77a846af Mon Sep 17 00:00:00 2001 From: Indian-boult Date: Mon, 23 Nov 2026 02:30:02 +0530 Subject: [PATCH 2/2] convert array header items with a method call The array header code mapped items through ToString::to_string, which needs the item type itself to implement Display. A typify newtype for a string with a pattern only derefs to String, so a header whose items have a pattern failed to compile with "ListThingsXCodesItem doesn't implement Display". A method call derefs, as the scalar header code already does. param-arrays.json gains an x-codes header whose items have a pattern, and build_param_arrays compiles the clients generated from it. --- progenitor-impl/src/method.rs | 6 +- .../tests/output/src/param_arrays_builder.rs | 106 +++++++++++++++++- .../output/src/param_arrays_builder_tagged.rs | 93 ++++++++++++++- .../tests/output/src/param_arrays_cli.rs | 16 +++ .../tests/output/src/param_arrays_httpmock.rs | 24 +++- .../output/src/param_arrays_positional.rs | 79 ++++++++++++- progenitor/tests/build_param_arrays.rs | 1 + sample_openapi/param-arrays.json | 12 ++ 8 files changed, 324 insertions(+), 13 deletions(-) diff --git a/progenitor-impl/src/method.rs b/progenitor-impl/src/method.rs index 42270c9b..dfbcfefe 100644 --- a/progenitor-impl/src/method.rs +++ b/progenitor-impl/src/method.rs @@ -2165,13 +2165,15 @@ impl Construction { /// The string a header parameter is sent as. OpenAPI 3.0.3 gives header /// parameters only the simple style, which joins the items of an array with -/// commas, so `["a", "b"]` is sent as `a,b`. +/// commas, so `["a", "b"]` is sent as `a,b`. Each item is converted with a +/// method call, as a scalar header is, so an item type that only derefs to +/// `String` works too. pub(crate) fn header_value_string(value: TokenStream, is_list: bool) -> TokenStream { if is_list { quote! { #value .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(",") } diff --git a/progenitor-impl/tests/output/src/param_arrays_builder.rs b/progenitor-impl/tests/output/src/param_arrays_builder.rs index c5174852..6ec86bf4 100644 --- a/progenitor-impl/tests/output/src/param_arrays_builder.rs +++ b/progenitor-impl/tests/output/src/param_arrays_builder.rs @@ -10,6 +10,78 @@ pub mod prelude { /// Types used as operation parameters and responses. #[allow(clippy::all)] pub mod types { + ///`ListThingsXCodesItem` + #[derive(:: serde :: Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct ListThingsXCodesItem(::std::string::String); + impl ::std::ops::Deref for ListThingsXCodesItem { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + + impl ::std::convert::From for ::std::string::String { + fn from(value: ListThingsXCodesItem) -> Self { + value.0 + } + } + + impl ::std::str::FromStr for ListThingsXCodesItem { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + ::std::convert::TryFrom::try_from(value) + } + } + + impl ::std::convert::TryFrom<&str> for ListThingsXCodesItem { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::with_flags("^[a-z]+$", "u").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[a-z]+$\"".into()); + } + Ok(Self(value.to_string())) + } + } + + impl ::std::convert::TryFrom<::std::string::String> for ListThingsXCodesItem { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + ::std::convert::TryFrom::try_from(value.as_str()) + } + } + + impl<'de> ::serde::Deserialize<'de> for ListThingsXCodesItem { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::convert::TryFrom::try_from(::std::string::String::deserialize(deserializer)?) + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + + impl ::schemars::JsonSchema for ListThingsXCodesItem { + fn schema_name() -> ::std::string::String { + "ListThingsXCodesItem".to_string() + } + + fn json_schema(g: &mut ::schemars::r#gen::SchemaGenerator) -> ::schemars::schema::Schema { + let mut schema = + <::std::string::String as ::schemars::JsonSchema>::json_schema(g).into_object(); + schema.string().pattern = ::std::option::Option::Some("^[a-z]+$".to_string()); + schema.into() + } + } + ///`ThingKind` #[derive( :: serde :: Deserialize, @@ -170,12 +242,14 @@ impl Client { ///Arguments: /// - `kinds`: kinds of thing to include /// - `tags`: tags that each thing must have + /// - `x_codes`: codes whose items are constrained strings /// - `x_labels`: labels for the request /// - `x_shard_ids`: shards to read from ///```ignore /// let response = client.list_things() /// .kinds(kinds) /// .tags(tags) + /// .x_codes(x_codes) /// .x_labels(x_labels) /// .x_shard_ids(x_shard_ids) /// .send() @@ -203,6 +277,7 @@ pub mod builder { client: &'a super::Client, kinds: Result<::std::vec::Vec, String>, tags: Result>, String>, + x_codes: Result>, String>, x_labels: Result>, String>, x_shard_ids: Result<::std::vec::Vec, String>, } @@ -213,6 +288,7 @@ pub mod builder { client: client, kinds: Err("kinds was not initialized".to_string()), tags: Ok(None), + x_codes: Ok(None), x_labels: Ok(None), x_shard_ids: Err("x_shard_ids was not initialized".to_string()), } @@ -240,6 +316,17 @@ pub mod builder { self } + pub fn x_codes(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec>, + { + self.x_codes = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: vec :: Vec < ListThingsXCodesItem >` for x_codes failed" + .to_string() + }); + self + } + pub fn x_labels(mut self, value: V) -> Self where V: std::convert::TryInto<::std::vec::Vec<::std::string::String>>, @@ -270,25 +357,38 @@ pub mod builder { client, kinds, tags, + x_codes, x_labels, x_shard_ids, } = self; let kinds = kinds.map_err(Error::InvalidRequest)?; let tags = tags.map_err(Error::InvalidRequest)?; + let x_codes = x_codes.map_err(Error::InvalidRequest)?; let x_labels = x_labels.map_err(Error::InvalidRequest)?; let x_shard_ids = x_shard_ids.map_err(Error::InvalidRequest)?; let url = format!("{}/things", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_codes { + header_map.append( + "x-codes", + value + .iter() + .map(|v| v.to_string()) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } if let Some(value) = x_labels { header_map.append( "x-labels", value .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(",") .try_into()?, @@ -298,7 +398,7 @@ pub mod builder { "x-shard-ids", x_shard_ids .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(",") .try_into()?, diff --git a/progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs b/progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs index 2b6f27b0..a835e8b6 100644 --- a/progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs +++ b/progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs @@ -12,6 +12,65 @@ pub mod prelude { /// Types used as operation parameters and responses. #[allow(clippy::all)] pub mod types { + ///`ListThingsXCodesItem` + #[derive(:: serde :: Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct ListThingsXCodesItem(::std::string::String); + impl ::std::ops::Deref for ListThingsXCodesItem { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + + impl ::std::convert::From for ::std::string::String { + fn from(value: ListThingsXCodesItem) -> Self { + value.0 + } + } + + impl ::std::str::FromStr for ListThingsXCodesItem { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + ::std::convert::TryFrom::try_from(value) + } + } + + impl ::std::convert::TryFrom<&str> for ListThingsXCodesItem { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::with_flags("^[a-z]+$", "u").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[a-z]+$\"".into()); + } + Ok(Self(value.to_string())) + } + } + + impl ::std::convert::TryFrom<::std::string::String> for ListThingsXCodesItem { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + ::std::convert::TryFrom::try_from(value.as_str()) + } + } + + impl<'de> ::serde::Deserialize<'de> for ListThingsXCodesItem { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::convert::TryFrom::try_from(::std::string::String::deserialize(deserializer)?) + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`ThingKind` #[derive( :: serde :: Deserialize, @@ -171,12 +230,14 @@ impl Client { ///Arguments: /// - `kinds`: kinds of thing to include /// - `tags`: tags that each thing must have + /// - `x_codes`: codes whose items are constrained strings /// - `x_labels`: labels for the request /// - `x_shard_ids`: shards to read from ///```ignore /// let response = client.list_things() /// .kinds(kinds) /// .tags(tags) + /// .x_codes(x_codes) /// .x_labels(x_labels) /// .x_shard_ids(x_shard_ids) /// .send() @@ -204,6 +265,7 @@ pub mod builder { client: &'a super::Client, kinds: Result<::std::vec::Vec, String>, tags: Result>, String>, + x_codes: Result>, String>, x_labels: Result>, String>, x_shard_ids: Result<::std::vec::Vec, String>, } @@ -214,6 +276,7 @@ pub mod builder { client: client, kinds: Err("kinds was not initialized".to_string()), tags: Ok(None), + x_codes: Ok(None), x_labels: Ok(None), x_shard_ids: Err("x_shard_ids was not initialized".to_string()), } @@ -241,6 +304,17 @@ pub mod builder { self } + pub fn x_codes(mut self, value: V) -> Self + where + V: std::convert::TryInto<::std::vec::Vec>, + { + self.x_codes = value.try_into().map(Some).map_err(|_| { + "conversion to `:: std :: vec :: Vec < ListThingsXCodesItem >` for x_codes failed" + .to_string() + }); + self + } + pub fn x_labels(mut self, value: V) -> Self where V: std::convert::TryInto<::std::vec::Vec<::std::string::String>>, @@ -271,25 +345,38 @@ pub mod builder { client, kinds, tags, + x_codes, x_labels, x_shard_ids, } = self; let kinds = kinds.map_err(Error::InvalidRequest)?; let tags = tags.map_err(Error::InvalidRequest)?; + let x_codes = x_codes.map_err(Error::InvalidRequest)?; let x_labels = x_labels.map_err(Error::InvalidRequest)?; let x_shard_ids = x_shard_ids.map_err(Error::InvalidRequest)?; let url = format!("{}/things", client.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), ); + if let Some(value) = x_codes { + header_map.append( + "x-codes", + value + .iter() + .map(|v| v.to_string()) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } if let Some(value) = x_labels { header_map.append( "x-labels", value .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(",") .try_into()?, @@ -299,7 +386,7 @@ pub mod builder { "x-shard-ids", x_shard_ids .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(",") .try_into()?, diff --git a/progenitor-impl/tests/output/src/param_arrays_cli.rs b/progenitor-impl/tests/output/src/param_arrays_cli.rs index ba24b7ee..5d13fd14 100644 --- a/progenitor-impl/tests/output/src/param_arrays_cli.rs +++ b/progenitor-impl/tests/output/src/param_arrays_cli.rs @@ -40,6 +40,14 @@ impl Cli { .required(false) .help("tags that each thing must have"), ) + .arg( + ::clap::Arg::new("x-codes") + .long("x-codes") + .value_parser(::clap::value_parser!(types::ListThingsXCodesItem)) + .action(::clap::ArgAction::Append) + .required(false) + .help("codes whose items are constrained strings"), + ) .arg( ::clap::Arg::new("x-labels") .long("x-labels") @@ -86,6 +94,14 @@ impl Cli { ); } + if let Some(values) = matches.get_many::("x-codes") { + request = request.x_codes( + values + .cloned() + .collect::<::std::vec::Vec>(), + ); + } + if let Some(values) = matches.get_many::<::std::string::String>("x-labels") { request = request.x_labels( values diff --git a/progenitor-impl/tests/output/src/param_arrays_httpmock.rs b/progenitor-impl/tests/output/src/param_arrays_httpmock.rs index 00b13005..7baa416c 100644 --- a/progenitor-impl/tests/output/src/param_arrays_httpmock.rs +++ b/progenitor-impl/tests/output/src/param_arrays_httpmock.rs @@ -33,6 +33,26 @@ pub mod operations { } } + pub fn x_codes<'a, T>(self, value: T) -> Self + where + T: Into>>, + { + if let Some(value) = value.into() { + Self( + self.0.header( + "x-codes", + value + .iter() + .map(|v| v.to_string()) + .collect::<::std::vec::Vec<_>>() + .join(","), + ), + ) + } else { + Self(self.0.header_missing("x-codes")) + } + } + pub fn x_labels<'a, T>(self, value: T) -> Self where T: Into>>, @@ -43,7 +63,7 @@ pub mod operations { "x-labels", value .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(","), ), @@ -59,7 +79,7 @@ pub mod operations { "x-shard-ids", value .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(","), ), diff --git a/progenitor-impl/tests/output/src/param_arrays_positional.rs b/progenitor-impl/tests/output/src/param_arrays_positional.rs index 642d3fbd..adda976f 100644 --- a/progenitor-impl/tests/output/src/param_arrays_positional.rs +++ b/progenitor-impl/tests/output/src/param_arrays_positional.rs @@ -11,6 +11,65 @@ pub mod prelude { /// Types used as operation parameters and responses. #[allow(clippy::all)] pub mod types { + ///`ListThingsXCodesItem` + #[derive(:: serde :: Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + #[serde(transparent)] + pub struct ListThingsXCodesItem(::std::string::String); + impl ::std::ops::Deref for ListThingsXCodesItem { + type Target = ::std::string::String; + fn deref(&self) -> &::std::string::String { + &self.0 + } + } + + impl ::std::convert::From for ::std::string::String { + fn from(value: ListThingsXCodesItem) -> Self { + value.0 + } + } + + impl ::std::str::FromStr for ListThingsXCodesItem { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + ::std::convert::TryFrom::try_from(value) + } + } + + impl ::std::convert::TryFrom<&str> for ListThingsXCodesItem { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + static PATTERN: ::std::sync::LazyLock<::regress::Regex> = + ::std::sync::LazyLock::new(|| { + ::regress::Regex::with_flags("^[a-z]+$", "u").unwrap() + }); + if PATTERN.find(value).is_none() { + return Err("doesn't match pattern \"^[a-z]+$\"".into()); + } + Ok(Self(value.to_string())) + } + } + + impl ::std::convert::TryFrom<::std::string::String> for ListThingsXCodesItem { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + ::std::convert::TryFrom::try_from(value.as_str()) + } + } + + impl<'de> ::serde::Deserialize<'de> for ListThingsXCodesItem { + fn deserialize(deserializer: D) -> ::std::result::Result + where + D: ::serde::Deserializer<'de>, + { + ::std::convert::TryFrom::try_from(::std::string::String::deserialize(deserializer)?) + .map_err(|e: self::error::ConversionError| { + ::custom(e.to_string()) + }) + } + } + ///`ThingKind` #[derive( :: serde :: Deserialize, @@ -171,27 +230,41 @@ impl Client { ///Arguments: /// - `kinds`: kinds of thing to include /// - `tags`: tags that each thing must have + /// - `x_codes`: codes whose items are constrained strings /// - `x_labels`: labels for the request /// - `x_shard_ids`: shards to read from pub async fn list_things<'a>( &'a self, kinds: &'a ::std::vec::Vec, tags: Option<&'a ::std::vec::Vec<::std::string::String>>, + x_codes: Option<&'a ::std::vec::Vec>, x_labels: Option<&'a ::std::vec::Vec<::std::string::String>>, x_shard_ids: &'a ::std::vec::Vec, ) -> Result>, Error<()>> { let url = format!("{}/things", self.baseurl,); - let mut header_map = ::reqwest::header::HeaderMap::with_capacity(3usize); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(4usize); header_map.append( ::reqwest::header::HeaderName::from_static("api-version"), ::reqwest::header::HeaderValue::from_static(Self::api_version()), ); + if let Some(value) = x_codes { + header_map.append( + "x-codes", + value + .iter() + .map(|v| v.to_string()) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } + if let Some(value) = x_labels { header_map.append( "x-labels", value .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(",") .try_into()?, @@ -202,7 +275,7 @@ impl Client { "x-shard-ids", x_shard_ids .iter() - .map(::std::string::ToString::to_string) + .map(|v| v.to_string()) .collect::<::std::vec::Vec<_>>() .join(",") .try_into()?, diff --git a/progenitor/tests/build_param_arrays.rs b/progenitor/tests/build_param_arrays.rs index 845c6575..a633e6f5 100644 --- a/progenitor/tests/build_param_arrays.rs +++ b/progenitor/tests/build_param_arrays.rs @@ -7,6 +7,7 @@ mod positional { let _ = Client::new("").unwrap().list_things( &vec![types::ThingKind::Widget], Some(&vec!["tag".to_string()]), + None, Some(&vec!["label".to_string()]), &vec![1, 2], ); diff --git a/sample_openapi/param-arrays.json b/sample_openapi/param-arrays.json index f61f0b02..6591ae3e 100644 --- a/sample_openapi/param-arrays.json +++ b/sample_openapi/param-arrays.json @@ -56,6 +56,18 @@ "format": "uint32" } } + }, + { + "in": "header", + "name": "x-codes", + "description": "codes whose items are constrained strings", + "schema": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[a-z]+$" + } + } } ], "responses": {