Skip to content
Myr

core: polish the core of ripgrep

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

This I believe finishes are quest to do mechanical updates to ripgrep's style, bringing it in line with my current practice (loosely speaking).

authored by Andrew Gallant · committed by Andrew Gallant · parent 90b8499 · Browse files · 7 files+108 added−109 removed
This commit

State

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

Diff stats

7 files+108 added−109 removed

  • other:+108 added−109 removed

7 files+108 added−109 removed

modified:.github/workflows/ci.yml+1 added-1 removed
51 unmodified lines
52 matrix:53 include:54 - build: pinned55 os: ubuntu-latest56 rust: 1.70.056 rust: 1.72.157 - build: stable58 os: ubuntu-latest59 rust: stable60 - build: beta
165 unmodified lines
modified:crates/core/args.rs+60 added-56 removed
1use std::cmp;2use std::env;3use std::ffi::{OsStr, OsString};4use std::fs;5use std::io::{self, IsTerminal, Write};6use std::path::{Path, PathBuf};7use std::process;8use std::str::FromStr;9use std::sync::Arc;10use std::time::SystemTime;1use std::{2 env,3 ffi::{OsStr, OsString},4 io::{self, IsTerminal, Write},5 path::{Path, PathBuf},6 sync::Arc,7};812use clap;13use grep::cli;14use grep::matcher::LineTerminator;9use {10 clap,11 grep::{12 cli,13 matcher::LineTerminator,14 printer::{15 default_color_specs, ColorSpecs, HyperlinkConfig,16 HyperlinkEnvironment, HyperlinkFormat, JSONBuilder, PathPrinter,17 PathPrinterBuilder, Standard, StandardBuilder, Stats, Summary,18 SummaryBuilder, SummaryKind, JSON,19 },20 regex::{21 RegexMatcher as RustRegexMatcher,22 RegexMatcherBuilder as RustRegexMatcherBuilder,23 },24 searcher::{25 BinaryDetection, Encoding, MmapChoice, Searcher, SearcherBuilder,26 },27 },28 ignore::{29 overrides::{Override, OverrideBuilder},30 types::{FileTypeDef, Types, TypesBuilder},31 {Walk, WalkBuilder, WalkParallel},32 },33 termcolor::{BufferWriter, ColorChoice, WriteColor},34};3536#[cfg(feature = "pcre2")]37use grep::pcre2::{38 RegexMatcher as PCRE2RegexMatcher,39 RegexMatcherBuilder as PCRE2RegexMatcherBuilder,40};20use grep::printer::{21 default_color_specs, ColorSpecs, HyperlinkConfig, HyperlinkEnvironment,22 HyperlinkFormat, JSONBuilder, PathPrinter, PathPrinterBuilder, Standard,23 StandardBuilder, Stats, Summary, SummaryBuilder, SummaryKind, JSON,24};25use grep::regex::{26 RegexMatcher as RustRegexMatcher,27 RegexMatcherBuilder as RustRegexMatcherBuilder,28};29use grep::searcher::{30 BinaryDetection, Encoding, MmapChoice, Searcher, SearcherBuilder,31};32use ignore::overrides::{Override, OverrideBuilder};33use ignore::types::{FileTypeDef, Types, TypesBuilder};34use ignore::{Walk, WalkBuilder, WalkParallel};35use log;36use termcolor::{BufferWriter, ColorChoice, WriteColor};4138use crate::app;39use crate::config;40use crate::logger::Logger;41use crate::messages::{set_ignore_messages, set_messages};42use crate::search::{43 PatternMatcher, Printer, SearchWorker, SearchWorkerBuilder,42use crate::{43 app, config,44 logger::Logger,45 messages::{set_ignore_messages, set_messages},46 search::{PatternMatcher, Printer, SearchWorker, SearchWorkerBuilder},47 subject::{Subject, SubjectBuilder},48 Result,49};45use crate::subject::{Subject, SubjectBuilder};46use crate::Result;5051/// The command that ripgrep should execute based on the command line52/// configuration.53#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1078 unmodified lines
1132 fn hyperlink_config(&self) -> Result<HyperlinkConfig> {1133 let mut env = HyperlinkEnvironment::new();1134 env.host(hostname(self.value_of_os("hostname-bin")))1135 .wsl_prefix(wsl_prefix());1136 let fmt: HyperlinkFormat =1133 let fmt = match self.value_of_lossy("hyperlink-format") {1134 None => HyperlinkFormat::from_str("default").unwrap(),1135 Some(format) => match HyperlinkFormat::from_str(&format) {1136 Ok(format) => format,1137 Err(err) => {1138 let msg = format!("invalid hyperlink format: {err}");1139 return Err(msg.into());1140 }1141 },1142 };1137 match self.value_of_lossy("hyperlink-format") {1138 None => "default".parse().unwrap(),1139 Some(format) => match format.parse() {1140 Ok(format) => format,1141 Err(err) => {1142 let msg = format!("invalid hyperlink format: {err}");1143 return Err(msg.into());1144 }1145 },1146 };1147 log::debug!("hyperlink format: {:?}", fmt.to_string());1148 Ok(HyperlinkConfig::new(env, fmt))1149 }1150
441 unmodified lines
1592 }1593 let threads = self.usize_of("threads")?.unwrap_or(0);1594 let available =1595 std::thread::available_parallelism().map_or(1, |n| n.get());1592 Ok(if threads == 0 { cmp::min(12, available) } else { threads })1596 Ok(if threads == 0 { std::cmp::min(12, available) } else { threads })1597 }15981599 /// Builds a file type matcher from the command line flags.1600 fn types(&self) -> Result<Types> {
192 unmodified lines
1793fn sort_by_option<T: Ord>(1794 p1: &Option<T>,1795 p2: &Option<T>,1796 reverse: bool,1793) -> cmp::Ordering {1797) -> std::cmp::Ordering {1798 match (p1, p2, reverse) {1799 (Some(p1), Some(p2), true) => p1.cmp(&p2).reverse(),1800 (Some(p1), Some(p2), false) => p1.cmp(&p2),1797 _ => cmp::Ordering::Equal,1801 _ => std::cmp::Ordering::Equal,1802 }1803}18041805/// Returns a clap matches object if the given arguments parse successfully.
20 unmodified lines
1826 //1827 // (This is the point of this helper function. clap's functionality for1828 // doing this will panic on a broken pipe error.)1829 let _ = write!(io::stdout(), "{}", err);1826 process::exit(0);1830 std::process::exit(0);1831}18321833/// Attempts to discover the current working directory. This mostly just defers1834/// to the standard library, however, such things will fail if ripgrep is in
39 unmodified lines
1874 );1875 return platform_hostname();1876 }1877 };1874 let mut cmd = process::Command::new(&bin);1875 cmd.stdin(process::Stdio::null());1878 let mut cmd = std::process::Command::new(&bin);1879 cmd.stdin(std::process::Stdio::null());1880 let rdr = match grep::cli::CommandReader::new(&mut cmd) {1881 Ok(rdr) => rdr,1882 Err(err) => {1883 log::debug!(
74 unmodified lines
1958/// sorting Subjects by time.1959fn load_timestamps<G>(1960 subjects: impl Iterator<Item = Subject>,1961 get_time: G,1958) -> Vec<(Option<SystemTime>, Subject)>1962) -> Vec<(Option<std::time::SystemTime>, Subject)>1963where1960 G: Fn(&fs::Metadata) -> io::Result<SystemTime>,1964 G: Fn(&std::fs::Metadata) -> io::Result<std::time::SystemTime>,1965{1966 subjects1967 .map(|s| (s.path().metadata().and_then(|m| get_time(&m)).ok(), s))1968 .collect()
1 unmodified line
modified:crates/core/config.rs+10 added-15 removed
1// This module provides routines for reading ripgrep config "rc" files. The2// primary output of these routines is a sequence of arguments, where each3// argument corresponds precisely to one shell argument.45use std::env;6use std::error::Error;7use std::ffi::OsString;8use std::fs::File;9use std::io;10use std::path::{Path, PathBuf};5use std::{6 ffi::OsString,7 path::{Path, PathBuf},8};910use bstr::{io::BufReadExt, ByteSlice};13use log;1115use crate::Result;1612/// Return a sequence of arguments derived from ripgrep rc configuration files.13pub fn args() -> Vec<OsString> {19 let config_path = match env::var_os("RIPGREP_CONFIG_PATH") {14 let config_path = match std::env::var_os("RIPGREP_CONFIG_PATH") {15 None => return vec![],16 Some(config_path) => {17 if config_path.is_empty() {18 return vec![];
33 unmodified lines
52/// a problem parsing one or more lines in the file, then errors are returned53/// for each line in addition to successfully parsed arguments.54fn parse<P: AsRef<Path>>(55 path: P,61) -> Result<(Vec<OsString>, Vec<Box<dyn Error>>)> {56) -> crate::Result<(Vec<OsString>, Vec<Box<dyn std::error::Error>>)> {57 let path = path.as_ref();63 match File::open(&path) {58 match std::fs::File::open(&path) {59 Ok(file) => parse_reader(file),60 Err(err) => Err(From::from(format!("{}: {}", path.display(), err))),61 }62}
8 unmodified lines
71///72/// If the reader could not be read, then an error is returned. If there was a73/// problem parsing one or more lines, then errors are returned for each line74/// in addition to successfully parsed arguments.80fn parse_reader<R: io::Read>(75fn parse_reader<R: std::io::Read>(76 rdr: R,82) -> Result<(Vec<OsString>, Vec<Box<dyn Error>>)> {83 let mut bufrdr = io::BufReader::new(rdr);77) -> crate::Result<(Vec<OsString>, Vec<Box<dyn std::error::Error>>)> {78 let mut bufrdr = std::io::BufReader::new(rdr);79 let (mut args, mut errs) = (vec![], vec![]);80 let mut line_number = 0;81 bufrdr.for_byte_line_with_terminator(|line| {82 line_number += 1;
85 unmodified lines
modified:crates/core/main.rs+11 added-13 removed
1use std::error;2use std::io::{self, Write};3use std::process;4use std::sync::Mutex;5use std::time::Instant;1use std::{2 io::{self, Write},3 time::Instant,4};56use ignore::WalkState;79use args::Args;10use subject::Subject;8use crate::{args::Args, subject::Subject};910#[macro_use]11mod messages;12
26 unmodified lines
39#[cfg(all(target_env = "musl", target_pointer_width = "64"))]40#[global_allocator]41static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;4245type Result<T> = ::std::result::Result<T, Box<dyn error::Error>>;43type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;4445fn main() {46 if let Err(err) = Args::parse().and_then(try_main) {47 eprintln_locked!("{}", err);50 process::exit(2);48 std::process::exit(2);49 }50}5152fn try_main(args: Args) -> Result<()> {
8 unmodified lines
61 Types => types(&args),62 PCRE2Version => pcre2_version(&args),63 }?;64 if matched && (args.quiet() || !messages::errored()) {67 process::exit(0)65 std::process::exit(0)66 } else if messages::errored() {69 process::exit(2)67 std::process::exit(2)68 } else {71 process::exit(1)69 std::process::exit(1)70 }71}7273/// The top-level entry point for single-threaded search. This recursively
71 unmodified lines
145 let quit_after_match = args.quit_after_match()?;146 let started_at = Instant::now();147 let subject_builder = args.subject_builder();148 let bufwtr = args.buffer_writer()?;151 let stats = args.stats()?.map(Mutex::new);149 let stats = args.stats()?.map(std::sync::Mutex::new);150 let matched = AtomicBool::new(false);151 let searched = AtomicBool::new(false);152 let mut searcher_err = None;153 args.walker_parallel()?.run(|| {
224 unmodified lines
modified:crates/core/search.rs+21 added-16 removed
1use std::fs::File;2use std::io;3use std::path::{Path, PathBuf};4use std::process::{Command, Stdio};5use std::time::Duration;1use std::{2 io,3 path::{Path, PathBuf},4 time::Duration,5};67use grep::cli;8use grep::matcher::Matcher;7use {8 grep::{9 cli,10 matcher::Matcher,11 printer::{Standard, Stats, Summary, JSON},12 regex::RegexMatcher as RustRegexMatcher,13 searcher::{BinaryDetection, Searcher},14 },15 ignore::overrides::Override,16 serde_json::{self as json, json},17 termcolor::WriteColor,18};1920#[cfg(feature = "pcre2")]21use grep::pcre2::RegexMatcher as PCRE2RegexMatcher;11use grep::printer::{Standard, Stats, Summary, JSON};12use grep::regex::RegexMatcher as RustRegexMatcher;13use grep::searcher::{BinaryDetection, Searcher};14use ignore::overrides::Override;15use serde_json as json;16use serde_json::json;17use termcolor::WriteColor;2223use crate::subject::Subject;2425/// The configuration for the search worker. Among a few other things, the
373 unmodified lines
399 &mut self,400 path: &Path,401 ) -> io::Result<SearchResult> {402 let bin = self.config.preprocessor.as_ref().unwrap();399 let mut cmd = Command::new(bin);400 cmd.arg(path).stdin(Stdio::from(File::open(path)?));403 let mut cmd = std::process::Command::new(bin);404 cmd.arg(path)405 .stdin(std::process::Stdio::from(std::fs::File::open(path)?));406407 let mut rdr = self.command_builder.build(&mut cmd).map_err(|err| {408 io::Error::new(409 io::ErrorKind::Other,
144 unmodified lines
modified:crates/core/subject.rs+3 added-6 removed
1use std::path::Path;23use ignore::{self, DirEntry};4use log;53/// A configuration for describing how subjects should be built.4#[derive(Clone, Debug)]5struct Config {6 strip_dot_prefix: bool,
23 unmodified lines
30 /// logged if messages have been configured. Otherwise, if the subject is31 /// deemed searchable, then it is returned.32 pub fn build_from_result(33 &self,37 result: Result<DirEntry, ignore::Error>,34 result: Result<ignore::DirEntry, ignore::Error>,35 ) -> Option<Subject> {36 match result {37 Ok(dent) => self.build(dent),38 Err(err) => {
6 unmodified lines
45 /// Create a new subject using this builder's configuration.46 ///47 /// If a subject could not be created or should otherwise not be searched,48 /// then this returns `None` after emitting any relevant log messages.52 pub fn build(&self, dent: DirEntry) -> Option<Subject> {49 pub fn build(&self, dent: ignore::DirEntry) -> Option<Subject> {50 let subj =51 Subject { dent, strip_dot_prefix: self.config.strip_dot_prefix };52 if let Some(ignore_err) = subj.dent.error() {53 ignore_message!("{}", ignore_err);
38 unmodified lines
92/// A subject is a thing we want to search. Generally, a subject is either a93/// file or stdin.94#[derive(Clone, Debug)]95pub struct Subject {99 dent: DirEntry,96 dent: ignore::DirEntry,97 strip_dot_prefix: bool,98}99100impl Subject {
57 unmodified lines
modified:Cargo.toml+2 added-2 removed