ansible-rs 1.1.0

A Rust wrapper library for Ansible command-line tools (Linux/Unix only)
Documentation
//! 异步 Ansible 配置管理
//!
//! 提供完全独立的异步 Ansible 配置查询和管理功能。

use crate::{AnsibleConfig, AnsibleError, ConfigFormat, PluginType};
use crate::command_config::CommandConfig;
use crate::async_support::{AsyncResult, AsyncExecute, IntoAsync, FromAsync};
use std::ffi::OsStr;
use std::fmt::Display;
use tokio::process::Command;

/// 异步 Ansible 配置管理工具
///
/// `AsyncAnsibleConfig` 提供与 [`AnsibleConfig`] 相同的功能,但所有操作都是异步的。
///
/// # Examples
///
/// ## 基本异步配置查询
///
/// ```rust,no_run
/// use ansible::{AsyncAnsibleConfig, ConfigFormat};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut config = AsyncAnsibleConfig::new();
///     config.set_format(ConfigFormat::Json);
///
///     // 异步获取配置列表
///     let config_list = config.list().await?;
///     println!("Configuration: {}", config_list);
///
///     // 异步导出配置
///     let config_dump = config.dump().await?;
///     println!("Config dump: {}", config_dump);
///
///     Ok(())
/// }
/// ```
///
/// ## 并发配置查询
///
/// ```rust,no_run
/// use ansible::{AsyncAnsibleConfig, PluginType};
/// use tokio::try_join;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut config1 = AsyncAnsibleConfig::new();
///     config1.set_plugin_type(PluginType::Callback);
///
///     let mut config2 = AsyncAnsibleConfig::new();
///     config2.set_plugin_type(PluginType::Connection);
///
///     // 并发查询不同插件类型的配置
///     let (callback_config, connection_config) = try_join!(
///         config1.list(),
///         config2.list()
///     )?;
///
///     println!("Callback plugins: {}", callback_config);
///     println!("Connection plugins: {}", connection_config);
///
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct AsyncAnsibleConfig {
    command: String,
    cfg: CommandConfig,
    config_file: Option<String>,
    plugin_type: Option<String>,
}

impl Default for AsyncAnsibleConfig {
    fn default() -> Self {
        Self {
            command: "ansible-config".to_string(),
            cfg: CommandConfig::default(),
            config_file: None,
            plugin_type: None,
        }
    }
}

impl AsyncAnsibleConfig {
    /// 创建新的 AsyncAnsibleConfig 实例
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置系统环境变量
    pub fn set_system_envs(&mut self) -> &mut Self {
        self.cfg.set_system_envs();
        self
    }

    /// 过滤环境变量
    pub fn filter_envs<T, S>(&mut self, iter: T) -> &mut Self
    where
        T: IntoIterator<Item = S>,
        S: AsRef<OsStr> + Display,
    {
        self.cfg.filter_envs(iter);
        self
    }

    /// 添加环境变量
    pub fn add_env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.cfg.add_env(key, value);
        self
    }

    /// 添加命令行参数
    pub fn arg<S: AsRef<OsStr> + Display>(&mut self, arg: S) -> &mut Self {
        self.cfg.arg(arg);
        self
    }

    /// 设置配置文件
    pub fn set_config_file(&mut self, config_file: impl Into<String>) -> &mut Self {
        self.config_file = Some(config_file.into());
        self
    }

    /// 设置输出格式
    pub fn set_format(&mut self, format: ConfigFormat) -> &mut Self {
        self.arg("--format").arg(format.to_string());
        self
    }

    /// 设置插件类型过滤器
    pub fn set_plugin_type(&mut self, plugin_type: PluginType) -> &mut Self {
        self.plugin_type = Some(plugin_type.to_string());
        self
    }

    /// 异步列出配置选项
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use ansible::AsyncAnsibleConfig;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let config = AsyncAnsibleConfig::new();
    ///     let config_list = config.list().await?;
    ///     println!("Configuration options: {}", config_list);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn list(&self) -> AsyncResult<String> {
        let mut args = vec!["list"];
        if let Some(ref plugin_type) = self.plugin_type {
            args.push("--type");
            args.push(plugin_type);
        }
        self.execute_config_command(&args).await
    }

    /// 异步导出当前配置
    pub async fn dump(&self) -> AsyncResult<String> {
        self.execute_config_command(&["dump"]).await
    }

    /// 异步查看配置文件
    pub async fn view(&self) -> AsyncResult<String> {
        self.execute_config_command(&["view"]).await
    }

    /// 异步初始化配置文件
    pub async fn init(&self) -> AsyncResult<String> {
        self.execute_config_command(&["init"]).await
    }

    /// 异步验证配置文件
    pub async fn validate(&self) -> AsyncResult<String> {
        self.execute_config_command(&["validate"]).await
    }

    /// 执行配置命令的内部方法
    async fn execute_config_command(&self, args: &[&str]) -> AsyncResult<String> {
        let mut cmd = Command::new(&self.command);
        cmd.envs(&self.cfg.envs);
        cmd.args(&self.cfg.args);
        cmd.args(args);
        
        if let Some(ref config_file) = self.config_file {
            cmd.arg("--config").arg(config_file);
        }

        let output = cmd.output().await?;
        
        if !output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
            return Err(AnsibleError::command_failed(
                "Ansible config command failed",
                output.status.code(),
                Some(stdout),
                Some(stderr),
            ));
        }

        let result = [output.stdout, "\n".as_bytes().to_vec(), output.stderr].concat();
        let s = String::from_utf8_lossy(&result);
        Ok(s.to_string())
    }
}

impl AsyncExecute for AsyncAnsibleConfig {
    async fn execute_async(&self) -> AsyncResult<String> {
        self.list().await
    }
}

impl IntoAsync<AsyncAnsibleConfig> for AnsibleConfig {
    fn into_async(self) -> AsyncAnsibleConfig {
        AsyncAnsibleConfig {
            command: self.command,
            cfg: self.cfg,
            config_file: self.config_file,
            plugin_type: self.plugin_type,
        }
    }
}

impl FromAsync<AsyncAnsibleConfig> for AnsibleConfig {
    fn from_async(async_config: AsyncAnsibleConfig) -> Self {
        AnsibleConfig {
            command: async_config.command,
            cfg: async_config.cfg,
            config_file: async_config.config_file,
            plugin_type: async_config.plugin_type,
        }
    }
}

impl std::fmt::Display for AsyncAnsibleConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.command)
    }
}