Skip to main content

terraform_wrapper/commands/
version.rs

1use crate::Terraform;
2use crate::command::TerraformCommand;
3use crate::error::Result;
4use crate::exec;
5
6#[cfg(feature = "json")]
7use crate::types::version::VersionInfo;
8
9/// Command for retrieving Terraform version information.
10///
11/// By default, requests JSON output for programmatic parsing.
12///
13/// ```no_run
14/// # async fn example() -> terraform_wrapper::error::Result<()> {
15/// use terraform_wrapper::{Terraform, TerraformCommand};
16/// use terraform_wrapper::commands::version::VersionCommand;
17///
18/// let tf = Terraform::builder().build()?;
19/// let info = VersionCommand::new().execute(&tf).await?;
20/// # Ok(())
21/// # }
22/// ```
23#[derive(Debug, Clone)]
24pub struct VersionCommand {
25    json: bool,
26}
27
28impl Default for VersionCommand {
29    fn default() -> Self {
30        Self { json: true }
31    }
32}
33
34impl VersionCommand {
35    /// Create a new version command (JSON output enabled by default).
36    #[must_use]
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// Disable JSON output.
42    #[must_use]
43    pub fn no_json(mut self) -> Self {
44        self.json = false;
45        self
46    }
47}
48
49#[cfg(feature = "json")]
50impl TerraformCommand for VersionCommand {
51    type Output = VersionInfo;
52
53    fn args(&self) -> Vec<String> {
54        let mut args = vec!["version".to_string()];
55        if self.json {
56            args.push("-json".to_string());
57        }
58        args
59    }
60
61    async fn execute(&self, tf: &Terraform) -> Result<VersionInfo> {
62        let output = exec::run_terraform(tf, self.args()).await?;
63        serde_json::from_str(&output.stdout).map_err(|e| crate::error::Error::ParseError {
64            message: format!("failed to parse version json: {e}"),
65        })
66    }
67}
68
69#[cfg(not(feature = "json"))]
70impl TerraformCommand for VersionCommand {
71    type Output = exec::CommandOutput;
72
73    fn args(&self) -> Vec<String> {
74        let mut args = vec!["version".to_string()];
75        if self.json {
76            args.push("-json".to_string());
77        }
78        args
79    }
80
81    async fn execute(&self, tf: &Terraform) -> Result<exec::CommandOutput> {
82        exec::run_terraform(tf, self.args()).await
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn default_args_include_json() {
92        let cmd = VersionCommand::new();
93        assert_eq!(cmd.args(), vec!["version", "-json"]);
94    }
95
96    #[test]
97    fn no_json_args() {
98        let cmd = VersionCommand::new().no_json();
99        assert_eq!(cmd.args(), vec!["version"]);
100    }
101}