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
Provenance
- Commit
d958105- Tree
17a7852- Author
Andrew Gallant <jamslam@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
227381d
11 files changed+375 added−7 removed
modified:.github/workflows/ci.yml+3 added
169 unmodified lines170 echo "====="171 fi172 set -x173 174+ - name: Run tests with indexing enabled175+ run: ${{ env.CARGO }} test --verbose --workspace --features unstable-index ${{ env.TARGET_FLAGS }}176+177 - 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 linesmodified:crates/core/flags/doc/help.rs+21 added-3 removed
36 unmodified lines37 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 lines130 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 linesmodified:crates/core/flags/doc/man.rs+7 added-1 removed
35 unmodified lines36 37 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 linesmodified:crates/core/flags/doc/template.long.help+3 added
52 unmodified lines53 54 OUTPUT MODES:55 !!output-modes!!56 57+INDEXING:58+!!indexing!!59+60 LOGGING OPTIONS:61 !!logging!!62 63 OTHER BEHAVIORS:1 unmodified linemodified:crates/core/flags/doc/template.rg.1+3 added
112 unmodified lines113 .114 .SS OUTPUT MODES115 !!output-modes!!116 .117+.SS INDEXING118+!!indexing!!119+.120 .SS LOGGING OPTIONS121 !!logging!!122 .123 .SS OTHER BEHAVIORS304 unmodified linesmodified:crates/core/flags/doc/template.short.help+3 added
29 unmodified lines30 31 OUTPUT MODES:32 !!output-modes!!33 34+INDEXING:35+!!indexing!!36+37 LOGGING OPTIONS:38 !!logging!!39 40 OTHER BEHAVIORS:1 unmodified linemodified:crates/core/flags/defs.rs+312 added-3 removed
23 unmodified lines24 use 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 };33 34 #[cfg(test)]48 unmodified lines83 &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 lines3376 let args = parse_low_raw(["--include-zero", "--no-include-zero"]).unwrap();3377 assert_eq!(false, args.include_zero);3378 }3379 3380+/// -X/--index3381+#[derive(Debug)]3382+struct Index;3383+3384+impl 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"3402+Enable searching with an index. Without this flag, ripgrep never uses an3403+index.3404+.sp3405+ripgrep looks for an index in the following order. The first step that finds3406+one or more indexes wins:3407+.sp3408+.IP 1. 43409+When path operands are given on the command line, each operand is interpreted3410+as an index directory and every index is searched in command line order. An3411+operand that is not a valid index is an error.3412+.sp3413+.IP 2. 43414+The index named by the \fBRIPGREP_INDEX_PATH\fP environment variable.3415+.sp3416+.IP 3. 43417+A valid index in a \fB.ripgrep\fP directory in the current working directory.3418+.sp3419+.IP 4. 43420+A valid index in a \fB.ripgrep\fP directory in the nearest parent of the current3421+working directory.3422+.PP3423+If no index is found, ripgrep performs an ordinary search.3424+.sp3425+Indexed candidates are filtered by explicit glob and file-type selections,3426+hidden-file and depth settings, and the maximum file size. Ignore files,3427+including \fB.gitignore\fP, are not read or reapplied during an indexed search.3428+Options that require transformed contents or every file make the query3429+ineligible for candidate filtering and therefore trigger the fallback below.3430+.sp3431+This flag may be given at most twice. When it is given once and the query3432+cannot use an index, ripgrep performs an ordinary search. When it is given3433+twice and an index was found, ripgrep stops instead of performing an ordinary3434+search if the query cannot use the index.3435+"3436+ }3437+3438+ 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+}3449+3450+#[cfg(test)]3451+#[test]3452+fn test_index() {3453+ if !cfg!(feature = "unstable-index") {3454+ assert!(parse_low_raw(["-X"]).is_err());3455+ return;3456+ }3457+3458+ let args = parse_low_raw(None::<&str>).unwrap();3459+ assert_eq!(0, args.index);3460+ assert_eq!(Mode::Search(SearchMode::Standard), args.mode);3461+3462+ let args = parse_low_raw(["-X"]).unwrap();3463+ assert_eq!(1, args.index);3464+ assert_eq!(Mode::Search(SearchMode::Standard), args.mode);3465+3466+ let args = parse_low_raw(["--index"]).unwrap();3467+ assert_eq!(1, args.index);3468+3469+ let args = parse_low_raw(["-XX"]).unwrap();3470+ assert_eq!(2, args.index);3471+3472+ let args = parse_low_raw(["-X", "--index"]).unwrap();3473+ assert_eq!(2, args.index);3474+3475+ let result = parse_low_raw(["-XXX"]);3476+ assert!(result.is_err(), "{result:?}");3477+}3478+3479+/// --x-crud3480+#[derive(Debug)]3481+struct IndexCrud;3482+3483+impl 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"3498+Create or update an index for the files and directories given on the command3499+line. When no path is given, this recursively indexes the current working3500+directory. The files added to the index are exactly those selected by3501+ripgrep's normal traversal and filtering options.3502+.sp3503+An existing file is re-indexed only when its modification time is newer than3504+the time at which it was indexed. Use \flag{x-force} to re-index every selected3505+file, including files on file systems with unreliable or deliberately3506+preserved modification times. A previously indexed path that is no longer3507+accessible is removed from the index.3508+.sp3509+ripgrep chooses the index location in the following order:3510+.sp3511+.IP 1. 43512+The path given by \flag{x-path}.3513+.sp3514+.IP 2. 43515+The path in the \fBRIPGREP_INDEX_PATH\fP environment variable.3516+.sp3517+.IP 3. 43518+A valid index in a \fB.ripgrep\fP directory in the current working directory.3519+.sp3520+.IP 4. 43521+A valid index in a \fB.ripgrep\fP directory in the nearest parent of the current3522+working directory.3523+.sp3524+.IP 5. 43525+A \fB.ripgrep\fP directory in the current working directory, which is created3526+when necessary.3527+.PP3528+If the final location already exists but does not contain a valid index, then3529+ripgrep reports an error.3530+.sp3531+For example, this creates or incrementally updates an index for the current3532+directory:3533+.sp3534+.EX3535+ rg --x-crud3536+.EE3537+.sp3538+This updates one path in the same index:3539+.sp3540+.EX3541+ rg --x-crud path/to/file3542+.EE3543+"3544+ }3545+3546+ 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+}3553+3554+#[cfg(test)]3555+#[test]3556+fn test_index_crud() {3557+ if !cfg!(feature = "unstable-index") {3558+ assert!(parse_low_raw(["--x-crud"]).is_err());3559+ return;3560+ }3561+3562+ let args = parse_low_raw(None::<&str>).unwrap();3563+ assert_eq!(Mode::Search(SearchMode::Standard), args.mode);3564+3565+ let args = parse_low_raw(["--x-crud"]).unwrap();3566+ assert_eq!(Mode::Index(IndexMode::Crud), args.mode);3567+3568+ 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);3571+3572+ let args = parse_low_raw(["--x-crud", "--files"]).unwrap();3573+ assert_eq!(Mode::Files, args.mode);3574+}3575+3576+/// --x-force3577+#[derive(Debug)]3578+struct IndexForce;3579+3580+impl 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"3595+When used with \flag{x-crud}, re-index every selected file even when its3596+modification time indicates that the index is already up to date.3597+"3598+ }3599+3600+ 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+}3607+3608+#[cfg(test)]3609+#[test]3610+fn test_index_force() {3611+ if !cfg!(feature = "unstable-index") {3612+ assert!(parse_low_raw(["--x-force"]).is_err());3613+ return;3614+ }3615+3616+ let args = parse_low_raw(None::<&str>).unwrap();3617+ assert_eq!(false, args.index_force);3618+3619+ let args = parse_low_raw(["--x-force"]).unwrap();3620+ assert_eq!(true, args.index_force);3621+}3622+3623+/// --x-path3624+#[derive(Debug)]3625+struct IndexPath;3626+3627+impl 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"3645+Set 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+ }3652+3653+ 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+}3659+3660+#[cfg(test)]3661+#[test]3662+fn test_index_path() {3663+ if !cfg!(feature = "unstable-index") {3664+ assert!(parse_low_raw(["--x-path"]).is_err());3665+ return;3666+ }3667+3668+ let args = parse_low_raw(None::<&str>).unwrap();3669+ assert_eq!(None, args.index_path);3670+3671+ let args = parse_low_raw(["--x-path", "foo"]).unwrap();3672+ assert_eq!(Some(PathBuf::from("foo")), args.index_path);3673+3674+ let args = parse_low_raw(["--x-path=foo", "--x-path", "bar"]).unwrap();3675+ assert_eq!(Some(PathBuf::from("bar")), args.index_path);3676+}3677+3678 /// -v/--invert-match3679 #[derive(Debug)]3680 struct InvertMatch;3681 4191 unmodified lines7873 let args = parse_low_raw(["-w", "-x"]).unwrap();7874 assert_eq!(Some(BoundaryMode::Line), args.boundary);7875 }7876 7877+fn check_indexing_allowed() -> anyhow::Result<()> {7878+ if cfg!(feature = "unstable-index") {7879+ return Ok(());7880+ }7881+ anyhow::bail!("{}", crate::flags::INDEXING_NOT_SUPPORTED)7882+}7883+7884 mod convert {7885 use std::ffi::{OsStr, OsString};7886 7887 use anyhow::Context;201 unmodified linesmodified:crates/core/flags/lowargs.rs+12 added
63 unmodified lines64 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 lines155 #[derive(Clone, Copy, Debug, Eq, PartialEq)]156 pub(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 file28 unmodified lines193 }194 }195 }196 197+/// The kind of index operation that ripgrep should perform.198+#[derive(Clone, Copy, Debug, Eq, PartialEq)]199+pub(crate) enum IndexMode {200+ /// Add, update or remove files in an index.201+ Crud,202+}203+204 /// The kind of search that ripgrep is going to perform.205 #[derive(Clone, Copy, Debug, Eq, PartialEq)]206 pub(crate) enum SearchMode {207 /// The default standard mode of operation. ripgrep looks for matches and528 unmodified linesmodified:crates/core/flags/mod.rs+7 added
45 unmodified lines46 mod hiargs;47 mod lowargs;48 mod parse;49 50+const INDEXING_NOT_SUPPORTED: &'static str =51+ "Indexing is not supported in this build of ripgrep.";52+53 /// 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 correspondings150 unmodified lines207 /// 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. For13 unmodified lines231 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 linesmodified:crates/core/main.rs+1 added
84 unmodified lines85 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 linesmodified:Cargo.toml+3 added
68 unmodified lines69 walkdir = "2"70 71 [features]72 pcre2 = ["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.75+unstable-index = []76 77 [profile.release]78 debug = 179 41 unmodified lines