ansible-rs 1.1.0

A Rust wrapper library for Ansible command-line tools (Linux/Unix only)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Platform compatibility and system requirements validation.
//!
//! This module provides utilities for checking platform compatibility,
//! validating Ansible installation, and gathering system information.

use crate::errors::{AnsibleError, Result};
use std::process::Command;

/// Platform compatibility and system requirements validator.
///
/// The `PlatformValidator` provides static methods for checking platform
/// compatibility, validating Ansible installation, and verifying that all
/// required components are available.
///
/// # Examples
///
/// ## Basic Platform Check
///
/// ```rust,no_run
/// use ansible::PlatformValidator;
///
/// // Check if current platform is supported
/// PlatformValidator::check_platform()?;
///
/// // Check platform compatibility without panicking
/// if PlatformValidator::is_platform_supported() {
///     println!("Platform is supported");
/// } else {
///     println!("Platform not supported");
/// }
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Ansible Installation Check
///
/// ```rust,no_run
/// use ansible::PlatformValidator;
///
/// // Check if Ansible is installed
/// match PlatformValidator::check_ansible_installation() {
///     Ok(version) => println!("Ansible version: {}", version),
///     Err(e) => eprintln!("Ansible not found: {}", e),
/// }
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Component Availability
///
/// ```rust,no_run
/// use ansible::PlatformValidator;
///
/// // Check individual components
/// let components = [
///     ("ansible", PlatformValidator::check_ansible_installation as fn() -> Result<String, _>),
///     ("ansible-playbook", PlatformValidator::check_ansible_playbook as fn() -> Result<String, _>),
///     ("ansible-vault", PlatformValidator::check_ansible_vault as fn() -> Result<String, _>),
/// ];
///
/// for (name, check_fn) in &components {
///     match check_fn() {
///         Ok(_) => println!("✅ {} is available", name),
///         Err(_) => println!("❌ {} is not available", name),
///     }
/// }
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
pub struct PlatformValidator;

impl PlatformValidator {
    /// Check if the current platform is supported
    pub fn check_platform() -> Result<()> {
        #[cfg(not(any(
            target_os = "linux",
            target_os = "macos", 
            target_os = "freebsd",
            target_os = "openbsd",
            target_os = "netbsd"
        )))]
        {
            return Err(AnsibleError::unsupported_platform(format!(
                "ansible-rs only supports Unix-like systems. Current platform: {}",
                std::env::consts::OS
            )));
        }

        Ok(())
    }

    /// Check if Ansible is installed and accessible
    pub fn check_ansible_installation() -> Result<String> {
        Self::check_platform()?;

        let output = Command::new("ansible")
            .arg("--version")
            .output()
            .map_err(|e| {
                AnsibleError::command_not_found(format!(
                    "Ansible command not found. Please install Ansible first. Error: {}",
                    e
                ))
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AnsibleError::command_failed(
                "Failed to get Ansible version",
                output.status.code(),
                None,
                Some(stderr.to_string()),
            ));
        }

        let version_output = String::from_utf8_lossy(&output.stdout);
        Ok(version_output.to_string())
    }

    /// Check if ansible-playbook is available
    pub fn check_ansible_playbook() -> Result<String> {
        Self::check_platform()?;

        let output = Command::new("ansible-playbook")
            .arg("--version")
            .output()
            .map_err(|e| {
                AnsibleError::command_not_found(format!(
                    "ansible-playbook command not found. Please install Ansible first. Error: {}",
                    e
                ))
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AnsibleError::command_failed(
                "Failed to get ansible-playbook version",
                output.status.code(),
                None,
                Some(stderr.to_string()),
            ));
        }

        let version_output = String::from_utf8_lossy(&output.stdout);
        Ok(version_output.to_string())
    }

    /// Check if ansible-vault is available
    pub fn check_ansible_vault() -> Result<String> {
        Self::check_platform()?;

        let output = Command::new("ansible-vault")
            .arg("--help")
            .output()
            .map_err(|e| {
                AnsibleError::command_not_found(format!(
                    "ansible-vault command not found. Please install Ansible first. Error: {}",
                    e
                ))
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AnsibleError::command_failed(
                "Failed to check ansible-vault availability",
                output.status.code(),
                None,
                Some(stderr.to_string()),
            ));
        }

        Ok("ansible-vault is available".to_string())
    }

    /// Check if ansible-config is available
    pub fn check_ansible_config() -> Result<String> {
        Self::check_platform()?;

        let output = Command::new("ansible-config")
            .arg("--help")
            .output()
            .map_err(|e| {
                AnsibleError::command_not_found(format!(
                    "ansible-config command not found. Please install Ansible first. Error: {}",
                    e
                ))
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AnsibleError::command_failed(
                "Failed to check ansible-config availability",
                output.status.code(),
                None,
                Some(stderr.to_string()),
            ));
        }

        Ok("ansible-config is available".to_string())
    }

    /// Check if ansible-inventory is available
    pub fn check_ansible_inventory() -> Result<String> {
        Self::check_platform()?;

        let output = Command::new("ansible-inventory")
            .arg("--help")
            .output()
            .map_err(|e| {
                AnsibleError::command_not_found(format!(
                    "ansible-inventory command not found. Please install Ansible first. Error: {}",
                    e
                ))
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AnsibleError::command_failed(
                "Failed to check ansible-inventory availability",
                output.status.code(),
                None,
                Some(stderr.to_string()),
            ));
        }

        Ok("ansible-inventory is available".to_string())
    }

    /// Comprehensive system check
    pub fn check_all_requirements() -> Result<SystemInfo> {
        Self::check_platform()?;

        let ansible_version = Self::check_ansible_installation()?;
        let playbook_available = Self::check_ansible_playbook().is_ok();
        let vault_available = Self::check_ansible_vault().is_ok();
        let config_available = Self::check_ansible_config().is_ok();
        let inventory_available = Self::check_ansible_inventory().is_ok();

        Ok(SystemInfo {
            platform: std::env::consts::OS.to_string(),
            architecture: std::env::consts::ARCH.to_string(),
            ansible_version,
            playbook_available,
            vault_available,
            config_available,
            inventory_available,
        })
    }

    /// Get minimum required Ansible version
    pub fn minimum_ansible_version() -> &'static str {
        "2.9"
    }

    /// Get supported platforms
    pub fn supported_platforms() -> Vec<&'static str> {
        vec![
            "linux",
            "macos",
            "freebsd", 
            "openbsd",
            "netbsd",
        ]
    }

    /// Check if current platform is supported
    pub fn is_platform_supported() -> bool {
        Self::supported_platforms().contains(&std::env::consts::OS)
    }
}

/// Comprehensive system information and feature availability.
///
/// The `SystemInfo` struct provides detailed information about the current
/// system, including platform details, Ansible version, and availability
/// of various Ansible components.
///
/// # Examples
///
/// ## Getting System Information
///
/// ```rust,no_run
/// use ansible::get_system_info;
///
/// let system_info = get_system_info()?;
/// println!("{}", system_info);
///
/// if system_info.is_fully_supported() {
///     println!("All Ansible features are available!");
/// } else {
///     println!("Missing features: {:?}", system_info.missing_features());
/// }
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Feature Checking
///
/// ```rust,no_run
/// use ansible::get_system_info;
///
/// let system_info = get_system_info()?;
///
/// for (feature, available) in system_info.feature_summary() {
///     let status = if available { "✅" } else { "❌" };
///     println!("{} {}", status, feature);
/// }
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
#[derive(Debug, Clone)]
pub struct SystemInfo {
    /// Operating system name (e.g., "linux", "macos")
    pub platform: String,

    /// System architecture (e.g., "x86_64", "aarch64")
    pub architecture: String,

    /// Ansible version string (empty if not installed)
    pub ansible_version: String,

    /// Whether ansible-playbook is available
    pub playbook_available: bool,

    /// Whether ansible-vault is available
    pub vault_available: bool,

    /// Whether ansible-config is available
    pub config_available: bool,

    /// Whether ansible-inventory is available
    pub inventory_available: bool,
}

impl SystemInfo {
    /// Check if all required components are available
    pub fn is_fully_supported(&self) -> bool {
        self.playbook_available 
            && self.vault_available 
            && self.config_available 
            && self.inventory_available
    }

    /// Get a summary of available features
    pub fn feature_summary(&self) -> Vec<(String, bool)> {
        vec![
            ("ansible".to_string(), !self.ansible_version.is_empty()),
            ("ansible-playbook".to_string(), self.playbook_available),
            ("ansible-vault".to_string(), self.vault_available),
            ("ansible-config".to_string(), self.config_available),
            ("ansible-inventory".to_string(), self.inventory_available),
        ]
    }

    /// Get missing features
    pub fn missing_features(&self) -> Vec<String> {
        let mut missing = Vec::new();
        
        if self.ansible_version.is_empty() {
            missing.push("ansible".to_string());
        }
        if !self.playbook_available {
            missing.push("ansible-playbook".to_string());
        }
        if !self.vault_available {
            missing.push("ansible-vault".to_string());
        }
        if !self.config_available {
            missing.push("ansible-config".to_string());
        }
        if !self.inventory_available {
            missing.push("ansible-inventory".to_string());
        }
        
        missing
    }
}

impl std::fmt::Display for SystemInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "System Information:")?;
        writeln!(f, "  Platform: {} ({})", self.platform, self.architecture)?;
        writeln!(f, "  Ansible Version: {}", self.ansible_version.trim())?;
        writeln!(f, "  Available Features:")?;
        
        for (feature, available) in self.feature_summary() {
            let status = if available { "" } else { "" };
            writeln!(f, "    {} {}", status, feature)?;
        }
        
        if !self.is_fully_supported() {
            writeln!(f, "  Missing Features: {:?}", self.missing_features())?;
        }
        
        Ok(())
    }
}

/// Convenience function to validate system requirements at startup
pub fn validate_system() -> Result<()> {
    PlatformValidator::check_platform()?;
    PlatformValidator::check_ansible_installation()?;
    Ok(())
}

/// Convenience function to get system information
pub fn get_system_info() -> Result<SystemInfo> {
    PlatformValidator::check_all_requirements()
}