help.rs
This file
Path
crates/core/flags/doc/help.rs
277 lines · 9.5 KiB · Rust
Last changed by
cargo: add new build-time `unstable-index` featureAndrew Gallantbefore adoptiond958105
History of this fileTake it
1/*!2Provides routines for generating ripgrep's "short" and "long" help3documentation.45The short version is used when the `-h` flag is given, while the long version6is used when the `--help` flag is given.7*/89use std::{collections::BTreeMap, fmt::Write};1011use crate::flags::{Category, Flag, defs::FLAGS, doc::version};1213const TEMPLATE_SHORT: &'static str = include_str!("template.short.help");14const TEMPLATE_LONG: &'static str = include_str!("template.long.help");1516/// Wraps `std::write!` and asserts there is no failure.17///18/// We only write to `String` in this module.19macro_rules! write {20 ($($tt:tt)*) => { std::write!($($tt)*).unwrap(); }21}2223/// Generate short documentation, i.e., for `-h`.24pub(crate) fn generate_short() -> String {25 let mut cats: BTreeMap<Category, (Vec<String>, Vec<String>)> =26 BTreeMap::new();27 let (mut maxcol1, mut maxcol2) = (0, 0);28 for flag in FLAGS.iter().copied() {29 let columns =30 cats.entry(flag.doc_category()).or_insert((vec![], vec![]));31 let (col1, col2) = generate_short_flag(flag);32 maxcol1 = maxcol1.max(col1.len());33 maxcol2 = maxcol2.max(col2.len());34 columns.0.push(col1);35 columns.1.push(col2);36 }37 let mut out =38 TEMPLATE_SHORT.replace("!!VERSION!!", &version::generate_digits());39 for (cat, (col1, col2)) in cats.iter() {40 let var = format!("!!{name}!!", name = cat.as_str());41 if !cfg!(feature = "unstable-index")42 && matches!(cat, crate::flags::Category::Indexing)43 {44 out = out.replace(45 &var,46 &format!(" {}", crate::flags::INDEXING_NOT_SUPPORTED),47 );48 } else {49 let val = format_short_columns(col1, col2, maxcol1, maxcol2);50 out = out.replace(&var, &val);51 }52 }53 out54}5556/// Generate short for a single flag.57///58/// The first element corresponds to the flag name while the second element59/// corresponds to the documentation string.60fn generate_short_flag(flag: &dyn Flag) -> (String, String) {61 let (mut col1, mut col2) = (String::new(), String::new());6263 // Some of the variable names are fine for longer form64 // docs, but they make the succinct short help very noisy.65 // So just shorten some of them.66 let var = flag.doc_variable().map(|s| {67 let mut s = s.to_string();68 s = s.replace("SEPARATOR", "SEP");69 s = s.replace("REPLACEMENT", "TEXT");70 s = s.replace("NUM+SUFFIX?", "NUM");71 s72 });7374 // Generate the first column, the flag name.75 if let Some(byte) = flag.name_short() {76 let name = char::from(byte);77 write!(col1, r"-{name}");78 write!(col1, r", ");79 }80 write!(col1, r"--{name}", name = flag.name_long());81 if let Some(var) = var.as_ref() {82 write!(col1, r"={var}");83 }8485 // And now the second column, with the description.86 write!(col2, "{}", flag.doc_short());8788 (col1, col2)89}9091/// Write two columns of documentation.92///93/// `maxcol1` should be the maximum length (in bytes) of the first column,94/// while `maxcol2` should be the maximum length (in bytes) of the second95/// column.96fn format_short_columns(97 col1: &[String],98 col2: &[String],99 maxcol1: usize,100 _maxcol2: usize,101) -> String {102 assert_eq!(col1.len(), col2.len(), "columns must have equal length");103 const PAD: usize = 2;104 let mut out = String::new();105 for (i, (c1, c2)) in col1.iter().zip(col2.iter()).enumerate() {106 if i > 0 {107 write!(out, "\n");108 }109110 let pad = maxcol1 - c1.len() + PAD;111 write!(out, " ");112 write!(out, "{c1}");113 write!(out, "{}", " ".repeat(pad));114 write!(out, "{c2}");115 }116 out117}118119/// Generate long documentation, i.e., for `--help`.120pub(crate) fn generate_long() -> String {121 let mut cats = BTreeMap::new();122 for flag in FLAGS.iter().copied() {123 let mut cat = cats.entry(flag.doc_category()).or_insert(String::new());124 if !cat.is_empty() {125 write!(cat, "\n\n");126 }127 generate_long_flag(flag, &mut cat);128 }129130 let mut out =131 TEMPLATE_LONG.replace("!!VERSION!!", &version::generate_digits());132 for (cat, value) in cats.iter() {133 let var = format!("!!{name}!!", name = cat.as_str());134 if !cfg!(feature = "unstable-index")135 && matches!(cat, crate::flags::Category::Indexing)136 {137 out = out.replace(138 &var,139 &format!(" {}", crate::flags::INDEXING_NOT_SUPPORTED),140 );141 } else {142 out = out.replace(&var, value);143 }144 }145 out146}147148/// Write generated documentation for `flag` to `out`.149fn generate_long_flag(flag: &dyn Flag, out: &mut String) {150 if let Some(byte) = flag.name_short() {151 let name = char::from(byte);152 write!(out, r" -{name}");153 if let Some(var) = flag.doc_variable() {154 write!(out, r" {var}");155 }156 write!(out, r", ");157 } else {158 write!(out, r" ");159 }160161 let name = flag.name_long();162 write!(out, r"--{name}");163 if let Some(var) = flag.doc_variable() {164 write!(out, r"={var}");165 }166 write!(out, "\n");167168 let doc = flag.doc_long().trim();169 let doc = super::render_custom_markup(doc, "flag", |name, out| {170 let Some(flag) = crate::flags::parse::lookup(name) else {171 unreachable!(r"found unrecognized \flag{{{name}}} in --help docs")172 };173 if let Some(name) = flag.name_short() {174 write!(out, r"-{}/", char::from(name));175 }176 write!(out, r"--{}", flag.name_long());177 });178 let doc = super::render_custom_markup(&doc, "flag-negate", |name, out| {179 let Some(flag) = crate::flags::parse::lookup(name) else {180 unreachable!(181 r"found unrecognized \flag-negate{{{name}}} in --help docs"182 )183 };184 let Some(name) = flag.name_negated() else {185 let long = flag.name_long();186 unreachable!(187 "found \\flag-negate{{{long}}} in --help docs but \188 {long} does not have a negation"189 );190 };191 write!(out, r"--{name}");192 });193194 let mut cleaned = remove_roff(&doc);195 if let Some(negated) = flag.name_negated() {196 // Flags that can be negated that aren't switches, like197 // --context-separator, are somewhat weird. Because of that, the docs198 // for those flags should discuss the semantics of negation explicitly.199 // But for switches, the behavior is always the same.200 if flag.is_switch() {201 write!(cleaned, "\n\nThis flag can be disabled with --{negated}.");202 }203 }204 let indent = " ".repeat(8);205 let wrapopts = textwrap::Options::new(71)206 // Normally I'd be fine with breaking at hyphens, but ripgrep's docs207 // includes a lot of flag names, and they in turn contain hyphens.208 // Breaking flag names across lines is not great.209 .word_splitter(textwrap::WordSplitter::NoHyphenation);210 for (i, paragraph) in cleaned.split("\n\n").enumerate() {211 if i > 0 {212 write!(out, "\n\n");213 }214 let mut new = paragraph.to_string();215 if paragraph.lines().all(|line| line.starts_with(" ")) {216 // Re-indent but don't refill so as to preserve line breaks217 // in code/shell example snippets.218 new = textwrap::indent(&new, &indent);219 } else {220 new = new.replace("\n", " ");221 new = textwrap::refill(&new, &wrapopts);222 new = textwrap::indent(&new, &indent);223 }224 write!(out, "{}", new.trim_end());225 }226}227228/// Removes roff syntax from `v` such that the result is approximately plain229/// text readable.230///231/// This is basically a mish mash of heuristics based on the specific roff used232/// in the docs for the flags in this tool. If new kinds of roff are used in233/// the docs, then this may need to be updated to handle them.234fn remove_roff(v: &str) -> String {235 let mut lines = vec![];236 for line in v.trim().lines() {237 assert!(!line.is_empty(), "roff should have no empty lines");238 if line.starts_with(".") {239 if line.starts_with(".IP ") {240 let item_label = line241 .split(" ")242 .nth(1)243 .expect("first argument to .IP")244 .replace(r"\(bu", r"•")245 .replace(r"\fB", "")246 .replace(r"\fP", ":");247 lines.push(format!("{item_label}"));248 } else if line.starts_with(".IB ") || line.starts_with(".BI ") {249 let pieces = line250 .split_whitespace()251 .skip(1)252 .collect::<Vec<_>>()253 .concat();254 lines.push(format!("{pieces}"));255 } else if line.starts_with(".sp")256 || line.starts_with(".PP")257 || line.starts_with(".TP")258 {259 lines.push("".to_string());260 }261 } else if line.starts_with(r"\fB") && line.ends_with(r"\fP") {262 let line = line.replace(r"\fB", "").replace(r"\fP", "");263 lines.push(format!("{line}:"));264 } else {265 lines.push(line.to_string());266 }267 }268 // Squash multiple adjacent paragraph breaks into one.269 lines.dedup_by(|l1, l2| l1.is_empty() && l2.is_empty());270 lines271 .join("\n")272 .replace(r"\fB", "")273 .replace(r"\fI", "")274 .replace(r"\fP", "")275 .replace(r"\-", "-")276 .replace(r"\\", r"\")277}