Skip to content

Commit 392bb09

Browse files
committed
core: polish the core of ripgrep
This I believe finishes are quest to do mechanical updates to ripgrep's style, bringing it in line with my current practice (loosely speaking).
1 parent 90b8499 commit 392bb09

File tree

7 files changed

+111
-112
lines changed

7 files changed

+111
-112
lines changed

.github/workflows/ci.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ jobs:
5353
include:
5454
- build: pinned
5555
os: ubuntu-latest
56-
rust: 1.70.0
56+
rust: 1.72.1
5757
- build: stable
5858
os: ubuntu-latest
5959
rust: stable

Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ exclude = [
2323
]
2424
build = "build.rs"
2525
autotests = false
26-
edition = "2018"
27-
rust-version = "1.70"
26+
edition = "2021"
27+
rust-version = "1.72"
2828

2929
[[bin]]
3030
bench = false

crates/core/args.rs

+62-58
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,52 @@
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;
11-
12-
use clap;
13-
use grep::cli;
14-
use grep::matcher::LineTerminator;
1+
use std::{
2+
env,
3+
ffi::{OsStr, OsString},
4+
io::{self, IsTerminal, Write},
5+
path::{Path, PathBuf},
6+
sync::Arc,
7+
};
8+
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+
1536
#[cfg(feature = "pcre2")]
1637
use grep::pcre2::{
1738
RegexMatcher as PCRE2RegexMatcher,
1839
RegexMatcherBuilder as PCRE2RegexMatcherBuilder,
1940
};
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};
37-
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,
41+
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,
4449
};
45-
use crate::subject::{Subject, SubjectBuilder};
46-
use crate::Result;
4750

4851
/// The command that ripgrep should execute based on the command line
4952
/// configuration.
@@ -1130,16 +1133,17 @@ impl ArgMatches {
11301133
let mut env = HyperlinkEnvironment::new();
11311134
env.host(hostname(self.value_of_os("hostname-bin")))
11321135
.wsl_prefix(wsl_prefix());
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-
};
1136+
let fmt: HyperlinkFormat =
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+
};
11431147
log::debug!("hyperlink format: {:?}", fmt.to_string());
11441148
Ok(HyperlinkConfig::new(env, fmt))
11451149
}
@@ -1589,7 +1593,7 @@ impl ArgMatches {
15891593
let threads = self.usize_of("threads")?.unwrap_or(0);
15901594
let available =
15911595
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 })
15931597
}
15941598

15951599
/// Builds a file type matcher from the command line flags.
@@ -1790,11 +1794,11 @@ fn sort_by_option<T: Ord>(
17901794
p1: &Option<T>,
17911795
p2: &Option<T>,
17921796
reverse: bool,
1793-
) -> cmp::Ordering {
1797+
) -> std::cmp::Ordering {
17941798
match (p1, p2, reverse) {
17951799
(Some(p1), Some(p2), true) => p1.cmp(&p2).reverse(),
17961800
(Some(p1), Some(p2), false) => p1.cmp(&p2),
1797-
_ => cmp::Ordering::Equal,
1801+
_ => std::cmp::Ordering::Equal,
17981802
}
17991803
}
18001804

@@ -1823,7 +1827,7 @@ where
18231827
// (This is the point of this helper function. clap's functionality for
18241828
// doing this will panic on a broken pipe error.)
18251829
let _ = write!(io::stdout(), "{}", err);
1826-
process::exit(0);
1830+
std::process::exit(0);
18271831
}
18281832

18291833
/// Attempts to discover the current working directory. This mostly just defers
@@ -1871,8 +1875,8 @@ fn hostname(bin: Option<&OsStr>) -> Option<String> {
18711875
return platform_hostname();
18721876
}
18731877
};
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());
18761880
let rdr = match grep::cli::CommandReader::new(&mut cmd) {
18771881
Ok(rdr) => rdr,
18781882
Err(err) => {
@@ -1955,9 +1959,9 @@ fn wsl_prefix() -> Option<String> {
19551959
fn load_timestamps<G>(
19561960
subjects: impl Iterator<Item = Subject>,
19571961
get_time: G,
1958-
) -> Vec<(Option<SystemTime>, Subject)>
1962+
) -> Vec<(Option<std::time::SystemTime>, Subject)>
19591963
where
1960-
G: Fn(&fs::Metadata) -> io::Result<SystemTime>,
1964+
G: Fn(&std::fs::Metadata) -> io::Result<std::time::SystemTime>,
19611965
{
19621966
subjects
19631967
.map(|s| (s.path().metadata().and_then(|m| get_time(&m)).ok(), s))

crates/core/config.rs

+10-15
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,16 @@
22
// primary output of these routines is a sequence of arguments, where each
33
// argument corresponds precisely to one shell argument.
44

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+
};
119

1210
use bstr::{io::BufReadExt, ByteSlice};
13-
use log;
14-
15-
use crate::Result;
1611

1712
/// Return a sequence of arguments derived from ripgrep rc configuration files.
1813
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") {
2015
None => return vec![],
2116
Some(config_path) => {
2217
if config_path.is_empty() {
@@ -58,9 +53,9 @@ pub fn args() -> Vec<OsString> {
5853
/// for each line in addition to successfully parsed arguments.
5954
fn parse<P: AsRef<Path>>(
6055
path: P,
61-
) -> Result<(Vec<OsString>, Vec<Box<dyn Error>>)> {
56+
) -> crate::Result<(Vec<OsString>, Vec<Box<dyn std::error::Error>>)> {
6257
let path = path.as_ref();
63-
match File::open(&path) {
58+
match std::fs::File::open(&path) {
6459
Ok(file) => parse_reader(file),
6560
Err(err) => Err(From::from(format!("{}: {}", path.display(), err))),
6661
}
@@ -77,10 +72,10 @@ fn parse<P: AsRef<Path>>(
7772
/// If the reader could not be read, then an error is returned. If there was a
7873
/// problem parsing one or more lines, then errors are returned for each line
7974
/// in addition to successfully parsed arguments.
80-
fn parse_reader<R: io::Read>(
75+
fn parse_reader<R: std::io::Read>(
8176
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);
8479
let (mut args, mut errs) = (vec![], vec![]);
8580
let mut line_number = 0;
8681
bufrdr.for_byte_line_with_terminator(|line| {

crates/core/main.rs

+11-13
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
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+
};
65

76
use ignore::WalkState;
87

9-
use args::Args;
10-
use subject::Subject;
8+
use crate::{args::Args, subject::Subject};
119

1210
#[macro_use]
1311
mod messages;
@@ -42,12 +40,12 @@ mod subject;
4240
#[global_allocator]
4341
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
4442

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>>;
4644

4745
fn main() {
4846
if let Err(err) = Args::parse().and_then(try_main) {
4947
eprintln_locked!("{}", err);
50-
process::exit(2);
48+
std::process::exit(2);
5149
}
5250
}
5351

@@ -64,11 +62,11 @@ fn try_main(args: Args) -> Result<()> {
6462
PCRE2Version => pcre2_version(&args),
6563
}?;
6664
if matched && (args.quiet() || !messages::errored()) {
67-
process::exit(0)
65+
std::process::exit(0)
6866
} else if messages::errored() {
69-
process::exit(2)
67+
std::process::exit(2)
7068
} else {
71-
process::exit(1)
69+
std::process::exit(1)
7270
}
7371
}
7472

@@ -148,7 +146,7 @@ fn search_parallel(args: &Args) -> Result<bool> {
148146
let started_at = Instant::now();
149147
let subject_builder = args.subject_builder();
150148
let bufwtr = args.buffer_writer()?;
151-
let stats = args.stats()?.map(Mutex::new);
149+
let stats = args.stats()?.map(std::sync::Mutex::new);
152150
let matched = AtomicBool::new(false);
153151
let searched = AtomicBool::new(false);
154152
let mut searcher_err = None;

crates/core/search.rs

+22-17
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
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;
6-
7-
use grep::cli;
8-
use grep::matcher::Matcher;
1+
use std::{
2+
io,
3+
path::{Path, PathBuf},
4+
time::Duration,
5+
};
6+
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+
920
#[cfg(feature = "pcre2")]
1021
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;
1822

1923
use crate::subject::Subject;
2024

@@ -396,8 +400,9 @@ impl<W: WriteColor> SearchWorker<W> {
396400
path: &Path,
397401
) -> io::Result<SearchResult> {
398402
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)?));
401406

402407
let mut rdr = self.command_builder.build(&mut cmd).map_err(|err| {
403408
io::Error::new(

crates/core/subject.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
use std::path::Path;
22

3-
use ignore::{self, DirEntry};
4-
use log;
5-
63
/// A configuration for describing how subjects should be built.
74
#[derive(Clone, Debug)]
85
struct Config {
@@ -34,7 +31,7 @@ impl SubjectBuilder {
3431
/// deemed searchable, then it is returned.
3532
pub fn build_from_result(
3633
&self,
37-
result: Result<DirEntry, ignore::Error>,
34+
result: Result<ignore::DirEntry, ignore::Error>,
3835
) -> Option<Subject> {
3936
match result {
4037
Ok(dent) => self.build(dent),
@@ -49,7 +46,7 @@ impl SubjectBuilder {
4946
///
5047
/// If a subject could not be created or should otherwise not be searched,
5148
/// 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> {
5350
let subj =
5451
Subject { dent, strip_dot_prefix: self.config.strip_dot_prefix };
5552
if let Some(ignore_err) = subj.dent.error() {
@@ -96,7 +93,7 @@ impl SubjectBuilder {
9693
/// file or stdin.
9794
#[derive(Clone, Debug)]
9895
pub struct Subject {
99-
dent: DirEntry,
96+
dent: ignore::DirEntry,
10097
strip_dot_prefix: bool,
10198
}
10299

0 commit comments

Comments
 (0)