Skip to content
Myr

cargo: add new build-time `unstable-index` feature

Before adoption: this commit came in with the history the project adopted, so no landing records it.

... and add some of the initial flags, spec'd out in #1497, for adding indexing to ripgrep. These don't do anything yet. I chose to go this route because indexing will be a big feature, and it would be better to develop it on master instead of maintaining a long-lived branch for it.

authored by Andrew Gallant · committed by Andrew Gallant · parent 227381d · Browse files · 11 files+375 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+375 added−7 removed

  • other:+375 added−7 removed

11 files+375 added−7 removed

modified:.github/workflows/ci.yml+3 added
169 unmodified lines
170 echo "====="171 fi172 set -x173174 - name: Run tests with indexing enabled175 run: ${{ env.CARGO }} test --verbose --workspace --features unstable-index ${{ env.TARGET_FLAGS }}176177 - name: Run tests with PCRE2 (sans cross)178 if: matrix.target == ''179 run: ${{ env.CARGO }} test --verbose --workspace --features pcre2 ${{ env.TARGET_FLAGS }}180
91 unmodified lines
modified:crates/core/flags/doc/help.rs+21 added-3 removed
36 unmodified lines
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 {41 let val = format_short_columns(col1, col2, maxcol1, maxcol2);42 out = out.replace(&var, &val);49 let val = format_short_columns(col1, col2, maxcol1, maxcol2);50 out = out.replace(&var, &val);51 }52 }53 out54}55
74 unmodified lines
130 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 {125 out = out.replace(&var, value);142 out = out.replace(&var, value);143 }144 }145 out146}147
130 unmodified lines
modified:crates/core/flags/doc/man.rs+7 added-1 removed
35 unmodified lines
3637 let mut out = TEMPLATE.replace("!!VERSION!!", &version::generate_digits());38 for (cat, value) in cats.iter() {39 let var = format!("!!{name}!!", name = cat.as_str());40 if !cfg!(feature = "unstable-index")41 && matches!(cat, crate::flags::Category::Indexing)42 {43 out = out.replace(&var, crate::flags::INDEXING_NOT_SUPPORTED);44 } else {40 out = out.replace(&var, value);45 out = out.replace(&var, value);46 }47 }48 out49}50
66 unmodified lines
modified:crates/core/flags/doc/template.long.help+3 added
52 unmodified lines
5354OUTPUT MODES:55!!output-modes!!5657INDEXING:58!!indexing!!5960LOGGING OPTIONS:61!!logging!!6263OTHER BEHAVIORS:
1 unmodified line
modified:crates/core/flags/doc/template.rg.1+3 added
112 unmodified lines
113.114.SS OUTPUT MODES115!!output-modes!!116.117.SS INDEXING118!!indexing!!119.120.SS LOGGING OPTIONS121!!logging!!122.123.SS OTHER BEHAVIORS
304 unmodified lines
modified:crates/core/flags/doc/template.short.help+3 added
29 unmodified lines
3031OUTPUT MODES:32!!output-modes!!3334INDEXING:35!!indexing!!3637LOGGING OPTIONS:38!!logging!!3940OTHER BEHAVIORS:
1 unmodified line
modified:crates/core/flags/defs.rs+312 added-3 removed
23 unmodified lines
24use crate::flags::{25 Category, Flag, FlagValue,26 lowargs::{27 BinaryMode, BoundaryMode, BufferMode, CaseMode, ColorChoice,28 ContextMode, EncodingMode, EngineChoice, GenerateMode, LoggingMode,29 LowArgs, MmapMode, Mode, PatternSource, SearchMode, SortMode,30 SortModeKind, SpecialMode, TypeChange,28 ContextMode, EncodingMode, EngineChoice, GenerateMode, IndexMode,29 LoggingMode, LowArgs, MmapMode, Mode, PatternSource, SearchMode,30 SortMode, SortModeKind, SpecialMode, TypeChange,31 },32};3334#[cfg(test)]
48 unmodified lines
83 &IgnoreCase,84 &IgnoreFile,85 &IgnoreFileCaseInsensitive,86 &IncludeZero,87 &Index,88 &IndexCrud,89 &IndexForce,90 &IndexPath,91 &InvertMatch,92 &JSON,93 &LineBuffered,94 &LineNumber,
3281 unmodified lines
3376 let args = parse_low_raw(["--include-zero", "--no-include-zero"]).unwrap();3377 assert_eq!(false, args.include_zero);3378}33793380/// -X/--index3381#[derive(Debug)]3382struct Index;33833384impl Flag for Index {3385 fn is_switch(&self) -> bool {3386 true3387 }3388 fn name_short(&self) -> Option<u8> {3389 Some(b'X')3390 }3391 fn name_long(&self) -> &'static str {3392 "index"3393 }3394 fn doc_category(&self) -> Category {3395 Category::Indexing3396 }3397 fn doc_short(&self) -> &'static str {3398 r"Use a search index when one is available."3399 }3400 fn doc_long(&self) -> &'static str {3401 r"3402Enable searching with an index. Without this flag, ripgrep never uses an3403index.3404.sp3405ripgrep looks for an index in the following order. The first step that finds3406one or more indexes wins:3407.sp3408.IP 1. 43409When path operands are given on the command line, each operand is interpreted3410as an index directory and every index is searched in command line order. An3411operand that is not a valid index is an error.3412.sp3413.IP 2. 43414The index named by the \fBRIPGREP_INDEX_PATH\fP environment variable.3415.sp3416.IP 3. 43417A valid index in a \fB.ripgrep\fP directory in the current working directory.3418.sp3419.IP 4. 43420A valid index in a \fB.ripgrep\fP directory in the nearest parent of the current3421working directory.3422.PP3423If no index is found, ripgrep performs an ordinary search.3424.sp3425Indexed candidates are filtered by explicit glob and file-type selections,3426hidden-file and depth settings, and the maximum file size. Ignore files,3427including \fB.gitignore\fP, are not read or reapplied during an indexed search.3428Options that require transformed contents or every file make the query3429ineligible for candidate filtering and therefore trigger the fallback below.3430.sp3431This flag may be given at most twice. When it is given once and the query3432cannot use an index, ripgrep performs an ordinary search. When it is given3433twice and an index was found, ripgrep stops instead of performing an ordinary3434search if the query cannot use the index.3435"3436 }34373438 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3439 check_indexing_allowed()?;3440 assert!(v.unwrap_switch(), "--index has no negation");3441 args.index = args.index.saturating_add(1);3442 anyhow::ensure!(3443 args.index <= 2,3444 "-X/--index may be given at most twice"3445 );3446 Ok(())3447 }3448}34493450#[cfg(test)]3451#[test]3452fn test_index() {3453 if !cfg!(feature = "unstable-index") {3454 assert!(parse_low_raw(["-X"]).is_err());3455 return;3456 }34573458 let args = parse_low_raw(None::<&str>).unwrap();3459 assert_eq!(0, args.index);3460 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);34613462 let args = parse_low_raw(["-X"]).unwrap();3463 assert_eq!(1, args.index);3464 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);34653466 let args = parse_low_raw(["--index"]).unwrap();3467 assert_eq!(1, args.index);34683469 let args = parse_low_raw(["-XX"]).unwrap();3470 assert_eq!(2, args.index);34713472 let args = parse_low_raw(["-X", "--index"]).unwrap();3473 assert_eq!(2, args.index);34743475 let result = parse_low_raw(["-XXX"]);3476 assert!(result.is_err(), "{result:?}");3477}34783479/// --x-crud3480#[derive(Debug)]3481struct IndexCrud;34823483impl Flag for IndexCrud {3484 fn is_switch(&self) -> bool {3485 true3486 }3487 fn name_long(&self) -> &'static str {3488 "x-crud"3489 }3490 fn doc_category(&self) -> Category {3491 Category::Indexing3492 }3493 fn doc_short(&self) -> &'static str {3494 r"Create or update a search index."3495 }3496 fn doc_long(&self) -> &'static str {3497 r"3498Create or update an index for the files and directories given on the command3499line. When no path is given, this recursively indexes the current working3500directory. The files added to the index are exactly those selected by3501ripgrep's normal traversal and filtering options.3502.sp3503An existing file is re-indexed only when its modification time is newer than3504the time at which it was indexed. Use \flag{x-force} to re-index every selected3505file, including files on file systems with unreliable or deliberately3506preserved modification times. A previously indexed path that is no longer3507accessible is removed from the index.3508.sp3509ripgrep chooses the index location in the following order:3510.sp3511.IP 1. 43512The path given by \flag{x-path}.3513.sp3514.IP 2. 43515The path in the \fBRIPGREP_INDEX_PATH\fP environment variable.3516.sp3517.IP 3. 43518A valid index in a \fB.ripgrep\fP directory in the current working directory.3519.sp3520.IP 4. 43521A valid index in a \fB.ripgrep\fP directory in the nearest parent of the current3522working directory.3523.sp3524.IP 5. 43525A \fB.ripgrep\fP directory in the current working directory, which is created3526when necessary.3527.PP3528If the final location already exists but does not contain a valid index, then3529ripgrep reports an error.3530.sp3531For example, this creates or incrementally updates an index for the current3532directory:3533.sp3534.EX3535 rg --x-crud3536.EE3537.sp3538This updates one path in the same index:3539.sp3540.EX3541 rg --x-crud path/to/file3542.EE3543"3544 }35453546 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3547 check_indexing_allowed()?;3548 assert!(v.unwrap_switch(), "--x-crud has no negation");3549 args.mode.update(Mode::Index(IndexMode::Crud));3550 Ok(())3551 }3552}35533554#[cfg(test)]3555#[test]3556fn test_index_crud() {3557 if !cfg!(feature = "unstable-index") {3558 assert!(parse_low_raw(["--x-crud"]).is_err());3559 return;3560 }35613562 let args = parse_low_raw(None::<&str>).unwrap();3563 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);35643565 let args = parse_low_raw(["--x-crud"]).unwrap();3566 assert_eq!(Mode::Index(IndexMode::Crud), args.mode);35673568 let args = parse_low_raw(["--files", "--x-crud", "foo"]).unwrap();3569 assert_eq!(Mode::Index(IndexMode::Crud), args.mode);3570 assert_eq!(vec![std::ffi::OsString::from("foo")], args.positional);35713572 let args = parse_low_raw(["--x-crud", "--files"]).unwrap();3573 assert_eq!(Mode::Files, args.mode);3574}35753576/// --x-force3577#[derive(Debug)]3578struct IndexForce;35793580impl Flag for IndexForce {3581 fn is_switch(&self) -> bool {3582 true3583 }3584 fn name_long(&self) -> &'static str {3585 "x-force"3586 }3587 fn doc_category(&self) -> Category {3588 Category::Indexing3589 }3590 fn doc_short(&self) -> &'static str {3591 r"Force selected files to be re-indexed."3592 }3593 fn doc_long(&self) -> &'static str {3594 r"3595When used with \flag{x-crud}, re-index every selected file even when its3596modification time indicates that the index is already up to date.3597"3598 }35993600 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3601 check_indexing_allowed()?;3602 assert!(v.unwrap_switch(), "--x-force has no negation");3603 args.index_force = true;3604 Ok(())3605 }3606}36073608#[cfg(test)]3609#[test]3610fn test_index_force() {3611 if !cfg!(feature = "unstable-index") {3612 assert!(parse_low_raw(["--x-force"]).is_err());3613 return;3614 }36153616 let args = parse_low_raw(None::<&str>).unwrap();3617 assert_eq!(false, args.index_force);36183619 let args = parse_low_raw(["--x-force"]).unwrap();3620 assert_eq!(true, args.index_force);3621}36223623/// --x-path3624#[derive(Debug)]3625struct IndexPath;36263627impl Flag for IndexPath {3628 fn is_switch(&self) -> bool {3629 false3630 }3631 fn name_long(&self) -> &'static str {3632 "x-path"3633 }3634 fn doc_variable(&self) -> Option<&'static str> {3635 Some("PATH")3636 }3637 fn doc_category(&self) -> Category {3638 Category::Indexing3639 }3640 fn doc_short(&self) -> &'static str {3641 r"Set the path of the index to update."3642 }3643 fn doc_long(&self) -> &'static str {3644 r"3645Set the index path used by \flag{x-crud}. This takes precedence over3646\fBRIPGREP_INDEX_PATH\fP and automatic discovery of a \fB.ripgrep\fP directory.3647"3648 }3649 fn completion_type(&self) -> CompletionType {3650 CompletionType::Filename3651 }36523653 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3654 check_indexing_allowed()?;3655 args.index_path = Some(PathBuf::from(v.unwrap_value()));3656 Ok(())3657 }3658}36593660#[cfg(test)]3661#[test]3662fn test_index_path() {3663 if !cfg!(feature = "unstable-index") {3664 assert!(parse_low_raw(["--x-path"]).is_err());3665 return;3666 }36673668 let args = parse_low_raw(None::<&str>).unwrap();3669 assert_eq!(None, args.index_path);36703671 let args = parse_low_raw(["--x-path", "foo"]).unwrap();3672 assert_eq!(Some(PathBuf::from("foo")), args.index_path);36733674 let args = parse_low_raw(["--x-path=foo", "--x-path", "bar"]).unwrap();3675 assert_eq!(Some(PathBuf::from("bar")), args.index_path);3676}36773678/// -v/--invert-match3679#[derive(Debug)]3680struct InvertMatch;3681
4191 unmodified lines
7873 let args = parse_low_raw(["-w", "-x"]).unwrap();7874 assert_eq!(Some(BoundaryMode::Line), args.boundary);7875}78767877fn check_indexing_allowed() -> anyhow::Result<()> {7878 if cfg!(feature = "unstable-index") {7879 return Ok(());7880 }7881 anyhow::bail!("{}", crate::flags::INDEXING_NOT_SUPPORTED)7882}78837884mod convert {7885 use std::ffi::{OsStr, OsString};78867887 use anyhow::Context;
201 unmodified lines
modified:crates/core/flags/lowargs.rs+12 added
63 unmodified lines
64 pub(crate) iglobs: Vec<String>,65 pub(crate) ignore_file: Vec<PathBuf>,66 pub(crate) ignore_file_case_insensitive: bool,67 pub(crate) include_zero: bool,68 pub(crate) index: usize,69 pub(crate) index_force: bool,70 pub(crate) index_path: Option<PathBuf>,71 pub(crate) invert_match: bool,72 pub(crate) line_number: Option<bool>,73 pub(crate) logging: Option<LoggingMode>,74 pub(crate) max_columns: Option<u64>,
80 unmodified lines
155#[derive(Clone, Copy, Debug, Eq, PartialEq)]156pub(crate) enum Mode {157 /// ripgrep will execute a search of some kind.158 Search(SearchMode),159 /// Create or update a search index.160 Index(IndexMode),161 /// Show the files that *would* be searched, but don't actually search162 /// them.163 Files,164 /// List all file type definitions configured, including the default file
28 unmodified lines
193 }194 }195}196197/// The kind of index operation that ripgrep should perform.198#[derive(Clone, Copy, Debug, Eq, PartialEq)]199pub(crate) enum IndexMode {200 /// Add, update or remove files in an index.201 Crud,202}203204/// The kind of search that ripgrep is going to perform.205#[derive(Clone, Copy, Debug, Eq, PartialEq)]206pub(crate) enum SearchMode {207 /// The default standard mode of operation. ripgrep looks for matches and
528 unmodified lines
modified:crates/core/flags/mod.rs+7 added
45 unmodified lines
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 correspondings
150 unmodified lines
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. For
13 unmodified lines
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 }
70 unmodified lines
modified:crates/core/main.rs+1 added
84 unmodified lines
85 let matched = match args.mode() {86 Mode::Search(_) if !args.matches_possible() => false,87 Mode::Search(mode) if args.threads() == 1 => search(&args, mode)?,88 Mode::Search(mode) => search_parallel(&args, mode)?,89 Mode::Index(_) => anyhow::bail!("indexing not yet implemented"),90 Mode::Files if args.threads() == 1 => files(&args)?,91 Mode::Files => files_parallel(&args)?,92 Mode::Types => return types(&args),93 Mode::Generate(mode) => return generate(mode),
391 unmodified lines
modified:Cargo.toml+3 added
68 unmodified lines
69walkdir = "2"7071[features]72pcre2 = ["grep/pcre2"]73# This provides opt-in support for indexing. This is currently in active74# development and may have very serious bugs. Use at your own risk.75unstable-index = []7677[profile.release]78debug = 179
41 unmodified lines