Skip to main content

didbot/
main.rs

1//! `didbot` — the one command a person types, and nothing more than a
2//! router.
3//!
4//! `didbot <verb> …` finds the binary that answers `<verb>` and replaces
5//! itself with it, handing over the rest of the command line. The
6//! first-party verbs are in [`verbs::FIRST_PARTY`], each naming its binary,
7//! so a verb whose binary is not installed is answered with what to install.
8//! Any other word is `didbot-<word>` on `PATH`, which is how someone adds a
9//! verb without touching this repository.
10//!
11//! The dispatcher passes argv and nothing else. It adds nothing to the
12//! environment and removes every variable in [`didbot_cli::env::CREDENTIALS`]
13//! before handing off: a verb reached this way authenticates for itself, and
14//! a program reachable by a typo on `didbot-` inherits no credential from the
15//! shell that ran it.
16//!
17//! `didbot --list` scans `PATH` for `didbot-*`, asks each for `--version` and
18//! prints what it found. Every binary is versioned on its own, so a mix of
19//! versions shows up here and fails nowhere.
20
21#![forbid(unsafe_code)]
22
23mod path;
24mod run;
25mod verbs;
26
27use std::ffi::OsString;
28use std::process::ExitCode;
29
30use clap::{CommandFactory, Parser, Subcommand};
31use didbot_cli::{finish, FirstPartyVerb, Refusal};
32
33use crate::verbs::FIRST_PARTY;
34
35/// The spelling every refusal from this binary is prefixed with.
36const PROGRAM: &str = "didbot";
37
38#[derive(Parser)]
39#[command(
40    name = PROGRAM,
41    version,
42    about = "The didbot commands, one entry point",
43    long_about = "Runs `didbot-<verb>` from PATH with the rest of the command line, and \
44                  nothing else: no credential from this shell reaches the verb.",
45    after_help = verbs::help_table(),
46    allow_external_subcommands = true,
47    disable_help_subcommand = true,
48    arg_required_else_help = true,
49    args_conflicts_with_subcommands = true
50)]
51struct Cli {
52    /// Print every didbot-* binary on PATH, with its version
53    #[arg(long)]
54    list: bool,
55    #[command(subcommand)]
56    verb: Option<Verb>,
57}
58
59#[derive(Subcommand)]
60enum Verb {
61    #[command(external_subcommand)]
62    External(Vec<OsString>),
63}
64
65fn main() -> ExitCode {
66    let cli: Cli = didbot_cli::parse();
67    if cli.list {
68        return finish(PROGRAM, list());
69    }
70    let Some(Verb::External(words)) = cli.verb else {
71        // Unreachable through clap: `arg_required_else_help` answers the
72        // empty command line, and `--list` returned above.
73        return finish(
74            PROGRAM,
75            Err(Refusal::usage("a verb is required; see --help")),
76        );
77    };
78    let (verb, rest) = words
79        .split_first()
80        .expect("an external subcommand has a name");
81    let verb = verb.to_string_lossy();
82
83    // `didbot help <verb>` is `didbot <verb> --help`, resolved the same way.
84    if verb == "help" {
85        return match rest.split_first() {
86            None => {
87                let _ = Cli::command().print_help();
88                ExitCode::SUCCESS
89            }
90            Some((asked, _)) => {
91                let asked = asked.to_string_lossy();
92                finish(PROGRAM, dispatch(&asked, &[OsString::from("--help")]))
93            }
94        };
95    }
96    finish(PROGRAM, dispatch(&verb, rest))
97}
98
99/// Finds the binary for `verb` and runs it with `argv`.
100///
101/// Only returns when the binary is not there, or could not be started: on
102/// success the verb's process replaces this one.
103fn dispatch(verb: &str, argv: &[OsString]) -> Result<(), Refusal> {
104    match FirstPartyVerb::lookup(FIRST_PARTY, verb) {
105        Some(row) => {
106            let binary = path::find(row.binary).ok_or_else(|| {
107                Refusal::failed(format!(
108                    "`{verb}` runs {}, which is not on PATH; install {}",
109                    row.binary, row.package
110                ))
111            })?;
112            let leading: Vec<OsString> = row.argv.iter().map(OsString::from).collect();
113            run::exec(&binary, leading.iter().chain(argv))
114        }
115        None => {
116            let name = format!("didbot-{verb}");
117            let binary = path::find(&name).ok_or_else(|| {
118                Refusal::usage(format!(
119                    "unknown command `{verb}`; `didbot --list` shows what is installed"
120                ))
121            })?;
122            run::exec(&binary, argv)
123        }
124    }
125}
126
127/// `--list`: this binary, then every `didbot-*` on `PATH` with what it says
128/// to `--version`, then the first-party binaries that are not installed.
129fn list() -> Result<(), Refusal> {
130    let own = std::env::current_exe()
131        .map_err(|error| Refusal::failed(format!("cannot tell where this binary is: {error}")))?;
132    let mut rows = vec![(
133        PROGRAM.to_owned(),
134        env!("CARGO_PKG_VERSION").to_owned(),
135        own.display().to_string(),
136    )];
137    for (name, binary) in path::installed() {
138        let version = run::version_of(&binary)
139            .and_then(|line| line.split_whitespace().nth(1).map(str::to_owned))
140            .unwrap_or_else(|| "?".to_owned());
141        rows.push((name, version, binary.display().to_string()));
142    }
143    let name_width = rows.iter().map(|row| row.0.len()).max().unwrap_or(0);
144    let version_width = rows.iter().map(|row| row.1.len()).max().unwrap_or(0);
145    for (name, version, location) in &rows {
146        println!("{name:<name_width$}  {version:<version_width$}  {location}");
147    }
148
149    let mut missing: Vec<&str> = FIRST_PARTY
150        .iter()
151        .map(|row| row.binary)
152        .filter(|binary| !rows.iter().any(|row| row.0 == *binary))
153        .collect();
154    missing.dedup();
155    for binary in missing {
156        let verbs: Vec<&str> = FIRST_PARTY
157            .iter()
158            .filter(|row| row.binary == binary)
159            .map(|row| row.verb)
160            .collect();
161        println!("{binary}: not installed ({})", verbs.join(", "));
162    }
163    Ok(())
164}
165
166#[cfg(test)]
167mod reference {
168    use clap::CommandFactory;
169
170    /// The README's CLI reference holds what `--help` prints.
171    #[test]
172    fn cli_reference() {
173        didbot_cli::reference::check_command("didbot", super::Cli::command());
174    }
175}