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..dfbcfefe 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,25 @@ 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`. 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(|v| v.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..6ec86bf4 --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_builder.rs @@ -0,0 +1,431 @@ +#[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 { + ///`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, + :: 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_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() + /// .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_codes: 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_codes: 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_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>>, + { + 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_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(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(|v| v.to_string()) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } + header_map.append( + "x-shard-ids", + x_shard_ids + .iter() + .map(|v| v.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..a835e8b6 --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_builder_tagged.rs @@ -0,0 +1,419 @@ +#[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 { + ///`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, + :: 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_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() + /// .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_codes: 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_codes: 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_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>>, + { + 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_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(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(|v| v.to_string()) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } + header_map.append( + "x-shard-ids", + x_shard_ids + .iter() + .map(|v| v.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..5d13fd14 --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_cli.rs @@ -0,0 +1,179 @@ +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-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") + .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::("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 + .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..7baa416c --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_httpmock.rs @@ -0,0 +1,132 @@ +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_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>>, + { + if let Some(value) = value.into() { + Self( + self.0.header( + "x-labels", + value + .iter() + .map(|v| v.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(|v| v.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..adda976f --- /dev/null +++ b/progenitor-impl/tests/output/src/param_arrays_positional.rs @@ -0,0 +1,307 @@ +#[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 { + ///`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, + :: 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_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(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(|v| v.to_string()) + .collect::<::std::vec::Vec<_>>() + .join(",") + .try_into()?, + ); + } + + header_map.append( + "x-shard-ids", + x_shard_ids + .iter() + .map(|v| v.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..a633e6f5 --- /dev/null +++ b/progenitor/tests/build_param_arrays.rs @@ -0,0 +1,53 @@ +// 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()]), + None, + 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..6591ae3e --- /dev/null +++ b/sample_openapi/param-arrays.json @@ -0,0 +1,102 @@ +{ + "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" + } + } + }, + { + "in": "header", + "name": "x-codes", + "description": "codes whose items are constrained strings", + "schema": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[a-z]+$" + } + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ThingKind": { + "type": "string", + "enum": [ + "widget", + "gadget" + ] + } + } + } +}