Skip to main content

terraform_wrapper/commands/
modules.rs

1use crate::Terraform;
2use crate::command::TerraformCommand;
3use crate::error::Result;
4use crate::exec::{self, CommandOutput};
5
6/// Command for listing declared modules in a configuration.
7///
8/// Lists all modules declared in the current working directory.
9/// Supports `-json` for machine-readable output.
10///
11/// Requires Terraform v1.10.0 or later.
12///
13/// ```no_run
14/// # async fn example() -> terraform_wrapper::error::Result<()> {
15/// use terraform_wrapper::{Terraform, TerraformCommand};
16/// use terraform_wrapper::commands::modules::ModulesCommand;
17///
18/// let tf = Terraform::builder().working_dir("/tmp/infra").build()?;
19/// let output = ModulesCommand::new()
20///     .json()
21///     .execute(&tf)
22///     .await?;
23/// # Ok(())
24/// # }
25/// ```
26#[derive(Debug, Clone, Default)]
27pub struct ModulesCommand {
28    json: bool,
29    raw_args: Vec<String>,
30}
31
32impl ModulesCommand {
33    /// Create a new modules command with default options.
34    #[must_use]
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// Enable machine-readable JSON output (`-json`).
40    #[must_use]
41    pub fn json(mut self) -> Self {
42        self.json = true;
43        self
44    }
45
46    /// Add a raw argument (escape hatch for unsupported options).
47    #[must_use]
48    pub fn arg(mut self, arg: impl Into<String>) -> Self {
49        self.raw_args.push(arg.into());
50        self
51    }
52}
53
54impl TerraformCommand for ModulesCommand {
55    type Output = CommandOutput;
56
57    fn args(&self) -> Vec<String> {
58        let mut args = vec!["modules".to_string()];
59        if self.json {
60            args.push("-json".to_string());
61        }
62        args.extend(self.raw_args.clone());
63        args
64    }
65
66    async fn execute(&self, tf: &Terraform) -> Result<CommandOutput> {
67        exec::run_terraform(tf, self.args()).await
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn default_args() {
77        let cmd = ModulesCommand::new();
78        assert_eq!(cmd.args(), vec!["modules"]);
79    }
80
81    #[test]
82    fn with_json() {
83        let cmd = ModulesCommand::new().json();
84        assert_eq!(cmd.args(), vec!["modules", "-json"]);
85    }
86}