Skip to content
Myr

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

14 files+331 added−2 removed

modified:crates/core/flags/hiargs.rs+27 added
59 unmodified lines
60 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 lines
287 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 lines
926 }927 }928 Ok(builder)929 }930931 pub(crate) fn index(&self) -> usize {932 self.index933 }934935 #[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 }947948 #[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}956957/// State that only needs to be computed once during argument parsing.958///
558 unmodified lines
added:crates/core/index/disabled.rs+9 added
1use crate::flags::{HiArgs, SearchMode};23pub(crate) fn write(_args: &HiArgs) -> anyhow::Result<()> {4 anyhow::bail!("indexing not enabled in this build of ripgrep")5}67pub(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
1use crate::flags::{HiArgs, SearchMode};23pub(crate) fn write(args: &HiArgs) -> anyhow::Result<()> {4 let _index = args.index_write()?;5 Ok(())6}78pub(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
1pub(crate) use self::imp::*;23#[cfg(not(feature = "unstable-index"))]4#[path = "disabled.rs"]5mod imp;6#[cfg(feature = "unstable-index")]7#[path = "enabled.rs"]8mod imp;
deleted:crates/core/index.rs
modified:crates/core/main.rs+5 added-1 removed
83 unmodified lines
84 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 lines
added:crates/index/src/index.rs+217 added
1use std::{2 ffi::{OsStr, OsString},3 path::{Path, PathBuf},4};56use anyhow::Context;7use redb::{Database, ReadOnlyDatabase};89const INDEX_FILE_NAME: &str = "index.db";1011#[derive(Debug)]12pub struct Index {13 path: PathBuf,14 db: Handle,15}1617impl Index {18 pub fn builder() -> IndexBuilder {19 IndexBuilder::new()20 }2122 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 }2627 pub fn path(&self) -> &Path {28 &self.path29 }30}3132#[derive(Default)]33pub struct IndexBuilder {34 create: bool,35 write: bool,36}3738impl IndexBuilder {39 pub fn new() -> IndexBuilder {40 IndexBuilder::default()41 }4243 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 }5152 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 }6869 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 }9293 pub fn create(&mut self, yes: bool) -> &mut IndexBuilder {94 self.create = yes;95 self96 }9798 pub fn write(&mut self, yes: bool) -> &mut IndexBuilder {99 self.write = yes;100 self101 }102}103104pub struct IndexDiscovery {105 builder: IndexBuilder,106 cwd: Option<PathBuf>,107 env_name: OsString,108 dir_name: OsString,109}110111impl 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 }120121 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 }147148 pub fn cwd(&mut self, cwd: impl AsRef<Path>) -> &mut IndexDiscovery {149 self.cwd = Some(cwd.as_ref().into());150 self151 }152153 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 }160161 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 }168169 pub fn create(&mut self, yes: bool) -> &mut IndexDiscovery {170 self.builder.create(yes);171 self172 }173}174175enum Handle {176 ReadWrite(Database),177 ReadOnly(ReadOnlyDatabase),178}179180impl 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 }190191 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 }199200 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}209210impl 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)]23pub use index::{Index, IndexBuilder, IndexDiscovery};45mod index;6pub mod literal;
added:tests/index/basic.rs+6 added
1use crate::util::{Dir, TestCommand};23rgtest!(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
1use crate::util::{Dir, TestCommand};23rgtest!(search_mode, |dir: Dir, _cmd: TestCommand| {4 dir.create("test", "foobar");5 dir.command().arg("--x-crud").assert_exit_code(0);67 dir.command()8 .arg("-X")9 .arg("--files-without-match")10 .arg("no-match")
1 unmodified line
12});1314rgtest!(binary, |dir: Dir, _cmd: TestCommand| {15 dir.create("test", "foobar");16 dir.command().arg("--x-crud").assert_exit_code(0);1718 dir.command().arg("-X").arg("--text").arg("foobar").assert_err();19});2021rgtest!(encoding, |dir: Dir, _cmd: TestCommand| {22 dir.create("test", "foobar");23 dir.command().arg("--x-crud").assert_exit_code(0);2425 dir.command().arg("-X").arg("-Eutf16").arg("foobar").assert_err();26 dir.command().arg("-X").arg("-Enone").arg("foobar").assert_err();2728 eqnice!(
3 unmodified lines
32});3334rgtest!(engine, |dir: Dir, _cmd: TestCommand| {35 dir.create("test", "foobar");36 dir.command().arg("--x-crud").assert_exit_code(0);3738 dir.command().arg("-X").arg("--engine=pcre2").arg("foobar").assert_err();3940 eqnice!(41 "test:foobar\n",
6 unmodified lines
48});4950rgtest!(follow, |dir: Dir, _cmd: TestCommand| {51 dir.create("test", "foobar");52 dir.command().arg("--x-crud").assert_exit_code(0);5354 dir.command().arg("-X").arg("--follow").arg("foobar").assert_err();55});5657rgtest!(glob, |dir: Dir, _cmd: TestCommand| {58 dir.create("test", "foobar");59 dir.command().arg("--x-crud").assert_exit_code(0);6061 dir.command().arg("-X").arg("--glob=test").arg("foobar").assert_err();62});6364rgtest!(hidden, |dir: Dir, _cmd: TestCommand| {65 dir.create(".test", "foobar");66 dir.command().arg("--x-crud").assert_exit_code(0);6768 dir.command().arg("-X").arg("--hidden").arg("foobar").assert_err();69});7071rgtest!(iglob, |dir: Dir, _cmd: TestCommand| {72 dir.create("test", "foobar");73 dir.command().arg("--x-crud").assert_exit_code(0);7475 dir.command().arg("-X").arg("--iglob=test").arg("foobar").assert_err();76});7778rgtest!(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);8283 dir.command()84 .arg("-X")85 .arg("--ignore-file=ignore-file")86 .arg("foobar")
1 unmodified line
88});8990rgtest!(no_ignore, |dir: Dir, _cmd: TestCommand| {91 dir.create("test", "foobar");92 dir.command().arg("--x-crud").assert_exit_code(0);9394 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 lines
117});118119rgtest!(no_require_git, |dir: Dir, _cmd: TestCommand| {120 dir.create("test", "foobar");121 dir.command().arg("--x-crud").assert_exit_code(0);122123 dir.command().arg("-X").arg("--no-require-git").arg("foobar").assert_err();124});125126rgtest!(one_file_system, |dir: Dir, _cmd: TestCommand| {127 dir.create("test", "foobar");128 dir.command().arg("--x-crud").assert_exit_code(0);129130 dir.command()131 .arg("-X")132 .arg("--one-file-system")133 .arg("foobar")
2 unmodified lines
136137#[cfg(unix)] // in order to use `cat`138rgtest!(pre, |dir: Dir, _cmd: TestCommand| {139 dir.create("test", "foobar");140 dir.command().arg("--x-crud").assert_exit_code(0);141142 dir.command().arg("-X").arg("--pre").arg("cat").arg("foobar").assert_err();143});144145rgtest!(search_zip, |dir: Dir, _cmd: TestCommand| {146 dir.create("test", "foobar");147 dir.command().arg("--x-crud").assert_exit_code(0);148149 dir.command().arg("-X").arg("--search-zip").arg("foobar").assert_err();150});151152rgtest!(unrestricted, |dir: Dir, _cmd: TestCommand| {153 dir.create("test", "foobar");154 dir.command().arg("--x-crud").assert_exit_code(0);155156 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.2mod 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.5mod disallowed;
modified:.gitignore+3 added
18 unmodified lines
1920# Cargo timings21cargo-timing-*.html22cargo-timing.html2324# ripgrep index25.ripgrep
modified:Cargo.lock+1 added
416 unmodified lines
417dependencies = [418 "anyhow",419 "bstr",420 "grep",421 "grep-index",422 "ignore",423 "lexopt",424 "log",425 "serde",
156 unmodified lines
modified:Cargo.toml+2 added-1 removed
56 unmodified lines
57[dependencies]58anyhow = "1.0.75"59bstr = "1.7.0"60grep = { version = "0.4.1", path = "crates/grep" }61grep-index = { version = "0.0.1", path = "crates/index", optional = true }62ignore = { version = "0.4.29", path = "crates/ignore" }63lexopt = "0.3.0"64log = "0.4.5"65serde_json = "1.0.23"
11 unmodified lines
77[features]78pcre2 = ["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.80unstable-index = []81unstable-index = ["dep:grep-index"]8283[profile.release]84debug = 185
41 unmodified lines