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
Provenance
- Commit
392bb09- Tree
c449ae9- Author
Andrew Gallant <jamslam@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
90b8499
7 files changed+108 added−109 removed
modified:.github/workflows/ci.yml+1 added-1 removed
51 unmodified lines52 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: beta165 unmodified linesmodified:crates/core/args.rs+60 added-56 removed
1-use std::cmp;2-use std::env;3-use std::ffi::{OsStr, OsString};4-use std::fs;5-use std::io::{self, IsTerminal, Write};6-use std::path::{Path, PathBuf};7-use std::process;8-use std::str::FromStr;9-use std::sync::Arc;10-use std::time::SystemTime;1+use std::{2+ env,3+ ffi::{OsStr, OsString},4+ io::{self, IsTerminal, Write},5+ path::{Path, PathBuf},6+ sync::Arc,7+};8 12-use clap;13-use grep::cli;14-use grep::matcher::LineTerminator;9+use {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+};35+36 #[cfg(feature = "pcre2")]37 use grep::pcre2::{38 RegexMatcher as PCRE2RegexMatcher,39 RegexMatcherBuilder as PCRE2RegexMatcherBuilder,40 };20-use grep::printer::{21- default_color_specs, ColorSpecs, HyperlinkConfig, HyperlinkEnvironment,22- HyperlinkFormat, JSONBuilder, PathPrinter, PathPrinterBuilder, Standard,23- StandardBuilder, Stats, Summary, SummaryBuilder, SummaryKind, JSON,24-};25-use grep::regex::{26- RegexMatcher as RustRegexMatcher,27- RegexMatcherBuilder as RustRegexMatcherBuilder,28-};29-use grep::searcher::{30- BinaryDetection, Encoding, MmapChoice, Searcher, SearcherBuilder,31-};32-use ignore::overrides::{Override, OverrideBuilder};33-use ignore::types::{FileTypeDef, Types, TypesBuilder};34-use ignore::{Walk, WalkBuilder, WalkParallel};35-use log;36-use termcolor::{BufferWriter, ColorChoice, WriteColor};41 38-use crate::app;39-use crate::config;40-use crate::logger::Logger;41-use crate::messages::{set_ignore_messages, set_messages};42-use crate::search::{43- PatternMatcher, Printer, SearchWorker, SearchWorkerBuilder,42+use 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 };45-use crate::subject::{Subject, SubjectBuilder};46-use crate::Result;50 51 /// The command that ripgrep should execute based on the command line52 /// configuration.53 #[derive(Clone, Copy, Debug, Eq, PartialEq)]1078 unmodified lines1132 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 lines1592 }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 }1598 1599 /// Builds a file type matcher from the command line flags.1600 fn types(&self) -> Result<Types> {192 unmodified lines1793 fn 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 }1804 1805 /// Returns a clap matches object if the given arguments parse successfully.20 unmodified lines1826 //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 }1832 1833 /// Attempts to discover the current working directory. This mostly just defers1834 /// to the standard library, however, such things will fail if ripgrep is in39 unmodified lines1874 );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 lines1958 /// sorting Subjects by time.1959 fn 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)>1963 where1960- 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 linemodified: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.4 5-use std::env;6-use std::error::Error;7-use std::ffi::OsString;8-use std::fs::File;9-use std::io;10-use std::path::{Path, PathBuf};5+use std::{6+ ffi::OsString,7+ path::{Path, PathBuf},8+};9 10 use bstr::{io::BufReadExt, ByteSlice};13-use log;11 15-use crate::Result;16-12 /// Return a sequence of arguments derived from ripgrep rc configuration files.13 pub 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 lines52 /// a problem parsing one or more lines in the file, then errors are returned53 /// for each line in addition to successfully parsed arguments.54 fn 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 lines71 ///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.80-fn parse_reader<R: io::Read>(75+fn 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 linesmodified:crates/core/main.rs+11 added-13 removed
1-use std::error;2-use std::io::{self, Write};3-use std::process;4-use std::sync::Mutex;5-use std::time::Instant;1+use std::{2+ io::{self, Write},3+ time::Instant,4+};5 6 use ignore::WalkState;7 9-use args::Args;10-use subject::Subject;8+use crate::{args::Args, subject::Subject};9 10 #[macro_use]11 mod messages;12 26 unmodified lines39 #[cfg(all(target_env = "musl", target_pointer_width = "64"))]40 #[global_allocator]41 static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;42 45-type Result<T> = ::std::result::Result<T, Box<dyn error::Error>>;43+type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;44 45 fn 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 }51 52 fn try_main(args: Args) -> Result<()> {8 unmodified lines61 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 }72 73 /// The top-level entry point for single-threaded search. This recursively71 unmodified lines145 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 linesmodified:crates/core/search.rs+21 added-16 removed
1-use std::fs::File;2-use std::io;3-use std::path::{Path, PathBuf};4-use std::process::{Command, Stdio};5-use std::time::Duration;1+use std::{2+ io,3+ path::{Path, PathBuf},4+ time::Duration,5+};6 7-use grep::cli;8-use grep::matcher::Matcher;7+use {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+};19+20 #[cfg(feature = "pcre2")]21 use grep::pcre2::RegexMatcher as PCRE2RegexMatcher;11-use grep::printer::{Standard, Stats, Summary, JSON};12-use grep::regex::RegexMatcher as RustRegexMatcher;13-use grep::searcher::{BinaryDetection, Searcher};14-use ignore::overrides::Override;15-use serde_json as json;16-use serde_json::json;17-use termcolor::WriteColor;22 23 use crate::subject::Subject;24 25 /// The configuration for the search worker. Among a few other things, the373 unmodified lines399 &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)?));406 407 let mut rdr = self.command_builder.build(&mut cmd).map_err(|err| {408 io::Error::new(409 io::ErrorKind::Other,144 unmodified linesmodified:crates/core/subject.rs+3 added-6 removed
1 use std::path::Path;2 3-use ignore::{self, DirEntry};4-use log;5-3 /// A configuration for describing how subjects should be built.4 #[derive(Clone, Debug)]5 struct Config {6 strip_dot_prefix: bool,23 unmodified lines30 /// 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 lines45 /// 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 lines92 /// A subject is a thing we want to search. Generally, a subject is either a93 /// file or stdin.94 #[derive(Clone, Debug)]95 pub struct Subject {99- dent: DirEntry,96+ dent: ignore::DirEntry,97 strip_dot_prefix: bool,98 }99 100 impl Subject {57 unmodified linesmodified:Cargo.toml+2 added-2 removed
21 unmodified lines22232425262726272829303178 unmodified lines21 unmodified lines "/scripts/",]build = "build.rs"autotests = falseedition = "2018"rust-version = "1.70"edition = "2021"rust-version = "1.72"
[[bin]]bench = falsepath = "crates/core/main.rs"78 unmodified lines