Skip to main content

openstack_cli_compute/v2/quota_set/
show.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Show QuotaSet command
19//!
20//! Wraps invoking of the `v2.1/os-quota-sets/{id}` with `GET` method
21
22use clap::Args;
23use eyre::OptionExt;
24use tracing::info;
25
26use openstack_cli_core::cli::CliArgs;
27use openstack_cli_core::error::OpenStackCliError;
28use openstack_cli_core::output::OutputProcessor;
29use openstack_sdk::AsyncOpenStack;
30
31use openstack_sdk::api::QueryAsync;
32use openstack_sdk::api::compute::v2::quota_set::get;
33use openstack_sdk::api::find_by_name;
34use openstack_sdk::api::identity::v3::user::find as find_user;
35use openstack_types::compute::v2::quota_set::response;
36use tracing::warn;
37
38/// Show the quota for a project or a project and a user.
39///
40/// Normal response codes: 200
41///
42/// Error response codes: badRequest(400), unauthorized(401), forbidden(403)
43#[derive(Args)]
44#[command(about = "Show A Quota")]
45pub struct QuotaSetCommand {
46    /// Request Query parameters
47    #[command(flatten)]
48    query: QueryParameters,
49
50    /// Path parameters
51    #[command(flatten)]
52    path: PathParameters,
53}
54
55/// Query parameters
56#[derive(Args)]
57struct QueryParameters {
58    /// User resource for which the operation should be performed.
59    #[command(flatten)]
60    user: UserInput,
61}
62
63/// User input select group
64#[derive(Args)]
65#[group(required = false, multiple = false)]
66struct UserInput {
67    /// User Name.
68    #[arg(long, help_heading = "Path parameters", value_name = "USER_NAME")]
69    user_name: Option<String>,
70    /// User ID.
71    #[arg(long, help_heading = "Path parameters", value_name = "USER_ID")]
72    user_id: Option<String>,
73    /// Current authenticated user.
74    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
75    current_user: bool,
76}
77
78/// Path parameters
79#[derive(Args)]
80struct PathParameters {
81    /// id parameter for /v2.1/os-quota-sets/{id} API
82    #[arg(
83        help_heading = "Path parameters",
84        id = "path_param_id",
85        value_name = "ID"
86    )]
87    id: String,
88}
89
90impl QuotaSetCommand {
91    /// Perform command action
92    pub async fn take_action<C: CliArgs>(
93        &self,
94        parsed_args: &C,
95        client: &mut AsyncOpenStack,
96    ) -> Result<(), OpenStackCliError> {
97        info!("Show QuotaSet");
98
99        let op = OutputProcessor::from_args(parsed_args, Some("compute.quota_set"), Some("show"));
100        op.validate_args(parsed_args)?;
101
102        let mut ep_builder = get::Request::builder();
103
104        ep_builder.id(&self.path.id);
105        // Set query parameters
106        if let Some(id) = &self.query.user.user_id {
107            // user_id is passed. No need to lookup
108            ep_builder.user_id(id);
109        } else if let Some(name) = &self.query.user.user_name {
110            // user_name is passed. Need to lookup resource
111            let mut sub_find_builder = find_user::Request::builder();
112            warn!(
113                "Querying user by name (because of `--user-name` parameter passed) may not be definite. This may fail in which case parameter `--user-id` should be used instead."
114            );
115
116            sub_find_builder.id(name);
117            let find_ep = sub_find_builder
118                .build()
119                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
120            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
121            // Try to extract resource id
122            match find_data.get("id") {
123                Some(val) => match val.as_str() {
124                    Some(id_str) => {
125                        ep_builder.user_id(id_str.to_owned());
126                    }
127                    None => {
128                        return Err(OpenStackCliError::ResourceAttributeNotString(
129                            serde_json::to_string(&val)?,
130                        ));
131                    }
132                },
133                None => {
134                    return Err(OpenStackCliError::ResourceAttributeMissing(
135                        "id".to_string(),
136                    ));
137                }
138            };
139        } else if self.query.user.current_user {
140            ep_builder.user_id(
141                client
142                    .get_auth_info()
143                    .ok_or_eyre("Cannot determine current authentication information")?
144                    .token
145                    .user
146                    .id,
147            );
148        }
149
150        let ep = ep_builder
151            .build()
152            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
153
154        let data: serde_json::Value = ep.query_async(client).await?;
155
156        op.output_single::<response::get_20::QuotaSetResponse>(data.clone())
157            .or_else(|_| op.output_single::<response::get_236::QuotaSetResponse>(data.clone()))
158            .or_else(|_| op.output_single::<response::get_257::QuotaSetResponse>(data.clone()))?;
159        // Show command specific hints
160        op.show_command_hint()?;
161        Ok(())
162    }
163}