mod.rs
This file
Path
crates/core/flags/mod.rs
309 lines · 11.8 KiB · Rust
Last changed by
cargo: add new build-time `unstable-index` featureAndrew Gallantbefore adoptiond958105
History of this fileTake it
1/*!2Defines ripgrep's command line interface.34This modules deals with everything involving ripgrep's flags and positional5arguments. This includes generating shell completions, `--help` output and even6ripgrep's man page. It's also responsible for parsing and validating every7flag (including reading ripgrep's config file), and manages the contact points8between these flags and ripgrep's cast of supporting libraries. For example,9once [`HiArgs`] has been created, it knows how to create a multi threaded10recursive directory traverser.11*/12use std::{13 ffi::OsString,14 fmt::Debug,15 panic::{RefUnwindSafe, UnwindSafe},16};1718pub(crate) use crate::flags::{19 complete::{20 bash::generate as generate_complete_bash,21 fish::generate as generate_complete_fish,22 powershell::generate as generate_complete_powershell,23 zsh::generate as generate_complete_zsh,24 },25 doc::{26 help::{27 generate_long as generate_help_long,28 generate_short as generate_help_short,29 },30 man::generate as generate_man_page,31 version::{32 generate_long as generate_version_long,33 generate_pcre2 as generate_version_pcre2,34 generate_short as generate_version_short,35 },36 },37 hiargs::HiArgs,38 lowargs::{GenerateMode, Mode, SearchMode, SpecialMode},39 parse::{ParseResult, parse},40};4142mod complete;43mod config;44mod defs;45mod doc;46mod hiargs;47mod lowargs;48mod parse;4950const INDEXING_NOT_SUPPORTED: &'static str =51 "Indexing is not supported in this build of ripgrep.";5253/// A trait that encapsulates the definition of an optional flag for ripgrep.54///55/// This trait is meant to be used via dynamic dispatch. Namely, the `defs`56/// module provides a single global slice of `&dyn Flag` values correspondings57/// to all of the flags in ripgrep.58///59/// ripgrep's required positional arguments are handled by the parser and by60/// the conversion from low-level arguments to high level arguments. Namely,61/// all of ripgrep's positional arguments are treated as file paths, except62/// in certain circumstances where the first argument is treated as a regex63/// pattern.64///65/// Note that each implementation of this trait requires a long flag name,66/// but can also optionally have a short version and even a negation flag.67/// For example, the `-E/--encoding` flag accepts a value, but it also has a68/// `--no-encoding` negation flag for reverting back to "automatic" encoding69/// detection. All three of `-E`, `--encoding` and `--no-encoding` are provided70/// by a single implementation of this trait.71///72/// ripgrep only supports flags that are switches or flags that accept a single73/// value. Flags that accept multiple values are an unsupported aberration.74trait Flag: Debug + Send + Sync + UnwindSafe + RefUnwindSafe + 'static {75 /// Returns true if this flag is a switch. When a flag is a switch, the76 /// CLI parser will not look for a value after the flag is seen.77 fn is_switch(&self) -> bool;7879 /// A short single byte name for this flag. This returns `None` by default,80 /// which signifies that the flag has no short name.81 ///82 /// The byte returned must be an ASCII codepoint that is a `.` or is83 /// alpha-numeric.84 fn name_short(&self) -> Option<u8> {85 None86 }8788 /// Returns the long name of this flag. All flags must have a "long" name.89 ///90 /// The long name must be at least 2 bytes, and all of its bytes must be91 /// ASCII codepoints that are either `-` or alpha-numeric.92 fn name_long(&self) -> &'static str;9394 /// Returns a list of aliases for this flag.95 ///96 /// The aliases must follow the same rules as `Flag::name_long`.97 ///98 /// By default, an empty slice is returned.99 fn aliases(&self) -> &'static [&'static str] {100 &[]101 }102103 /// Returns a negated name for this flag. The negation of a flag is104 /// intended to have the opposite meaning of a flag or to otherwise turn105 /// something "off" or revert it to its default behavior.106 ///107 /// Negated flags are not listed in their own section in the `-h/--help`108 /// output or man page. Instead, they are automatically mentioned at the109 /// end of the documentation section of the flag they negated.110 ///111 /// The aliases must follow the same rules as `Flag::name_long`.112 ///113 /// By default, a flag has no negation and this returns `None`.114 fn name_negated(&self) -> Option<&'static str> {115 None116 }117118 /// Returns the variable name describing the type of value this flag119 /// accepts. This should always be set for non-switch flags and never set120 /// for switch flags.121 ///122 /// For example, the `--max-count` flag has its variable name set to `NUM`.123 ///124 /// The convention is to capitalize variable names.125 ///126 /// By default this returns `None`.127 fn doc_variable(&self) -> Option<&'static str> {128 None129 }130131 /// Returns the category of this flag.132 ///133 /// Every flag must have a single category. Categories are used to organize134 /// flags in the generated documentation.135 fn doc_category(&self) -> Category;136137 /// A (very) short documentation string describing what this flag does.138 ///139 /// This may sacrifice "proper English" in order to be as terse as140 /// possible. Generally, we try to ensure that `rg -h` doesn't have any141 /// lines that exceed 79 columns.142 fn doc_short(&self) -> &'static str;143144 /// A (possibly very) longer documentation string describing in full145 /// detail what this flag does. This should be in mandoc/mdoc format.146 fn doc_long(&self) -> &'static str;147148 /// If this is a non-switch flag that accepts a small set of specific149 /// values, then this should list them.150 ///151 /// This returns an empty slice by default.152 fn doc_choices(&self) -> &'static [&'static str] {153 &[]154 }155156 fn completion_type(&self) -> CompletionType {157 CompletionType::Other158 }159160 /// Given the parsed value (which might just be a switch), this should161 /// update the state in `args` based on the value given for this flag.162 ///163 /// This may update state for other flags as appropriate.164 ///165 /// The `-V/--version` and `-h/--help` flags are treated specially in the166 /// parser and should do nothing here.167 ///168 /// By convention, implementations should generally not try to "do"169 /// anything other than validate the value given. For example, the170 /// implementation for `--hostname-bin` should not try to resolve the171 /// hostname to use by running the binary provided. That should be saved172 /// for a later step. This convention is used to ensure that getting the173 /// low-level arguments is as reliable and quick as possible. It also174 /// ensures that "doing something" occurs a minimal number of times. For175 /// example, by avoiding trying to find the hostname here, we can do it176 /// once later no matter how many times `--hostname-bin` is provided.177 ///178 /// Implementations should not include the flag name in the error message179 /// returned. The flag name is included automatically by the parser.180 fn update(181 &self,182 value: FlagValue,183 args: &mut crate::flags::lowargs::LowArgs,184 ) -> anyhow::Result<()>;185}186187/// The category that a flag belongs to.188///189/// Categories are used to organize flags into "logical" groups in the190/// generated documentation.191#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]192enum Category {193 /// Flags related to how ripgrep reads its input. Its "input" generally194 /// consists of the patterns it is trying to match and the haystacks it is195 /// trying to search.196 Input,197 /// Flags related to the operation of the search itself. For example,198 /// whether case insensitive matching is enabled.199 Search,200 /// Flags related to how ripgrep filters haystacks. For example, whether201 /// to respect gitignore files or not.202 Filter,203 /// Flags related to how ripgrep shows its search results. For example,204 /// whether to show line numbers or not.205 Output,206 /// Flags related to changing ripgrep's output at a more fundamental level.207 /// For example, flags like `--count` suppress printing of individual208 /// lines, and instead just print the total count of matches for each file209 /// searched.210 OutputModes,211 /// Flags related to indexing. This section includes flags both for212 /// searching an index and updating an index.213 Indexing,214 /// Flags related to logging behavior such as emitting non-fatal error215 /// messages or printing search statistics.216 Logging,217 /// Other behaviors not related to ripgrep's core functionality. For218 /// example, printing the file type globbing rules, or printing the list219 /// of files ripgrep would search without actually searching them.220 OtherBehaviors,221}222223impl Category {224 /// Returns a string representation of this category.225 ///226 /// This string is the name of the variable used in various templates for227 /// generated documentation. This name can be used for interpolation.228 fn as_str(&self) -> &'static str {229 match *self {230 Category::Input => "input",231 Category::Search => "search",232 Category::Filter => "filter",233 Category::Output => "output",234 Category::OutputModes => "output-modes",235 Category::Indexing => "indexing",236 Category::Logging => "logging",237 Category::OtherBehaviors => "other-behaviors",238 }239 }240}241242/// The kind of argument a flag accepts, to be used for shell completions.243#[derive(Clone, Copy, Debug)]244enum CompletionType {245 /// No special category. is_switch() and doc_choices() may apply.246 Other,247 /// A path to a file.248 Filename,249 /// A command in $PATH.250 Executable,251 /// The name of a file type, as used by e.g. --type.252 Filetype,253 /// The name of an encoding_rs encoding, as used by --encoding.254 Encoding,255}256257/// Represents a value parsed from the command line.258///259/// This doesn't include the corresponding flag, but values come in one of260/// two forms: a switch (on or off) or an arbitrary value.261///262/// Note that the CLI doesn't directly support negated switches. For example,263/// you can'd do anything like `-n=false` or any of that nonsense. Instead,264/// the CLI parser knows about which flag names are negations and which aren't265/// (courtesy of the `Flag` trait). If a flag given is known as a negation,266/// then a `FlagValue::Switch(false)` value is passed into `Flag::update`.267#[derive(Debug)]268enum FlagValue {269 /// A flag that is either on or off.270 Switch(bool),271 /// A flag that comes with an arbitrary user value.272 Value(OsString),273}274275impl FlagValue {276 /// Return the yes or no value of this switch.277 ///278 /// If this flag value is not a switch, then this panics.279 ///280 /// This is useful when writing the implementation of `Flag::update`.281 /// namely, callers usually know whether a switch or a value is expected.282 /// If a flag is something different, then it indicates a bug, and thus a283 /// panic is acceptable.284 fn unwrap_switch(self) -> bool {285 match self {286 FlagValue::Switch(yes) => yes,287 FlagValue::Value(_) => {288 unreachable!("got flag value but expected switch")289 }290 }291 }292293 /// Return the user provided value of this flag.294 ///295 /// If this flag is a switch, then this panics.296 ///297 /// This is useful when writing the implementation of `Flag::update`.298 /// namely, callers usually know whether a switch or a value is expected.299 /// If a flag is something different, then it indicates a bug, and thus a300 /// panic is acceptable.301 fn unwrap_value(self) -> OsString {302 match self {303 FlagValue::Switch(_) => {304 unreachable!("got switch but expected flag value")305 }306 FlagValue::Value(v) => v,307 }308 }309}