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