openstack-cli-image 0.13.8

OpenStack CLI Image commands
Documentation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
// WARNING: This file is automatically generated from OpenAPI schema using
// `openstack-codegenerator`.

//! Create Location command
//!
//! Wraps invoking of the `v2/images/{image_id}/locations` with `POST` method

use clap::Args;
use eyre::{OptionExt, WrapErr};
use tracing::info;

use openstack_cli_core::cli::CliArgs;
use openstack_cli_core::error::OpenStackCliError;
use openstack_cli_core::output::OutputProcessor;
use openstack_sdk::AsyncOpenStack;

use openstack_cli_core::common::parse_key_val;
use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::image::v2::image::location::create;
use openstack_types::image::v2::image::location::response;
use serde_json::Value;

/// Add location to an image which is in `queued` state. Accepts location url,
/// validation_data in JSON body.
///
/// Adding a location to an image is only allowed for the owner or a user with
/// the service role. If these conditions are not met, a 403 (Forbidden) will
/// be returned.
///
/// Attempting to add a location path to an image that is not in `queued` state
/// will result in a 409 (Conflict) response code
///
/// Attempting to provide incorrect hash value in validation data(in the case
/// of http store) to the image will result in a 400 (Bad Request) response
/// code.
///
/// Normal response codes: 200
///
/// Error response codes: 400, 403, 404, 409
#[derive(Args)]
#[command(about = "Add Location")]
pub struct LocationCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

    /// Path parameters
    #[command(flatten)]
    path: PathParameters,

    #[arg(help_heading = "Body parameters", long, value_name="key=value", value_parser=parse_key_val::<String, Value>)]
    metadata: Option<Vec<(String, Value)>>,

    /// The URL of the new location to be added in the image.
    #[arg(help_heading = "Body parameters", long)]
    url: String,

    /// An image metadata in key:value pairs containing values of
    /// `os_hash_value` and `os_hash_algo` to be added to the image. If
    /// `do_secure_hash` is not passed then it is the responsibility of the
    /// consumer of location add API to provide the correct values in
    /// `validation_data`’
    #[command(flatten)]
    validation_data: Option<ValidationData>,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {}

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// image_id parameter for /v2/images/{image_id}/locations API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_image_id",
        value_name = "IMAGE_ID"
    )]
    image_id: String,
}
/// ValidationData Body data
#[derive(Args, Clone)]
struct ValidationData {
    #[arg(help_heading = "Body parameters", long)]
    checksum: Option<String>,

    #[arg(help_heading = "Body parameters", long)]
    os_hash_algo: String,

    #[arg(help_heading = "Body parameters", long)]
    os_hash_value: String,
}

impl LocationCommand {
    /// Perform command action
    pub async fn take_action<C: CliArgs>(
        &self,
        parsed_args: &C,
        client: &mut AsyncOpenStack,
    ) -> Result<(), OpenStackCliError> {
        info!("Create Location");

        let op =
            OutputProcessor::from_args(parsed_args, Some("image.image/location"), Some("create"));
        op.validate_args(parsed_args)?;

        let mut ep_builder = create::Request::builder();

        ep_builder.image_id(&self.path.image_id);

        // Set body parameters
        // Set Request.metadata data
        if let Some(arg) = &self.metadata {
            ep_builder.metadata(arg.iter().cloned());
        }

        // Set Request.url data
        ep_builder.url(&self.url);

        // Set Request.validation_data data
        if let Some(args) = &self.validation_data {
            let mut validation_data_builder = create::ValidationDataBuilder::default();
            if let Some(val) = &args.checksum {
                validation_data_builder.checksum(val);
            }

            validation_data_builder.os_hash_algo(&args.os_hash_algo);

            validation_data_builder.os_hash_value(&args.os_hash_value);

            ep_builder.validation_data(
                validation_data_builder
                    .build()
                    .wrap_err("error preparing the request data")?,
            );
        }

        let ep = ep_builder
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;

        let data: serde_json::Value = ep.query_async(client).await?;

        op.output_single::<response::create::LocationResponse>(data.clone())?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}