Skip to content

Commit

Permalink
feat: added support for --generate-man command (#85)
Browse files Browse the repository at this point in the history
  • Loading branch information
fujiapple852 committed Apr 10, 2024
1 parent e2e109b commit cb918c7
Show file tree
Hide file tree
Showing 11 changed files with 387 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ pub enum TrippyAction {
PrintConfigTemplate,
/// Generate shell completion and exit.
PrintShellCompletions(Shell),
/// Generate a man page and exit.
PrintManPage,
}

impl TrippyAction {
Expand All @@ -266,6 +268,8 @@ impl TrippyAction {
Self::PrintConfigTemplate
} else if let Some(shell) = args.generate {
Self::PrintShellCompletions(shell)
} else if args.generate_man {
Self::PrintManPage
} else {
Self::Trippy(TrippyConfig::from(args, platform)?)
})
Expand Down Expand Up @@ -1609,6 +1613,7 @@ mod tests {
#[test_case("trip --generate zsh", Ok(TrippyAction::PrintShellCompletions(Shell::Zsh)); "generate zsh shell completions")]
#[test_case("trip --generate bash", Ok(TrippyAction::PrintShellCompletions(Shell::Bash)); "generate bash shell completions")]
#[test_case("trip --generate foo", Err(anyhow!("error: one of the values isn't valid for an argument")); "generate invalid shell completions")]
#[test_case("trip --generate-man", Ok(TrippyAction::PrintManPage); "generate man page")]
fn test_action(cmd: &str, expected: anyhow::Result<TrippyAction>) {
compare(parse_action(cmd), expected);
}
Expand Down
6 changes: 5 additions & 1 deletion src/config/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use clap_complete::Shell;
#[command(name = "trip", author, version, about, long_about = None, arg_required_else_help(true), styles=Styles::styled())]
pub struct Args {
/// A space delimited list of hostnames and IPs to trace
#[arg(required_unless_present_any(["print_tui_theme_items", "print_tui_binding_commands", "print_config_template", "generate"]))]
#[arg(required_unless_present_any(["print_tui_theme_items", "print_tui_binding_commands", "print_config_template", "generate", "generate_man"]))]
pub targets: Vec<String>,

/// Config file
Expand Down Expand Up @@ -240,6 +240,10 @@ pub struct Args {
#[arg(long)]
pub generate: Option<Shell>,

/// Generate ROFF man page
#[arg(long)]
pub generate_man: bool,

/// Print a template toml config file and exit
#[arg(long)]
pub print_config_template: bool,
Expand Down
14 changes: 14 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ fn main() -> anyhow::Result<()> {
TrippyAction::PrintTuiThemeItems => print_tui_theme_items(),
TrippyAction::PrintTuiBindingCommands => print_tui_binding_commands(),
TrippyAction::PrintConfigTemplate => print_config_template(),
TrippyAction::PrintManPage => print_man_page()?,
TrippyAction::PrintShellCompletions(shell) => print_shell_completions(shell)?,
}
Ok(())
Expand Down Expand Up @@ -102,6 +103,11 @@ fn print_shell_completions(shell: Shell) -> anyhow::Result<()> {
process::exit(0);
}

fn print_man_page() -> anyhow::Result<()> {
println!("{}", man_page()?);
process::exit(0);
}

/// Start the DNS resolver.
fn start_dns_resolver(cfg: &TrippyConfig) -> anyhow::Result<DnsResolver> {
Ok(DnsResolver::start(trippy::dns::Config::new(
Expand Down Expand Up @@ -467,6 +473,13 @@ fn shell_completions(shell: Shell) -> anyhow::Result<String> {
Ok(String::from_utf8(buffer)?)
}

fn man_page() -> anyhow::Result<String> {
let cmd = Args::command();
let mut buffer: Vec<u8> = vec![];
clap_mangen::Man::new(cmd).render(&mut buffer)?;
Ok(String::from_utf8(buffer)?)
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -479,6 +492,7 @@ mod tests {
#[test_case(include_str!("../test_resources/config/completions_fish.txt"), &shell_completions(Shell::Fish).unwrap(); "generate fish shell completions")]
#[test_case(include_str!("../test_resources/config/completions_powershell.txt"), &shell_completions(Shell::PowerShell).unwrap(); "generate powershell shell completions")]
#[test_case(include_str!("../test_resources/config/completions_zsh.txt"), &shell_completions(Shell::Zsh).unwrap(); "generate zsh shell completions")]
#[test_case(include_str!("../test_resources/config/trip.1"), &man_page().unwrap(); "generate man page")]
fn test_output(expected: &str, actual: &str) {
if remove_whitespace(actual.to_string()) != remove_whitespace(expected.to_string()) {
pretty_assertions::assert_eq!(actual, expected);
Expand Down
2 changes: 1 addition & 1 deletion test_resources/config/completions_bash.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ _trip() {

case "${cmd}" in
trip)
opts="-c -m -u -p -F -4 -6 -P -S -A -I -i -T -g -R -U -f -t -Q -e -r -y -z -a -M -s -C -G -v -h -V --config-file --mode --unprivileged --protocol --udp --tcp --icmp --addr-family --ipv4 --ipv6 --target-port --source-port --source-address --interface --min-round-duration --max-round-duration --grace-duration --initial-sequence --multipath-strategy --max-inflight --first-ttl --max-ttl --packet-size --payload-pattern --tos --icmp-extensions --read-timeout --dns-resolve-method --dns-resolve-all --dns-timeout --dns-lookup-as-info --tui-address-mode --tui-as-mode --tui-custom-columns --tui-icmp-extension-mode --tui-geoip-mode --tui-max-addrs --tui-max-samples --tui-max-flows --tui-preserve-screen --tui-refresh-rate --tui-privacy-max-ttl --tui-theme-colors --print-tui-theme-items --tui-key-bindings --print-tui-binding-commands --report-cycles --geoip-mmdb-file --generate --print-config-template --log-format --log-filter --log-span-events --verbose --help --version [TARGETS]..."
opts="-c -m -u -p -F -4 -6 -P -S -A -I -i -T -g -R -U -f -t -Q -e -r -y -z -a -M -s -C -G -v -h -V --config-file --mode --unprivileged --protocol --udp --tcp --icmp --addr-family --ipv4 --ipv6 --target-port --source-port --source-address --interface --min-round-duration --max-round-duration --grace-duration --initial-sequence --multipath-strategy --max-inflight --first-ttl --max-ttl --packet-size --payload-pattern --tos --icmp-extensions --read-timeout --dns-resolve-method --dns-resolve-all --dns-timeout --dns-lookup-as-info --tui-address-mode --tui-as-mode --tui-custom-columns --tui-icmp-extension-mode --tui-geoip-mode --tui-max-addrs --tui-max-samples --tui-max-flows --tui-preserve-screen --tui-refresh-rate --tui-privacy-max-ttl --tui-theme-colors --print-tui-theme-items --tui-key-bindings --print-tui-binding-commands --report-cycles --geoip-mmdb-file --generate --generate-man --print-config-template --log-format --log-filter --log-span-events --verbose --help --version [TARGETS]..."
if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
Expand Down
1 change: 1 addition & 0 deletions test_resources/config/completions_elvish.txt
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ set edit:completion:arg-completer[trip] = {|@words|
cand --tui-preserve-screen 'Preserve the screen on exit [default: false]'
cand --print-tui-theme-items 'Print all TUI theme items and exit'
cand --print-tui-binding-commands 'Print all TUI commands that can be bound and exit'
cand --generate-man 'Generate ROFF man page'
cand --print-config-template 'Print a template toml config file and exit'
cand -v 'Enable verbose debug logging'
cand --verbose 'Enable verbose debug logging'
Expand Down
1 change: 1 addition & 0 deletions test_resources/config/completions_fish.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ complete -c trip -s z -l dns-lookup-as-info -d 'Lookup autonomous system (AS) in
complete -c trip -l tui-preserve-screen -d 'Preserve the screen on exit [default: false]'
complete -c trip -l print-tui-theme-items -d 'Print all TUI theme items and exit'
complete -c trip -l print-tui-binding-commands -d 'Print all TUI commands that can be bound and exit'
complete -c trip -l generate-man -d 'Generate ROFF man page'
complete -c trip -l print-config-template -d 'Print a template toml config file and exit'
complete -c trip -s v -l verbose -d 'Enable verbose debug logging'
complete -c trip -s h -l help -d 'Print help (see more with \'--help\')'
Expand Down
1 change: 1 addition & 0 deletions test_resources/config/completions_powershell.txt
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ Register-ArgumentCompleter -Native -CommandName 'trip' -ScriptBlock {
[CompletionResult]::new('--tui-preserve-screen', 'tui-preserve-screen', [CompletionResultType]::ParameterName, 'Preserve the screen on exit [default: false]')
[CompletionResult]::new('--print-tui-theme-items', 'print-tui-theme-items', [CompletionResultType]::ParameterName, 'Print all TUI theme items and exit')
[CompletionResult]::new('--print-tui-binding-commands', 'print-tui-binding-commands', [CompletionResultType]::ParameterName, 'Print all TUI commands that can be bound and exit')
[CompletionResult]::new('--generate-man', 'generate-man', [CompletionResultType]::ParameterName, 'Generate ROFF man page')
[CompletionResult]::new('--print-config-template', 'print-config-template', [CompletionResultType]::ParameterName, 'Print a template toml config file and exit')
[CompletionResult]::new('-v', 'v', [CompletionResultType]::ParameterName, 'Enable verbose debug logging')
[CompletionResult]::new('--verbose', 'verbose', [CompletionResultType]::ParameterName, 'Enable verbose debug logging')
Expand Down
1 change: 1 addition & 0 deletions test_resources/config/completions_zsh.txt
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ full\:"Display all event spans"))' \
'--tui-preserve-screen[Preserve the screen on exit \[default\: false\]]' \
'--print-tui-theme-items[Print all TUI theme items and exit]' \
'--print-tui-binding-commands[Print all TUI commands that can be bound and exit]' \
'--generate-man[Generate ROFF man page]' \
'--print-config-template[Print a template toml config file and exit]' \
'-v[Enable verbose debug logging]' \
'--verbose[Enable verbose debug logging]' \
Expand Down
Loading

0 comments on commit cb918c7

Please sign in to comment.