asimov_cli/commands/
help_cmd.rs

1// This is free and unencumbered software released into the public domain.
2
3use clientele::SysexitsError::{self, *};
4use std::process::Stdio;
5
6use crate::{Result, shared::locate_subcommand};
7
8pub struct HelpCmdResult {
9    /// Whether the command was successful or not.
10    pub success: bool,
11
12    /// Return code of the executed command.
13    pub code: SysexitsError,
14
15    /// If `success` is `true`, this field contains stdout,
16    /// otherwise it contains stderr.
17    pub output: Vec<u8>,
18}
19
20/// Executes `help` command for the given subcommand.
21pub struct HelpCmd {
22    pub is_debug: bool,
23}
24
25impl HelpCmd {
26    pub fn execute(&self, cmd: &str, args: &[String]) -> Result<HelpCmdResult> {
27        // Locate the given subcommand:
28        let cmd = locate_subcommand(cmd)?;
29
30        // Execute the `--help` command:
31        let output = std::process::Command::new(&cmd.path)
32            .args([&[String::from("--help")], args].concat())
33            .stdin(Stdio::inherit())
34            .stdout(Stdio::piped())
35            .stderr(Stdio::piped())
36            .output();
37
38        match output {
39            Err(error) => {
40                if self.is_debug {
41                    eprintln!("asimov: {}", error);
42                }
43                Err(EX_SOFTWARE)
44            },
45            Ok(output) => match output.status.code() {
46                Some(code) if code == EX_OK.as_i32() => Ok(HelpCmdResult {
47                    success: true,
48                    code: EX_OK,
49                    output: output.stdout,
50                }),
51                _ => Ok(HelpCmdResult {
52                    success: false,
53                    code: output
54                        .status
55                        .code()
56                        .and_then(|code| SysexitsError::try_from(code).ok())
57                        .unwrap_or(EX_SOFTWARE),
58                    output: output.stderr,
59                }),
60            },
61        }
62    }
63}