diff --git a/src/indexer.rs b/src/indexer.rs index 9787dd3..aaa5e03 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -1291,6 +1291,30 @@ fn merge_matching_entry_details(result: &mut ManpageResult, incoming: &ManpageEn } fn fill_flag_alias_from_help(result: &mut ManpageResult, short: char, long: &str) -> bool { + let short_only = result + .entries + .iter() + .position(|entry| matches!(entry.switch, OwnedSwitch::Short(found) if found == short)); + let long_only = result + .entries + .iter() + .position(|entry| matches!(&entry.switch, OwnedSwitch::Long(name) if name == long)); + if let (Some(short_at), Some(long_at)) = (short_only, long_only) { + let spare = result.entries.remove(long_at); + let keep = &mut result.entries[if long_at < short_at { + short_at - 1 + } else { + short_at + }]; + keep.switch = OwnedSwitch::Both(short, long.to_owned()); + if keep.param.is_none() { + keep.param = spare.param; + } + if keep.desc.is_empty() { + keep.desc = spare.desc; + } + return true; + } if !entry_has_long(result, long) { for entry in &mut result.entries { if matches!(entry.switch, OwnedSwitch::Short(found) if found == short) { @@ -1323,6 +1347,14 @@ fn supplement_result_from_help(result: &mut ManpageResult, help: &ManpageResult) if fill_flag_alias_from_help(result, *short, long) { alias_changed = true; } + if entry_has_short(result, *short) && !entry_has_long(result, long) { + result.entries.push(ManpageEntry { + switch: OwnedSwitch::Long(long.clone()), + ..help_entry.clone() + }); + changed = true; + continue; + } if entry_overlaps(result, help_entry) { changed |= alias_changed; changed |= merge_matching_entry_details(result, help_entry); @@ -1764,6 +1796,63 @@ mod tests { ParamOrigin, }; + #[test] + fn colliding_short_keeps_the_long_of_a_merged_duplicate() { + let both = |short: char, long: &str| { + ManpageEntry { + switch: OwnedSwitch::Both(short, long.to_owned()), + param: None, + desc: long.to_owned(), + } + }; + let mut query = ManpageResult { + entries: vec![both('P', "attr-path")], + ..ManpageResult::default() + }; + let install = ManpageResult { + entries: vec![both('P', "preserve-installed")], + ..ManpageResult::default() + }; + assert!(supplement_result_from_duplicate_manpage( + &mut query, &install + )); + assert!(entry_has_long(&query, "preserve-installed")); + assert!( + query + .entries + .iter() + .any(|entry| { entry.switch == OwnedSwitch::Both('P', "attr-path".to_owned()) }) + ); + } + + #[test] + fn help_pair_joins_a_short_only_and_a_long_only_entry() { + let one = |switch| { + ManpageEntry { + switch, + param: None, + desc: String::new(), + } + }; + let mut result = ManpageResult { + entries: vec![ + one(OwnedSwitch::Short('t')), + one(OwnedSwitch::Long("list".to_owned())), + ], + ..ManpageResult::default() + }; + let help = ManpageResult { + entries: vec![one(OwnedSwitch::Both('t', "list".to_owned()))], + ..ManpageResult::default() + }; + assert!(supplement_result_from_help(&mut result, &help)); + assert_eq!(result.entries.len(), 1); + assert_eq!( + result.entries[0].switch, + OwnedSwitch::Both('t', "list".to_owned()) + ); + } + #[test] fn help_only_entries_apply_to_descendants() { let commands = HashSet::from(["git".to_owned(), "cargo test".to_owned()]); diff --git a/src/parsers/help.rs b/src/parsers/help.rs index b4e95c9..9779733 100644 --- a/src/parsers/help.rs +++ b/src/parsers/help.rs @@ -14,6 +14,7 @@ use nom::{ IResult, Parser as _, character::complete::space0, + sequence::preceded, }; use crate::{ @@ -23,12 +24,14 @@ use crate::{ description::description, helpers::get_indent, options::{ - flag_param, - switch_parser, + parse_usage_flags, + switch_and_param, }, positionals::{ extract_cli11_positionals, extract_usage_positionals, + skip_command_name, + usage_block, }, subcommands::subcommand_entry, }, @@ -38,6 +41,7 @@ use crate::{ ManpageSubcommand, OwnedParam, OwnedSwitch, + bracket_negation, }, }, }; @@ -51,7 +55,7 @@ type EntryParts<'src> = ( make_parser!(entry<'src> -> ManpageEntry, ( space0, - (switch_parser, flag_param), + switch_and_param, description, ) => |(_, (switch, param), (first, cont)) @@ -113,6 +117,11 @@ fn classify_section_line(line: &str) -> Option { if lower.starts_with("usage") { return Some(HelpSection::Unknown); } + // a column gap marks a `name description` entry, whose description can + // hold header words like "commands" or "flag". + if trimmed.contains(" ") || trimmed.contains('\t') { + return None; + } if lower.starts_with("valid arguments") || lower.contains(" is one of the following") || lower.contains(" defaults to") @@ -144,6 +153,40 @@ fn classify_section_line(line: &str) -> Option { None } +fn switch_names(switch: &OwnedSwitch) -> (Option, Option<&str>) { + match switch { + OwnedSwitch::Short(short) => (Some(*short), None), + OwnedSwitch::Long(long) => (None, Some(long)), + OwnedSwitch::Both(short, long) => (Some(*short), Some(long)), + } +} + +/// flags only the usage line names, git's `-C ` among them. +fn usage_line_entries(original: &str, listed: &[ManpageEntry]) -> Vec { + let Some(block) = usage_block(original) else { + return Vec::new(); + }; + let Ok((_, flags)) = preceded(skip_command_name, parse_usage_flags).parse(&block) else { + return Vec::new(); + }; + let mut added: Vec = Vec::new(); + for (switch, param) in flags { + let (short, long) = switch_names(&switch); + let known = listed.iter().chain(&added).any(|entry| { + let (known_short, known_long) = switch_names(&entry.switch); + (short.is_some() && short == known_short) || (long.is_some() && long == known_long) + }); + if !known { + added.push(ManpageEntry { + switch, + param, + desc: String::new(), + }); + } + } + added +} + fn consume_line(text: &str) -> &str { text.split_once('\n').map_or("", |(_, rest)| rest) } @@ -172,7 +215,9 @@ fn build_help_result(original: &str) -> ManpageResult { && let Ok((next, parsed)) = entry(rem) && parser_made_progress(rem, next) { + let negation = bracket_negation(line, &parsed); entries.push(parsed); + entries.extend(negation); rem = next; continue; } @@ -189,6 +234,8 @@ fn build_help_result(original: &str) -> ManpageResult { rem = consume_line(rem); } + entries.extend(usage_line_entries(original, &entries)); + // recursive --help probes dispatch on the lowercase name. let subcommands = dedup_subcommands(raw_subcommands) .into_iter() @@ -226,6 +273,7 @@ fn build_help_result(original: &str) -> ManpageResult { description: String::new(), }; result.normalize(); + result.attach_metavar_choices(original); result } diff --git a/src/parsers/help/options.rs b/src/parsers/help/options.rs index 7e31d70..cc0d87e 100644 --- a/src/parsers/help/options.rs +++ b/src/parsers/help/options.rs @@ -124,8 +124,9 @@ use nom::{ }, }; +// ripgrep spells its hidden-files flag `-.`, and some tools take `-?` for help. make_parser!(short_switch -> char, - preceded(char('-'), satisfy(char::is_alphanumeric))); + preceded(char('-'), satisfy(|ch: char| ch.is_alphanumeric() || matches!(ch, '.' | '?')))); // first char must be alphanumeric to reject `----------` separator lines in // `less --help` (and zstdless/bzless wrappers), else the dash run becomes a @@ -427,6 +428,49 @@ fn short_param_comma_long(input: &str) -> IResult<&str, Switch<'_>> { Ok((rem, Switch::Both(short, long))) } +// xz writes `-F format, --format=format`. a lowercase word is only a +// placeholder when the long form repeats it as its value. +fn lowercase_param_comma_long(input: &str) -> IResult<&str, (Switch<'_>, &str)> { + let (rem, (short, _, word, (), long)) = ( + short_switch, + space1, + take_while1(|ch: char| ch.is_ascii_lowercase()), + comma, + long_switch, + ) + .parse(input)?; + let repeated = rem + .strip_prefix('=') + .and_then(|tail| tail.strip_prefix(word)) + .is_some_and(|after| !after.starts_with(is_option_char)); + if !repeated { + return Err(NomErr::Error(NomError::new(input, ErrorKind::Verify))); + } + Ok((rem, (Switch::Both(short, long), word))) +} + +fn short_lowercase_param_comma_long(input: &str) -> IResult<&str, Switch<'_>> { + lowercase_param_comma_long(input).map(|(rem, (switch, _))| (rem, switch)) +} + +/// a switch and its value as one unit. the `-r number, --fill=number` form +/// names its value twice, so the repeat is the param and not a default. +/// +/// # Errors +/// +/// errors when the input does not start with a switch. +pub fn switch_and_param(input: &str) -> IResult<&str, (OwnedSwitch, Option)> { + if let Ok((rem, (switch, word))) = lowercase_param_comma_long(input) + && let Some(rest) = rem + .strip_prefix('=') + .and_then(|tail| tail.strip_prefix(word)) + { + let param = Param::Mandatory(word); + return Ok((rest, (switch.into(), Some(param.into())))); + } + (switch_parser, flag_param).parse(input) +} + switch_pair!(long_comma_short, long_switch, comma, short_switch => |long, short| Switch::Both(short, long)); @@ -463,6 +507,7 @@ make_parser!(switch_parser_borrowed<'src> -> Switch<'src>, short_comma_long, short_space_long, short_param_comma_long, + short_lowercase_param_comma_long, long_slash_short, long_comma_short, long_space_short, @@ -494,33 +539,119 @@ make_parser!(brace_pipe_switch<'src> -> Switch<'src>, ) ); +// git's `[-v | --version]` and `[-p | --paginate | -P | --no-pager]`. make_parser!(usage_switch_parser<'src> -> Switch<'src>, - alt((brace_pipe_switch, switch_parser_borrowed)) + alt((brace_pipe_switch, brace_pipe_long_short, brace_pipe_short_long, switch_parser_borrowed)) ); // trailing tokens inside a flag bracket. `[--option name value]` keeps // switch=Long("option") param=Mandatory("name"), discards ` value`. -make_parser!(take_till_bracket<'src> -> &'src str, take_till(|ch: char| ch == ']')); +make_parser!(take_till_bracket<'src> -> &'src str, + take_till(|ch: char| matches!(ch, ']' | '[' | '\n'))); + +// a switch cut short by `{` or more letters is a template (`--term-{new,bad}`) +// or a cluster (`-abc`), not a flag name. +type UsageFlag<'src> = (Switch<'src>, Option>); + +make_parser!(usage_flag<'src> -> UsageFlag<'src>, +( + terminated( + usage_switch_parser, + peek(alt((value((), satisfy(|ch| ch.is_whitespace() || matches!(ch, '=' | '[' | ']' | '|' | ',' | '<' | '\\'))), eof.map(|_| ())))) + ), + opt(alt((param_parser_borrowed, bracket_word_param))) +)); + +make_parser!(piped_usage_flags<'src> -> Vec>, + (usage_flag, many0(preceded((space0, char('|'), space0), usage_flag))) + => |(first, rest): (UsageFlag<'src>, Vec<_>)| { + let mut flags = vec![first]; + flags.extend(rest); + flags + } +); -make_parser!(flag_in_bracket<'src> -> (Switch<'src>, Option>), +make_parser!(flag_in_bracket<'src> -> Vec>, delimited( (char('['), space0), - (usage_switch_parser, opt(param_parser_borrowed)), - (take_till_bracket, char(']')) + piped_usage_flags, + (take_till_bracket, opt(char(']'))) ) ); +// a two letter bracket word, or a short one with a digit, is an example +// value like `[-t ext4] [-o ro]`. it says the flag takes a value but is not +// its name. +fn bracket_word(word: &str) -> Param<'_> { + let example = + word.len() == 2 || word.len() <= 4 && word.contains(|ch: char| ch.is_ascii_digit()); + Param::Mandatory(if example { "value" } else { word }) +} + +// a lowercase word closing the bracket after a flag names its value, +// `[-w secs]` and `[-o opt[,opts...]]`. +make_parser!(bracket_word_param<'src> -> Param<'src>, + delimited( + char(' '), + verify( + take_while1(|ch: char| ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '-' | '_')), + |word: &str| word.starts_with(|ch: char| ch.is_ascii_lowercase()), + ), + peek(satisfy(|ch| matches!(ch, ']' | '[' | '…' | '.'))) + ) => bracket_word); + +// `[-aApy]` bundles single-letter switches. only mixed case is taken since +// `[-xyz]` and `[-nt]` can equally be single-dash names and `[-WIDTH]` is a +// placeholder. man pages squeeze `[-S suffix]` into `[-Ssuffix]`, one flag +// and its value name. +fn short_cluster(input: &str) -> IResult<&str, Vec>> { + let (rem, letters) = delimited( + (char('['), space0, char('-')), + take_while1(|ch: char| ch.is_ascii_alphabetic()), + (space0, char(']')), + ) + .parse(input)?; + let mixed_case = letters.chars().any(|ch| ch.is_ascii_uppercase()) + && letters.chars().any(|ch| ch.is_ascii_lowercase()); + let (first, rest) = letters.split_at(1); + let flag_and_word = rest.len() > 1 + && (rest.chars().all(|ch| ch.is_ascii_lowercase()) + && first.starts_with(|ch: char| ch.is_ascii_uppercase()) + || rest.chars().all(|ch| ch.is_ascii_uppercase()) + && first.starts_with(|ch: char| ch.is_ascii_lowercase())); + let lead = letters.chars().take_while(char::is_ascii_lowercase).count(); + let opaque_word = lead >= 2 + && letters.get(lead + 1..).is_some_and(|tail| { + tail.starts_with(|ch: char| ch.is_ascii_lowercase()) && tail.len() >= 2 + }); + let camel_word = first.starts_with(|ch: char| ch.is_ascii_lowercase()) + && rest.starts_with(|ch: char| ch.is_ascii_uppercase()) + && rest.len() > 3 + && rest.chars().skip(1).all(|ch| ch.is_ascii_lowercase()); + if !mixed_case || flag_and_word || camel_word || opaque_word { + return Err(NomErr::Error(NomError::new(input, ErrorKind::Verify))); + } + Ok(( + rem, + letters + .chars() + .map(|ch| (Switch::Short(ch), None)) + .collect(), + )) +} + // collect every flag-bracketed switch and its first param. non-flag tokens // (positional brackets, command name, ellipses) skipped one char at a time. make_parser!(pub parse_usage_flags<'src> -> Vec<(OwnedSwitch, Option)>, many0(alt(( - map(flag_in_bracket, Some), + map(alt((flag_in_bracket, short_cluster)), Some), // `value(None, ...)` forces Clone on Switch/Param, `map(..., |_| None)` // doesn't. map(satisfy(|ch| ch != '\n' && ch != '\r'), |_| None), ))) - => |flags: Vec, Option>)>>| + => |flags: Vec>>>| flags.into_iter() + .flatten() .flatten() .map(|(switch, param)| (OwnedSwitch::from(switch), param.map(OwnedParam::from))) .collect() diff --git a/src/parsers/help/positionals.rs b/src/parsers/help/positionals.rs index d6683b3..2749a95 100644 --- a/src/parsers/help/positionals.rs +++ b/src/parsers/help/positionals.rs @@ -348,6 +348,18 @@ make_parser!(find_usage_line -> (), )) ); +/// the usage line with the indented lines wrapped under it, `usage:` dropped. +pub fn usage_block(input: &str) -> Option { + let mut lines = input.lines(); + let (head, ()) = lines.by_ref().find_map(|line| find_usage_line(line).ok())?; + let mut block = head.trim().to_owned(); + for line in lines.take_while(|line| line.starts_with([' ', '\t']) && !line.trim().is_empty()) { + block.push(' '); + block.push_str(line.trim()); + } + Some(block) +} + make_parser!(pub extract_usage_positionals<'src> -> Vec<(&'src str, Positional)>, preceded( many0(preceded(not(find_usage_line), (rest_of_line, line_ending))), diff --git a/src/parsers/manpage.rs b/src/parsers/manpage.rs index fd3da96..34be2ea 100644 --- a/src/parsers/manpage.rs +++ b/src/parsers/manpage.rs @@ -158,6 +158,20 @@ impl ManpageResult { || !self.positional_choices.is_empty() } + /// give still choice-less params the values a sentence elsewhere in `doc` + /// states for their metavar. + pub fn attach_metavar_choices(&mut self, doc: &str) { + for param in self + .entries + .iter_mut() + .filter_map(|entry| entry.param.as_mut()) + { + if param.choices.is_empty() { + param.choices = choices::mine_metavar(¶m.name, doc); + } + } + } + /// canonicalise so the cache holds one shape. runs once at the end of every /// parse path. pub fn normalize(&mut self) { @@ -177,6 +191,8 @@ impl ManpageResult { .join(" "); } } + let negations = self_negations(&self.entries); + self.entries.extend(negations); let entries = mem::take(&mut self.entries); self.entries = dedup_entries(merge_short_long_pairs(entries)); for entry in &mut self.entries { @@ -220,6 +236,61 @@ pub(crate) fn clamp_description(desc: &mut String) { desc.push('\u{2026}'); } +/// rg and other clap tools name a flag's opposite only inside its own +/// description, as in "this flag can be disabled with --no-crlf". naming +/// itself is what makes it safe, a flag mentioned by another entry may belong +/// to a different command. +fn self_negations(entries: &[ManpageEntry]) -> Vec { + let known: HashSet<&str> = entries.iter().filter_map(long_name).collect(); + let mut added = HashSet::new(); + entries + .iter() + .filter_map(|entry| { + let long = long_name(entry)?; + let opposite = long + .strip_prefix("no-") + .map_or_else(|| format!("no-{long}"), str::to_owned); + (!known.contains(opposite.as_str()) + && names_flag(&entry.desc, &opposite) + && added.insert(opposite.clone())) + .then(|| negation(opposite, long)) + }) + .collect() +} + +/// git's `--[no-]progress` spells both forms in one switch. +pub(crate) fn bracket_negation(line: &str, entry: &ManpageEntry) -> Option { + let long = long_name(entry)?; + names_flag(line, &format!("[no-]{long}")).then(|| negation(format!("no-{long}"), long)) +} + +fn negation(opposite: String, long: &str) -> ManpageEntry { + ManpageEntry { + switch: OwnedSwitch::Long(opposite), + param: None, + desc: format!("negates --{long}"), + } +} + +fn long_name(entry: &ManpageEntry) -> Option<&str> { + match &entry.switch { + OwnedSwitch::Long(long) | OwnedSwitch::Both(_, long) => Some(long), + OwnedSwitch::Short(_) => None, + } +} + +fn names_flag(desc: &str, long: &str) -> bool { + let token = format!("--{long}"); + let is_flag_char = |ch: char| ch.is_alphanumeric() || matches!(ch, '-' | '_'); + desc.match_indices(&token).any(|(at, _)| { + let before = desc.get(..at).and_then(|head| head.chars().next_back()); + let after = desc + .get(at + token.len()..) + .and_then(|tail| tail.chars().next()); + !before.is_some_and(is_flag_char) && !after.is_some_and(is_flag_char) + }) +} + fn entry_key(entry: &ManpageEntry) -> String { match &entry.switch { OwnedSwitch::Short(short) => format!("-{short}"), @@ -404,6 +475,17 @@ fn is_common_obvious_alias(short: char, long: &str) -> bool { pub fn parse_manpage_lines(lines: &[GroffLine]) -> ManpageResult { let mut result = parse_manpage_lines_raw(lines); result.normalize(); + let prose = lines + .iter() + .filter_map(|line| { + match line { + GroffLine::Text(text) => Some(text.as_str()), + GroffLine::Macro { .. } | GroffLine::Blank | GroffLine::Comment => None, + } + }) + .collect::>() + .join("\n"); + result.attach_metavar_choices(&prose); result } @@ -686,6 +768,44 @@ mod tests { } } + #[test] + fn self_named_opposites_become_entries() { + let mut result = ManpageResult { + entries: vec![ + entry( + OwnedSwitch::Both('m', "mmap".to_owned()), + "search using memory maps. this flag can be disabled with --no-mmap.", + ), + entry( + OwnedSwitch::Long("no-unicode".to_owned()), + "disable unicode mode. re-enable with --unicode", + ), + entry( + OwnedSwitch::Long("crlf".to_owned()), + "see --no-crlf-strict and --no-pcre2", + ), + entry( + OwnedSwitch::Long("color".to_owned()), + "disable with --no-color", + ), + entry(OwnedSwitch::Long("no-color".to_owned()), "no colours"), + ], + ..ManpageResult::default() + }; + result.normalize(); + let keys: Vec = result.entries.iter().map(entry_key).collect(); + assert_eq!(keys, [ + "--mmap", + "--no-unicode", + "--crlf", + "--color", + "--no-color", + "--no-mmap", + "--unicode" + ]); + assert_eq!(result.entries[5].desc, "negates --mmap"); + } + #[test] fn merges_non_adjacent_short_long_with_identical_desc() { let entries = vec![ diff --git a/src/parsers/manpage/choices.rs b/src/parsers/manpage/choices.rs index 849363f..87020fc 100644 --- a/src/parsers/manpage/choices.rs +++ b/src/parsers/manpage/choices.rs @@ -2,7 +2,10 @@ use std::collections::HashSet; -use crate::parsers::manpage::ParamChoice; +use crate::parsers::{ + manpage::ParamChoice, + nushell::nushell_type_of_param, +}; const MAX_VALUE_LEN: usize = 40; @@ -40,10 +43,11 @@ type Miner = fn(&str, &str) -> Vec; /// `desc` keeps its source line breaks. pub fn mine(param_name: &str, desc: &str) -> Vec { - let miners: [Miner; 5] = [ + let miners: [Miner; 6] = [ placeholder_list, bracketed_possible_values, listed_after_header, + quoted_label_list, parenthesized_list, inline_enumeration, ]; @@ -57,6 +61,52 @@ pub fn mine(param_name: &str, desc: &str) -> Vec { found } +/// values a doc-wide `The WHEN argument ...` sentence gives `param_name`. only +/// an all-caps metavar followed by the word `argument` counts, so a flag +/// cannot pick up a list written about some other name. +pub fn mine_metavar(param_name: &str, doc: &str) -> Vec { + let metavar = param_name.len() >= 3 + && param_name.starts_with(|ch: char| ch.is_ascii_uppercase()) + && param_name + .chars() + .all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_'); + if !metavar { + return Vec::new(); + } + let flat = flatten(doc); + flat.match_indices(param_name) + .filter(|(at, _)| { + !flat + .get(..*at) + .and_then(|before| before.chars().next_back()) + .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_') + }) + .filter_map(|(at, _)| flat.get(at + param_name.len()..)?.strip_prefix(" argument")) + .map(argument_values) + .find(|choices| choices.len() >= 2) + .unwrap_or_default() +} + +// `defaults to 'always' and can also be 'auto' or 'never'` or a plain linking +// verb followed by the list. +fn argument_values(after: &str) -> Vec { + if let Some(tail) = after.strip_prefix(" defaults to ") + && let Some((default, _, rest)) = enumerated_item(tail) + && let Some(listed) = [" and can also be ", " and can be "] + .iter() + .find_map(|joiner| rest.strip_prefix(joiner)) + { + let mut values = vec![choice(default, "")]; + values.extend(enumeration(listed)); + return values; + } + LINKING_VERBS + .iter() + .find_map(|verb| after.strip_prefix(verb)) + .map(enumeration) + .unwrap_or_default() +} + fn choice(value: &str, desc: &str) -> ParamChoice { ParamChoice { value: value.to_owned(), @@ -107,10 +157,28 @@ fn bracketed_possible_values(_param_name: &str, desc: &str) -> Vec .find(marker) .and_then(|start| desc.get(start + marker.len()..)) .and_then(|tail| tail.split_once(']')) - .map(|(inner, _)| values_of(inner.split(','))) + .map(|(inner, _)| bracketed_values(inner)) .unwrap_or_default() } +// eza writes `.name` and `mod|modified` as values and clap lists a custom +// `"+"` slot, none of which `values_of` takes. +fn bracketed_values(inner: &str) -> Vec { + let mut found = Vec::new(); + for part in inner.split(',').map(str::trim) { + let alternates: Vec<&str> = part.split('|').collect(); + if alternates + .iter() + .all(|alt| is_value(alt.strip_prefix('.').unwrap_or(alt))) + { + found.extend(alternates.into_iter().map(|alt| choice(alt, ""))); + } else if !part.contains('<') { + return Vec::new(); + } + } + found +} + fn listed_after_header(param_name: &str, desc: &str) -> Vec { let lines: Vec<&str> = desc.lines().map(str::trim).collect(); let param_lower = param_name.to_ascii_lowercase(); @@ -123,6 +191,36 @@ fn listed_after_header(param_name: &str, desc: &str) -> Vec { list_after(&lines, |paragraph| contains_word(paragraph, ¶m_lower)) } +// fd's `'f' or 'file': regular files` items under a first line ending in a +// colon. a later list such as fd's size units does not name the param's values. +fn quoted_label_list(_param_name: &str, desc: &str) -> Vec { + let mut lines = desc.lines().map(str::trim); + if !lines.next().is_some_and(|header| header.ends_with(':')) { + return Vec::new(); + } + let mut items: Vec = Vec::new(); + for line in lines.filter(|line| !line.is_empty()) { + match quoted_labels(line) { + Some(labelled) => items.extend(labelled), + None => break, + } + } + if items.len() >= 2 { items } else { Vec::new() } +} + +fn quoted_labels(line: &str) -> Option> { + let (labels, desc) = line.split_once("':")?; + let body = labels.strip_prefix('\'')?; + let values: Vec<&str> = body.split("' or '").collect(); + let spaced = desc.is_empty() || desc.starts_with(char::is_whitespace); + (spaced && values.iter().all(|value| is_value(value))).then(|| { + values + .into_iter() + .map(|value| choice(value, desc.trim())) + .collect() + }) +} + fn list_after(lines: &[&str], announces: Announces) -> Vec where Announces: Fn(&str) -> bool, @@ -269,6 +367,7 @@ fn inline_enumeration(param_name: &str, desc: &str) -> Vec { let after_param = flat .match_indices(param_name) .filter(|_| param_name.len() >= 2) + .filter(|_| nushell_type_of_param(param_name) != "path") .filter_map(|(at, _)| flat.split_at_checked(at)) .filter(|(before, _)| { !before diff --git a/src/parsers/manpage/strategies.rs b/src/parsers/manpage/strategies.rs index fb9e3e0..df3e377 100644 --- a/src/parsers/manpage/strategies.rs +++ b/src/parsers/manpage/strategies.rs @@ -8,10 +8,7 @@ use crate::{ parsers::{ help::{ help_parser, - options::{ - flag_param, - switch_parser, - }, + options::switch_and_param, }, manpage::{ ManpageEntry, @@ -56,7 +53,7 @@ fn collect_description_lines(lines: &[GroffLine], start: usize) -> (String, usiz pub fn parse_tag_to_entry(tag: &str, desc: String) -> Option { let rendered = strip_groff_escapes(tag); let result: nom::IResult<&str, (OwnedSwitch, Option)> = - (switch_parser, flag_param).parse(rendered.trim()); + switch_and_param.parse(rendered.trim()); match result { Ok((_, (switch, param))) => { Some(ManpageEntry { @@ -408,7 +405,7 @@ fn is_prose_line(text: &str, previous: &str) -> bool { if !line.starts_with('-') { return false; } - let Ok((rest, _)) = (switch_parser, flag_param).parse(line) else { + let Ok((rest, _)) = switch_and_param.parse(line) else { return false; }; rest.strip_prefix(' ').is_some_and(|tail| { diff --git a/tests/git_clone_fix.rs b/tests/git_clone_fix.rs index 308c1b1..f39786e 100644 --- a/tests/git_clone_fix.rs +++ b/tests/git_clone_fix.rs @@ -82,3 +82,37 @@ fn parser_keeps_negatable_params() { "reject-shallow should not parse prose as a param" ); } + +#[test] +fn bracketed_negations_keep_both_forms() { + let text = "usage: git clone [] [--] [] + + -j, --[no-]jobs number of submodules cloned in parallel + --[no-]progress force progress reporting + --checkout see --[no-]checkout-all +"; + let (_, result) = help_parser(text).expect("parse"); + let longs: Vec<&str> = result + .entries + .iter() + .filter_map(|entry| { + match &entry.switch { + OwnedSwitch::Long(long) | OwnedSwitch::Both(_, long) => Some(long.as_str()), + OwnedSwitch::Short(_) => None, + } + }) + .collect(); + assert_eq!(longs, [ + "jobs", + "no-jobs", + "progress", + "no-progress", + "checkout" + ]); + let no_jobs = result + .entries + .iter() + .find(|entry| matches!(&entry.switch, OwnedSwitch::Long(long) if long == "no-jobs")) + .expect("no-jobs entry"); + assert!(no_jobs.param.is_none()); +} diff --git a/tests/golden/parser/getent.snap b/tests/golden/parser/getent.snap index 52d4017..f4ba7b9 100644 --- a/tests/golden/parser/getent.snap +++ b/tests/golden/parser/getent.snap @@ -6,6 +6,7 @@ positional_choices: flags: -s|--service --no-idn + -?|--help positionals: database key diff --git a/tests/help_parser.rs b/tests/help_parser.rs index d9d3642..5e87ec3 100644 --- a/tests/help_parser.rs +++ b/tests/help_parser.rs @@ -119,6 +119,24 @@ fn flag_line_ending_in_a_colon_is_not_a_section_header() { assert_eq!(result.entries.len(), 3); } +#[test] +fn entry_descriptions_with_header_words_stay_entries() { + let result = parse( + "Commands: + query print stored completion data + dump list indexed commands + diff report flag and subcommand gaps + purge delete the cache +", + ); + let names: Vec<&str> = result + .subcommands + .iter() + .map(|sub| sub.name.as_str()) + .collect(); + assert_eq!(names, ["query", "dump", "diff", "purge"]); +} + #[test] fn git_negatable_long_with_an_option_value_is_kept() { let result = parse( @@ -312,3 +330,282 @@ fn flag_opening_a_description_is_not_a_short_alias() { ); assert!(entry(&result, "null").param.is_none()); } + +#[test] +fn punctuation_short_flags_pair_with_their_long_names() { + let result = parse( + "Options: + -., --hidden + Search hidden files and directories. + -?, --help + Show help. +", + ); + assert_eq!( + entry(&result, "hidden").switch, + OwnedSwitch::Both('.', "hidden".to_owned()) + ); + assert_eq!( + entry(&result, "help").switch, + OwnedSwitch::Both('?', "help".to_owned()) + ); +} + +fn choice_values(result: &ManpageResult, long: &str) -> Vec { + entry(result, long) + .param + .as_ref() + .map(|param| { + param + .choices + .iter() + .map(|found| found.value.clone()) + .collect() + }) + .unwrap_or_default() +} + +#[test] +fn wrapped_possible_values_keep_dotted_and_alternate_spellings() { + let result = parse( + "SORTING OPTIONS: + -s, --sort which field to sort by [default: name] [possible values: + name, .name, ext, + size, none] + -t, --time which timestamp field to show [possible values: + mod|modified, acc|accessed] + --time-style