use crate::error::{AppError, AppResult};
use crate::io::write_subtitle_to_stdout;
use clap::CommandFactory;
use std::process::ExitCode;
const BIN_NAME: &str = env!("CARGO_PKG_NAME");
pub async fn run_completions(shell: clap_complete::Shell) -> AppResult<ExitCode> {
let mut command = crate::cli::Cli::command();
let mut buffer: Vec<u8> = Vec::new();
clap_complete::generate(shell, &mut command, BIN_NAME, &mut buffer);
write_subtitle_to_stdout(&buffer).await?;
Ok(ExitCode::SUCCESS)
}
pub async fn run_man() -> AppResult<ExitCode> {
let command = crate::cli::Cli::command();
let mut buffer: Vec<u8> = Vec::new();
clap_mangen::Man::new(command)
.render(&mut buffer)
.map_err(AppError::Io)?;
write_subtitle_to_stdout(&buffer).await?;
Ok(ExitCode::SUCCESS)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_shell_renders_a_script_naming_the_binary() {
for shell in [
clap_complete::Shell::Bash,
clap_complete::Shell::Zsh,
clap_complete::Shell::Fish,
clap_complete::Shell::Elvish,
clap_complete::Shell::PowerShell,
] {
let mut command = crate::cli::Cli::command();
let mut buffer: Vec<u8> = Vec::new();
clap_complete::generate(shell, &mut command, BIN_NAME, &mut buffer);
let script = String::from_utf8(buffer).expect("completion script is not UTF-8");
assert!(!script.is_empty(), "{shell} rendered an empty script");
assert!(
script.contains(BIN_NAME),
"{shell} script does not name the binary"
);
}
}
#[test]
fn man_page_renders_and_names_the_binary() {
let command = crate::cli::Cli::command();
let mut buffer: Vec<u8> = Vec::new();
clap_mangen::Man::new(command)
.render(&mut buffer)
.expect("man page failed to render");
let page = String::from_utf8(buffer).expect("man page is not UTF-8");
assert!(!page.is_empty(), "man page is empty");
assert!(page.contains(BIN_NAME), "man page does not name the binary");
}
#[test]
fn completion_script_carries_our_own_flags() {
let mut command = crate::cli::Cli::command();
let mut buffer: Vec<u8> = Vec::new();
clap_complete::generate(
clap_complete::Shell::Bash,
&mut command,
BIN_NAME,
&mut buffer,
);
let script = String::from_utf8(buffer).expect("completion script is not UTF-8");
assert!(
script.contains("--print-schema"),
"completion script does not carry --print-schema"
);
}
}