Skip to content

Commit

Permalink
Refactor imports (#69)
Browse files Browse the repository at this point in the history
Co-authored-by: ci.datadog-api-spec <[email protected]>
  • Loading branch information
nkzou and ci.datadog-api-spec authored Apr 9, 2024
1 parent b8e89d6 commit aacc4cb
Show file tree
Hide file tree
Showing 864 changed files with 10,496 additions and 9,808 deletions.
2 changes: 1 addition & 1 deletion .generator/src/generator/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def format_parameters(data, spec, replace_values=None, has_body=False, **kwargs)
if has_body and body_is_required:
parameters += "body, "
if has_optional or body_is_required is False:
imports.add(f"datadog_api_client::datadog{kwargs.get('version', '')}::api::api_{kwargs.get('api')}::{spec['operationId']}OptionalParams")
imports.add(f"datadog_api_client::datadog{kwargs.get('version', '')}::api_{kwargs.get('api')}::{spec['operationId']}OptionalParams")
parameters += f"{spec['operationId']}OptionalParams::default()"
if has_body and not body_is_required:
parameters += ".body(body)"
Expand Down
47 changes: 23 additions & 24 deletions .generator/src/generator/templates/api.j2
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{% include "partial_header.j2" %}
use reqwest;
use serde::{Serialize, Deserialize};
use crate::datadog::*;
use crate::datadog;
use reqwest::header::{HeaderMap, HeaderValue};
{%- for _, _, operation in operations if "x-pagination" in operation %}
{%- if loop.first %}
Expand Down Expand Up @@ -84,21 +83,21 @@ pub enum {{operation.operationId}}Error {

#[derive(Debug, Clone)]
pub struct {{ structName }} {
config: configuration::Configuration,
config: datadog::Configuration,
client: reqwest_middleware::ClientWithMiddleware,
}

impl Default for {{ structName }} {
fn default() -> Self {
Self::with_config(configuration::Configuration::default())
Self::with_config(datadog::Configuration::default())
}
}

impl {{ structName }} {
pub fn new() -> Self {
Self::default()
}
pub fn with_config(config: configuration::Configuration) -> Self {
pub fn with_config(config: datadog::Configuration) -> Self {
let mut reqwest_client_builder = reqwest::Client::builder();

if let Some(proxy_url) = &config.proxy_url {
Expand Down Expand Up @@ -140,7 +139,7 @@ impl {{ structName }} {
Self { config, client }
}

pub fn with_client_and_config(config: configuration::Configuration, client: reqwest_middleware::ClientWithMiddleware) -> Self {
pub fn with_client_and_config(config: datadog::Configuration, client: reqwest_middleware::ClientWithMiddleware) -> Self {
Self {config, client}
}

Expand All @@ -152,14 +151,14 @@ impl {{ structName }} {
{% if operation.description is defined %}
{{ operation.description | block_comment }}
{%- endif %}
pub async fn {{operation.operationId | snake_case}}(&self{% for name, parameter in requiredParams %}, {{name|variable_name}}: {{ get_type_for_parameter(parameter, version) }}{% endfor %}{% if operation|has_optional_parameter %}, params: {{operation.operationId}}OptionalParams{% endif %}) -> Result<{% if returnType %}{{returnType}}{% else %}(){% endif %}, Error<{{operation.operationId}}Error>> {
pub async fn {{operation.operationId | snake_case}}(&self{% for name, parameter in requiredParams %}, {{name|variable_name}}: {{ get_type_for_parameter(parameter, version) }}{% endfor %}{% if operation|has_optional_parameter %}, params: {{operation.operationId}}OptionalParams{% endif %}) -> Result<{% if returnType %}{{returnType}}{% else %}(){% endif %}, datadog::Error<{{operation.operationId}}Error>> {
match self.{{operation.operationId | snake_case}}_with_http_info({% for name, parameter in requiredParams %}{{name|variable_name}}{% if loop.last %}{% if operation|has_optional_parameter %}, {% endif %}{% else %}, {% endif %}{% endfor %}{% if operation|has_optional_parameter %} params{% endif %}).await {
{%- if returnType %}
Ok(response_content) => {
if let Some(e) = response_content.entity {
Ok(e)
} else {
Err(Error::Serde(serde::de::Error::custom("response content was None")))
Err(datadog::Error::Serde(serde::de::Error::custom("response content was None")))
}
},
{%- else%}
Expand All @@ -178,7 +177,7 @@ impl {{ structName }} {

pub fn {{operation.operationId | snake_case}}_with_pagination(
&self{% for name, parameter in requiredParams %}, {% if limitParamParts[0] == name|variable_name %}mut {% endif %} {{name|variable_name}}: {{ get_type_for_parameter(parameter, version) }}{% endfor %}{% if operation|has_optional_parameter %}, mut params: {{operation.operationId}}OptionalParams{% endif %}
) -> impl Stream<Item = Result<{{ itemType }}, Error<{{ operation.operationId }}Error>>> + '_
) -> impl Stream<Item = Result<{{ itemType }}, datadog::Error<{{ operation.operationId }}Error>>> + '_
{
try_stream! {
{#- Limit param part fields #}
Expand Down Expand Up @@ -280,17 +279,17 @@ impl {{ structName }} {
{% if operation.description is defined %}
{{ operation.description | block_comment }}
{%- endif %}
pub async fn {{operation.operationId | snake_case}}_with_http_info(&self{% for name, parameter in requiredParams %}, {{name|variable_name}}: {{ get_type_for_parameter(parameter, version) }}{% endfor %}{% if operation|has_optional_parameter %}, params: {{operation.operationId}}OptionalParams{% endif %}) -> Result<ResponseContent<{% if returnType %}{{returnType}}{% else %}(){% endif %}>, Error<{{operation.operationId}}Error>> {
pub async fn {{operation.operationId | snake_case}}_with_http_info(&self{% for name, parameter in requiredParams %}, {{name|variable_name}}: {{ get_type_for_parameter(parameter, version) }}{% endfor %}{% if operation|has_optional_parameter %}, params: {{operation.operationId}}OptionalParams{% endif %}) -> Result<datadog::ResponseContent<{% if returnType %}{{returnType}}{% else %}(){% endif %}>, datadog::Error<{{operation.operationId}}Error>> {
let local_configuration = &self.config;
let operation_id = "{{ version }}.{{ operation.operationId | snake_case }}";
{%- if "x-unstable" in operation %}
if local_configuration.is_unstable_operation_enabled(operation_id) {
warn!("Using unstable operation {operation_id}");
} else {
let local_error = UnstableOperationDisabledError {
let local_error = datadog::UnstableOperationDisabledError {
msg: "Operation '{{ version }}.{{ operation.operationId | snake_case }}' is not enabled".to_string(),
};
return Err(Error::UnstableOperationDisabledError(local_error));
return Err(datadog::Error::UnstableOperationDisabledError(local_error));
}
{%- endif %}

Expand All @@ -308,7 +307,7 @@ impl {{ structName }} {
local_configuration.get_operation_host(operation_id)
{%- for name, parameter in operation|parameters if parameter.in == "path" %}, {{ name|variable_name }}=
{%- if parameter.schema.type == "string" %}
urlencode({{ name|variable_name }}{% if not parameter.required %}.unwrap(){% elif parameter.schema.nullable %}.unwrap(){% endif %}{% if parameter.schema.type == "array" %}.join(",").as_ref(){% endif %})
datadog::urlencode({{ name|variable_name }}{% if not parameter.required %}.unwrap(){% elif parameter.schema.nullable %}.unwrap(){% endif %}{% if parameter.schema.type == "array" %}.join(",").as_ref(){% endif %})
{%- else %}
{{ name|variable_name }}{% if not parameter.required %}.unwrap(){% elif parameter.schema.nullable %}.unwrap(){% endif %}{% if parameter.schema.type == "array" %}.join(",").as_ref(){% endif %}
{%- endif %}
Expand Down Expand Up @@ -372,7 +371,7 @@ impl {{ structName }} {
log::warn!("Failed to parse user agent header: {e}, falling back to default");
headers.insert(
reqwest::header::USER_AGENT,
HeaderValue::from_static(configuration::DEFAULT_USER_AGENT.as_str()),
HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
)
}
};
Expand Down Expand Up @@ -442,7 +441,7 @@ impl {{ structName }} {
{%- if operation.requestBody is defined and not formParameter %}
// build body parameters
let output = Vec::new();
let mut ser = serde_json::Serializer::with_formatter(output, DDFormatter);
let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
if {{operation.get("x-codegen-request-body-name", "body")|variable_name}}.serialize(&mut ser).is_ok() {
if let Some(content_encoding) = headers.get("Content-Encoding") {
match content_encoding.to_str().unwrap_or_default() {
Expand All @@ -456,7 +455,7 @@ impl {{ structName }} {
Ok(buf) => {
local_req_builder = local_req_builder.body(buf);
}
Err(e) => return Err(Error::Io(e)),
Err(e) => return Err(datadog::Error::Io(e)),
}
}
"deflate" => {
Expand All @@ -469,7 +468,7 @@ impl {{ structName }} {
Ok(buf) => {
local_req_builder = local_req_builder.body(buf);
}
Err(e) => return Err(Error::Io(e)),
Err(e) => return Err(datadog::Error::Io(e)),
}
}
"zstd1" => {
Expand All @@ -479,7 +478,7 @@ impl {{ structName }} {
Ok(buf) => {
local_req_builder = local_req_builder.body(buf);
}
Err(e) => return Err(Error::Io(e)),
Err(e) => return Err(datadog::Error::Io(e)),
}
}
_ => {
Expand All @@ -501,31 +500,31 @@ impl {{ structName }} {

if !local_status.is_client_error() && !local_status.is_server_error() {
{%- if returnType == "Vec<u8>" %}
Ok(ResponseContent {
Ok(datadog::ResponseContent {
status: local_status,
content: local_content.clone(),
entity: Some(local_content.into_bytes()),
})
{%- elif returnType %}
match serde_json::from_str::<{{ returnType }}>(&local_content) {
Ok(e) => return Ok(ResponseContent {
Ok(e) => return Ok(datadog::ResponseContent {
status: local_status,
content: local_content,
entity: Some(e),
}),
Err(e) => return Err(crate::datadog::Error::Serde(e)),
Err(e) => return Err(datadog::Error::Serde(e)),
};
{%- else %}
Ok(ResponseContent {
Ok(datadog::ResponseContent {
status: local_status,
content: local_content,
entity: None,
})
{%- endif %}
} else {
let local_entity: Option<{{operation.operationId}}Error> = serde_json::from_str(&local_content).ok();
let local_error = ResponseContent { status: local_status, content: local_content, entity: local_entity };
Err(Error::ResponseError(local_error))
let local_error = datadog::ResponseContent { status: local_status, content: local_content, entity: local_entity };
Err(datadog::Error::ResponseError(local_error))
}
}
{%- endfor %}
Expand Down
36 changes: 5 additions & 31 deletions .generator/src/generator/templates/common_mod.j2
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ use std::error;
use std::fmt;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

mod configuration;
pub use configuration::{Configuration, APIKey, DEFAULT_USER_AGENT};

#[derive(Debug, Clone)]
pub struct ResponseContent<T> {
pub status: reqwest::StatusCode,
Expand Down Expand Up @@ -75,38 +78,11 @@ impl <T> From<std::io::Error> for Error<T> {
}
}

pub fn urlencode<T: AsRef<str>>(s: T) -> String {
pub(crate) fn urlencode<T: AsRef<str>>(s: T) -> String {
::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect()
}

pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> {
if let serde_json::Value::Object(object) = value {
let mut params = vec![];

for (key, value) in object {
match value {
serde_json::Value::Object(_) => params.append(&mut parse_deep_object(
&format!("{}[{}]", prefix, key),
value,
)),
serde_json::Value::Array(array) => {
for (i, value) in array.iter().enumerate() {
params.append(&mut parse_deep_object(
&format!("{}[{}][{}]", prefix, key, i),
value,
));
}
},
serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())),
_ => params.push((format!("{}[{}]", prefix, key), value.to_string())),
}
}
return params;
}
unimplemented!("Only objects are supported with style=deepObject")
}

pub struct DDFormatter;
pub(crate) struct DDFormatter;

impl serde_json::ser::Formatter for DDFormatter {
fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> std::io::Result<()>
Expand All @@ -117,8 +93,6 @@ impl serde_json::ser::Formatter for DDFormatter {
}
}

pub mod configuration;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnparsedObject {
pub value: serde_json::Value,
Expand Down
6 changes: 3 additions & 3 deletions .generator/src/generator/templates/example.j2
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
{%- if context.body %}
{%- set body, imports = format_data_with_schema(context.body.value, context.api_request.schema.spec, replace_values=context._replace_values, required=True, variables=variables, version=version|upper, imports=imports)%}
{%- endif %}
use datadog_api_client::datadog::configuration::Configuration;
use datadog_api_client::datadog{{ version|upper }}::api::api_{{context["api_instance"]["name"] | snake_case}}::{{context["api_instance"]["name"]}}API;
use datadog_api_client::datadog;
use datadog_api_client::datadog{{ version|upper }}::api_{{context["api_instance"]["name"] | snake_case}}::{{context["api_instance"]["name"]}}API;
{%- for name in imports %}
use {{name}};
{%- endfor %}
Expand Down Expand Up @@ -37,7 +37,7 @@ async fn main() {
let body = {{ body }};
{%- endif %}

let {% if context._enable_operations %}mut{% endif %} configuration = Configuration::new();
let {% if context._enable_operations %}mut{% endif %} configuration = datadog::Configuration::new();

{%- for operation in context._enable_operations %}
configuration.set_unstable_operation_enabled("{{ version }}.{{ operation }}", true);
Expand Down
8 changes: 4 additions & 4 deletions .generator/src/generator/templates/function_mappings.j2
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub struct ApiInstances {
{%- for name, operations in apis.items() %}
{%- set fieldName = "api_"+name %}
{%- set structName = name.replace(" ", "")+"API" %}
pub {{version}}_{{fieldName | snake_case}}: Option<datadog{{ version.upper() }}::api::{{fieldName | snake_case}}::{{structName}}>,
pub {{version}}_{{fieldName | snake_case}}: Option<datadog{{ version.upper() }}::{{fieldName | snake_case}}::{{structName}}>,
{%- endfor %}
{%- endfor %}
}
Expand All @@ -28,7 +28,7 @@ pub fn initialize_api_instance(world: &mut DatadogWorld, api: String) {
{%- set structName = name.replace(" ", "")+"API" %}
"{{name.replace(" ", "")}}" => {
{%- for version in versions %}
world.api_instances.{{version}}_{{fieldName}} = Some(datadog{{ version.upper() }}::api::{{fieldName}}::{{structName}}::with_client_and_config(
world.api_instances.{{version}}_{{fieldName}} = Some(datadog{{ version.upper() }}::{{fieldName}}::{{structName}}::with_client_and_config(
world.config.clone(),
world.http_client.as_ref().unwrap().clone()
));
Expand Down Expand Up @@ -81,7 +81,7 @@ fn test_{{version}}_{{ operation['operationId'] | snake_case }}(world: &mut Data

{%- for parameter in optionalParams %}
{%- if loop.first %}
let mut params = datadog{{ version.upper() }}::api::{{ apiName }}::{{ operation['operationId'] }}OptionalParams::default();
let mut params = datadog{{ version.upper() }}::{{ apiName }}::{{ operation['operationId'] }}OptionalParams::default();
{%- endif %}
params.{{ parameter[0] | variable_name }} = {{ parameter[0] | variable_name }};
{%- if loop.last %}
Expand Down Expand Up @@ -130,7 +130,7 @@ fn test_{{version}}_{{ operation['operationId'] | snake_case }}_with_pagination(

{%- for parameter in optionalParams %}
{%- if loop.first %}
let mut params = datadog{{ version.upper() }}::api::{{ apiName }}::{{ operation['operationId'] }}OptionalParams::default();
let mut params = datadog{{ version.upper() }}::{{ apiName }}::{{ operation['operationId'] }}OptionalParams::default();
{%- endif %}
params.{{ parameter[0] | variable_name }} = {{ parameter[0] | variable_name }};
{%- if loop.last %}
Expand Down
4 changes: 4 additions & 0 deletions .generator/src/generator/templates/mod.j2
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{% include "partial_header.j2" %}

pub mod api;
{%- for name, operations in apis.items() %}
{%- set classname = "api_"+name%}
pub use self::api::{{classname | snake_case}};
{%- endfor %}
pub mod model;
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ datadog-api-client = "0"
Please follow the [installation](#installation) instructions and try the following snippet to validate your Datadog API key:

```rust
use datadog_api_client::datadog::configuration::Configuration;
use datadog_api_client::datadogV1::api::api_authentication::AuthenticationAPI;
use datadog_api_client::datadog::Configuration;
use datadog_api_client::datadogV1::api_authentication::AuthenticationAPI;

#[tokio::main]
async fn main() {
Expand Down
6 changes: 3 additions & 3 deletions examples/v1_authentication_validate.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// Validate API key returns "OK" response
use datadog_api_client::datadog::configuration::Configuration;
use datadog_api_client::datadogV1::api::api_authentication::AuthenticationAPI;
use datadog_api_client::datadog;
use datadog_api_client::datadogV1::api_authentication::AuthenticationAPI;

#[tokio::main]
async fn main() {
let configuration = Configuration::new();
let configuration = datadog::Configuration::new();
let api = AuthenticationAPI::with_config(configuration);
let resp = api.validate().await;
if let Ok(value) = resp {
Expand Down
6 changes: 3 additions & 3 deletions examples/v1_aws-integration_create_aws_account.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Create an AWS integration returns "OK" response
use datadog_api_client::datadog::configuration::Configuration;
use datadog_api_client::datadogV1::api::api_aws_integration::AWSIntegrationAPI;
use datadog_api_client::datadog;
use datadog_api_client::datadogV1::api_aws_integration::AWSIntegrationAPI;
use datadog_api_client::datadogV1::model::AWSAccount;
use std::collections::BTreeMap;

Expand All @@ -16,7 +16,7 @@ async fn main() {
.metrics_collection_enabled(false)
.resource_collection_enabled(true)
.role_name("DatadogAWSIntegrationRole".to_string());
let configuration = Configuration::new();
let configuration = datadog::Configuration::new();
let api = AWSIntegrationAPI::with_config(configuration);
let resp = api.create_aws_account(body).await;
if let Ok(value) = resp {
Expand Down
6 changes: 3 additions & 3 deletions examples/v1_aws-integration_create_aws_event_bridge_source.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Create an Amazon EventBridge source returns "OK" response
use datadog_api_client::datadog::configuration::Configuration;
use datadog_api_client::datadogV1::api::api_aws_integration::AWSIntegrationAPI;
use datadog_api_client::datadog;
use datadog_api_client::datadogV1::api_aws_integration::AWSIntegrationAPI;
use datadog_api_client::datadogV1::model::AWSEventBridgeCreateRequest;

#[tokio::main]
Expand All @@ -10,7 +10,7 @@ async fn main() {
.create_event_bus(true)
.event_generator_name("app-alerts".to_string())
.region("us-east-1".to_string());
let configuration = Configuration::new();
let configuration = datadog::Configuration::new();
let api = AWSIntegrationAPI::with_config(configuration);
let resp = api.create_aws_event_bridge_source(body).await;
if let Ok(value) = resp {
Expand Down
Loading

0 comments on commit aacc4cb

Please sign in to comment.