index: add some initial indexing scaffolding
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This gives us some room to actually start writing out some index operations.
authored by Andrew Gallant · committed by Andrew Gallant · parent d99ac34 · Browse files · 14 files·+331 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+331 added−2 removed
- tests:+38 added−0 removed
- other:+293 added−2 removed
Provenance
- Commit
8372866- Tree
f23ffac- Author
Andrew Gallant <jamslam@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
d99ac34
14 files changed+331 added−2 removed
modified:crates/core/flags/hiargs.rs+27 added
59 unmodified lines60 hyperlink_config: grep::printer::HyperlinkConfig,61 ignore_file_case_insensitive: bool,62 ignore_file: Vec<PathBuf>,63 include_zero: bool,64+ index: usize,65 invert_match: bool,66 is_terminal_stdout: bool,67 line_number: bool,68 max_columns: Option<u64>,218 unmodified lines287 hyperlink_config,288 ignore_file: low.ignore_file,289 ignore_file_case_insensitive: low.ignore_file_case_insensitive,290 include_zero: low.include_zero,291+ index: low.index,292 invert_match: low.invert_match,293 is_terminal_stdout: state.is_terminal_stdout,294 line_number,295 max_columns: low.max_columns,630 unmodified lines926 }927 }928 Ok(builder)929 }930+931+ pub(crate) fn index(&self) -> usize {932+ self.index933+ }934+935+ #[cfg(feature = "unstable-index")]936+ pub(crate) fn index_write(&self) -> anyhow::Result<grep_index::Index> {937+ let index = grep_index::IndexDiscovery::new()938+ .create(true)939+ .discover()?940+ .ok_or_else(|| {941+ anyhow::anyhow!(942+ "failed to find a place to create/update an index"943+ )944+ })?;945+ Ok(index)946+ }947+948+ #[cfg(feature = "unstable-index")]949+ pub(crate) fn index_read(&self) -> anyhow::Result<grep_index::Index> {950+ let index = grep_index::IndexDiscovery::new().discover()?.ok_or_else(951+ || anyhow::anyhow!("failed to find an index to read"),952+ )?;953+ Ok(index)954+ }955 }956 957 /// State that only needs to be computed once during argument parsing.958 ///558 unmodified linesadded:crates/core/index/disabled.rs+9 added
1+use crate::flags::{HiArgs, SearchMode};2+3+pub(crate) fn write(_args: &HiArgs) -> anyhow::Result<()> {4+ anyhow::bail!("indexing not enabled in this build of ripgrep")5+}6+7+pub(crate) fn read(_args: &HiArgs, _mode: SearchMode) -> anyhow::Result<bool> {8+ anyhow::bail!("indexing not enabled in this build of ripgrep")9+}added:crates/core/index/enabled.rs+16 added
1+use crate::flags::{HiArgs, SearchMode};2+3+pub(crate) fn write(args: &HiArgs) -> anyhow::Result<()> {4+ let _index = args.index_write()?;5+ Ok(())6+}7+8+pub(crate) fn read(args: &HiArgs, mode: SearchMode) -> anyhow::Result<bool> {9+ let _index = args.index_read()?;10+ // Do an exhaustive search for now.11+ if args.threads() == 1 {12+ crate::search(args, mode)13+ } else {14+ crate::search_parallel(args, mode)15+ }16+}added:crates/core/index/mod.rs+8 added
1+pub(crate) use self::imp::*;2+3+#[cfg(not(feature = "unstable-index"))]4+#[path = "disabled.rs"]5+mod imp;6+#[cfg(feature = "unstable-index")]7+#[path = "enabled.rs"]8+mod imp;deleted:crates/core/index.rs
modified:crates/core/main.rs+5 added-1 removed
83 unmodified lines84 ParseResult::Ok(args) => args,85 };86 let matched = match args.mode() {87 Mode::Search(_) if !args.matches_possible() => false,88+ Mode::Search(mode) if args.index() > 0 => index::read(&args, mode)?,89 Mode::Search(mode) if args.threads() == 1 => search(&args, mode)?,90 Mode::Search(mode) => search_parallel(&args, mode)?,90- Mode::Index(_) => anyhow::bail!("indexing not yet implemented"),91+ Mode::Index(_) => {92+ index::write(&args)?;93+ return Ok(ExitCode::from(0));94+ }95 Mode::Files if args.threads() == 1 => files(&args)?,96 Mode::Files => files_parallel(&args)?,97 Mode::Types => return types(&args),98 Mode::Generate(mode) => return generate(mode),391 unmodified linesadded:crates/index/src/index.rs+217 added
1+use std::{2+ ffi::{OsStr, OsString},3+ path::{Path, PathBuf},4+};5+6+use anyhow::Context;7+use redb::{Database, ReadOnlyDatabase};8+9+const INDEX_FILE_NAME: &str = "index.db";10+11+#[derive(Debug)]12+pub struct Index {13+ path: PathBuf,14+ db: Handle,15+}16+17+impl Index {18+ pub fn builder() -> IndexBuilder {19+ IndexBuilder::new()20+ }21+22+ pub fn exists(path: impl AsRef<Path>) -> bool {23+ let path = path.as_ref();24+ path.is_dir() && path.join(INDEX_FILE_NAME).is_file()25+ }26+27+ pub fn path(&self) -> &Path {28+ &self.path29+ }30+}31+32+#[derive(Default)]33+pub struct IndexBuilder {34+ create: bool,35+ write: bool,36+}37+38+impl IndexBuilder {39+ pub fn new() -> IndexBuilder {40+ IndexBuilder::default()41+ }42+43+ pub fn build(&self, path: impl AsRef<Path>) -> anyhow::Result<Index> {44+ let path = path.as_ref();45+ if self.create {46+ self.build_create(path)47+ } else {48+ self.build_open(path)49+ }50+ }51+52+ fn build_create(&self, path: &Path) -> anyhow::Result<Index> {53+ if let Err(err) = std::fs::create_dir(path)54+ && err.kind() != std::io::ErrorKind::AlreadyExists55+ {56+ return Err(err).with_context(|| {57+ format!("{}: failed to create directory", path.display())58+ });59+ }60+ let path = path.join(INDEX_FILE_NAME);61+ // TODO: Retry here if the database is already open.62+ let db = Database::create(&path).with_context(|| {63+ format!("{}: failed to create database", path.display())64+ })?;65+ let index = Index { path, db: Handle::ReadWrite(db) };66+ Ok(index)67+ }68+69+ fn build_open(&self, path: &Path) -> anyhow::Result<Index> {70+ let path = path.join(INDEX_FILE_NAME);71+ // TODO: Retry here if the database is already open.72+ let db = if self.write {73+ Handle::ReadWrite(Database::open(&path).with_context(|| {74+ format!(75+ "{}: failed to open read-write database",76+ path.display()77+ )78+ })?)79+ } else {80+ Handle::ReadOnly(ReadOnlyDatabase::open(&path).with_context(81+ || {82+ format!(83+ "{}: failed to open read-only database",84+ path.display()85+ )86+ },87+ )?)88+ };89+ let index = Index { path, db };90+ Ok(index)91+ }92+93+ pub fn create(&mut self, yes: bool) -> &mut IndexBuilder {94+ self.create = yes;95+ self96+ }97+98+ pub fn write(&mut self, yes: bool) -> &mut IndexBuilder {99+ self.write = yes;100+ self101+ }102+}103+104+pub struct IndexDiscovery {105+ builder: IndexBuilder,106+ cwd: Option<PathBuf>,107+ env_name: OsString,108+ dir_name: OsString,109+}110+111+impl IndexDiscovery {112+ pub fn new() -> IndexDiscovery {113+ IndexDiscovery {114+ builder: IndexBuilder::new(),115+ cwd: None,116+ env_name: "RIPGREP_INDEX_PATH".into(),117+ dir_name: ".ripgrep".into(),118+ }119+ }120+121+ pub fn discover(&self) -> anyhow::Result<Option<Index>> {122+ let cwd = match self.cwd.clone() {123+ Some(cwd) => cwd,124+ None => std::env::current_dir()125+ .context("failed to get current working directory")?,126+ };127+ anyhow::ensure!(128+ cwd.is_absolute(),129+ "current working directory `{}` is not absolute",130+ cwd.display()131+ );132+ if let Some(env_path) = std::env::var_os(&self.env_name) {133+ if !env_path.is_empty() {134+ return Ok(Some(self.builder.build(env_path)?));135+ }136+ }137+ for ancestor in cwd.ancestors() {138+ let path = ancestor.join(&self.dir_name);139+ // I guess this is subject to TOCTOU problems, but the underlying140+ // embedded database should handle synchronization problems for us.141+ if self.builder.create || Index::exists(&path) {142+ return Ok(Some(self.builder.build(&path)?));143+ }144+ }145+ Ok(None)146+ }147+148+ pub fn cwd(&mut self, cwd: impl AsRef<Path>) -> &mut IndexDiscovery {149+ self.cwd = Some(cwd.as_ref().into());150+ self151+ }152+153+ pub fn env_name(154+ &mut self,155+ name: impl AsRef<OsStr>,156+ ) -> &mut IndexDiscovery {157+ self.env_name = name.as_ref().into();158+ self159+ }160+161+ pub fn dir_name(162+ &mut self,163+ name: impl AsRef<OsStr>,164+ ) -> &mut IndexDiscovery {165+ self.dir_name = name.as_ref().into();166+ self167+ }168+169+ pub fn create(&mut self, yes: bool) -> &mut IndexDiscovery {170+ self.builder.create(yes);171+ self172+ }173+}174+175+enum Handle {176+ ReadWrite(Database),177+ ReadOnly(ReadOnlyDatabase),178+}179+180+impl Handle {181+ fn begin_read(182+ &self,183+ ) -> Result<redb::ReadTransaction, redb::TransactionError> {184+ use redb::ReadableDatabase;185+ match self {186+ Handle::ReadWrite(database) => database.begin_read(),187+ Handle::ReadOnly(database) => database.begin_read(),188+ }189+ }190+191+ fn read_write(&self) -> anyhow::Result<&Database> {192+ match self {193+ Handle::ReadWrite(database) => Ok(database),194+ Handle::ReadOnly(_) => {195+ anyhow::bail!("index was opened read-only")196+ }197+ }198+ }199+200+ fn read_write_mut(&mut self) -> anyhow::Result<&mut Database> {201+ match self {202+ Handle::ReadWrite(database) => Ok(database),203+ Handle::ReadOnly(_) => {204+ anyhow::bail!("index was opened read-only")205+ }206+ }207+ }208+}209+210+impl std::fmt::Debug for Handle {211+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {212+ match *self {213+ Handle::ReadWrite(_) => write!(f, "<redb read-write database>"),214+ Handle::ReadOnly(_) => write!(f, "<redb read-only database>"),215+ }216+ }217+}modified:crates/index/src/lib.rs+5 added
1+#![allow(warnings)]2+3+pub use index::{Index, IndexBuilder, IndexDiscovery};4+5+mod index;6 pub mod literal;added:tests/index/basic.rs+6 added
1+use crate::util::{Dir, TestCommand};2+3+rgtest!(read_no_index, |dir: Dir, _cmd: TestCommand| {4+ dir.create("test", "foobar");5+ dir.command().arg("-X").arg("foobar").assert_err();6+});modified:tests/index/disallowed.rs+30 added
1 use crate::util::{Dir, TestCommand};2 3 rgtest!(search_mode, |dir: Dir, _cmd: TestCommand| {4 dir.create("test", "foobar");5+ dir.command().arg("--x-crud").assert_exit_code(0);6+7 dir.command()8 .arg("-X")9 .arg("--files-without-match")10 .arg("no-match")1 unmodified line12 });13 14 rgtest!(binary, |dir: Dir, _cmd: TestCommand| {15 dir.create("test", "foobar");16+ dir.command().arg("--x-crud").assert_exit_code(0);17+18 dir.command().arg("-X").arg("--text").arg("foobar").assert_err();19 });20 21 rgtest!(encoding, |dir: Dir, _cmd: TestCommand| {22 dir.create("test", "foobar");23+ dir.command().arg("--x-crud").assert_exit_code(0);24+25 dir.command().arg("-X").arg("-Eutf16").arg("foobar").assert_err();26 dir.command().arg("-X").arg("-Enone").arg("foobar").assert_err();27 28 eqnice!(3 unmodified lines32 });33 34 rgtest!(engine, |dir: Dir, _cmd: TestCommand| {35 dir.create("test", "foobar");36+ dir.command().arg("--x-crud").assert_exit_code(0);37+38 dir.command().arg("-X").arg("--engine=pcre2").arg("foobar").assert_err();39 40 eqnice!(41 "test:foobar\n",6 unmodified lines48 });49 50 rgtest!(follow, |dir: Dir, _cmd: TestCommand| {51 dir.create("test", "foobar");52+ dir.command().arg("--x-crud").assert_exit_code(0);53+54 dir.command().arg("-X").arg("--follow").arg("foobar").assert_err();55 });56 57 rgtest!(glob, |dir: Dir, _cmd: TestCommand| {58 dir.create("test", "foobar");59+ dir.command().arg("--x-crud").assert_exit_code(0);60+61 dir.command().arg("-X").arg("--glob=test").arg("foobar").assert_err();62 });63 64 rgtest!(hidden, |dir: Dir, _cmd: TestCommand| {65 dir.create(".test", "foobar");66+ dir.command().arg("--x-crud").assert_exit_code(0);67+68 dir.command().arg("-X").arg("--hidden").arg("foobar").assert_err();69 });70 71 rgtest!(iglob, |dir: Dir, _cmd: TestCommand| {72 dir.create("test", "foobar");73+ dir.command().arg("--x-crud").assert_exit_code(0);74+75 dir.command().arg("-X").arg("--iglob=test").arg("foobar").assert_err();76 });77 78 rgtest!(ignore_file, |dir: Dir, _cmd: TestCommand| {79 dir.create("test", "foobar");80 dir.create("ignore-file", "");81+ dir.command().arg("--x-crud").assert_exit_code(0);82+83 dir.command()84 .arg("-X")85 .arg("--ignore-file=ignore-file")86 .arg("foobar")1 unmodified line88 });89 90 rgtest!(no_ignore, |dir: Dir, _cmd: TestCommand| {91 dir.create("test", "foobar");92+ dir.command().arg("--x-crud").assert_exit_code(0);93+94 dir.command().arg("-X").arg("--no-ignore").arg("foobar").assert_err();95 dir.command().arg("-X").arg("--no-ignore-dot").arg("foobar").assert_err();96 dir.command()97 .arg("-X")19 unmodified lines117 });118 119 rgtest!(no_require_git, |dir: Dir, _cmd: TestCommand| {120 dir.create("test", "foobar");121+ dir.command().arg("--x-crud").assert_exit_code(0);122+123 dir.command().arg("-X").arg("--no-require-git").arg("foobar").assert_err();124 });125 126 rgtest!(one_file_system, |dir: Dir, _cmd: TestCommand| {127 dir.create("test", "foobar");128+ dir.command().arg("--x-crud").assert_exit_code(0);129+130 dir.command()131 .arg("-X")132 .arg("--one-file-system")133 .arg("foobar")2 unmodified lines136 137 #[cfg(unix)] // in order to use `cat`138 rgtest!(pre, |dir: Dir, _cmd: TestCommand| {139 dir.create("test", "foobar");140+ dir.command().arg("--x-crud").assert_exit_code(0);141+142 dir.command().arg("-X").arg("--pre").arg("cat").arg("foobar").assert_err();143 });144 145 rgtest!(search_zip, |dir: Dir, _cmd: TestCommand| {146 dir.create("test", "foobar");147+ dir.command().arg("--x-crud").assert_exit_code(0);148+149 dir.command().arg("-X").arg("--search-zip").arg("foobar").assert_err();150 });151 152 rgtest!(unrestricted, |dir: Dir, _cmd: TestCommand| {153 dir.create("test", "foobar");154+ dir.command().arg("--x-crud").assert_exit_code(0);155+156 dir.command().arg("-X").arg("-u").arg("foobar").assert_err();157 dir.command().arg("-X").arg("-uu").arg("foobar").assert_err();158 dir.command().arg("-X").arg("-uuu").arg("foobar").assert_err();159 });modified:tests/index/mod.rs+2 added
1+// Some basic UX interactions with an index.2+mod basic;3 // At present, many features of ripgrep are not allowed when using indexing.4 // Ideally some or many of these restrictions will be lifted over time.5 mod disallowed;modified:.gitignore+3 added
18 unmodified lines19 20 # Cargo timings21 cargo-timing-*.html22 cargo-timing.html23+24+# ripgrep index25+.ripgrepmodified:Cargo.lock+1 added
416 unmodified lines417 dependencies = [418 "anyhow",419 "bstr",420 "grep",421+ "grep-index",422 "ignore",423 "lexopt",424 "log",425 "serde",156 unmodified linesmodified:Cargo.toml+2 added-1 removed
56 unmodified lines57 [dependencies]58 anyhow = "1.0.75"59 bstr = "1.7.0"60 grep = { version = "0.4.1", path = "crates/grep" }61+grep-index = { version = "0.0.1", path = "crates/index", optional = true }62 ignore = { version = "0.4.29", path = "crates/ignore" }63 lexopt = "0.3.0"64 log = "0.4.5"65 serde_json = "1.0.23"11 unmodified lines77 [features]78 pcre2 = ["grep/pcre2"]79 # This provides opt-in support for indexing. This is currently in active80 # development and may have very serious bugs. Use at your own risk.80-unstable-index = []81+unstable-index = ["dep:grep-index"]82 83 [profile.release]84 debug = 185 41 unmodified lines