Skip to content
Myr

main.rs

This file

Path

crates/core/main.rs

489 lines · 18.2 KiB · Rust

Last changed by

index: add some initial indexing scaffoldingAndrew Gallantbefore adoption8372866

History of this file

Take it

1/*!2The main entry point into ripgrep.3*/45use std::{io::Write, process::ExitCode};67use ignore::WalkState;89use crate::flags::{HiArgs, SearchMode};1011#[macro_use]12mod messages;1314mod flags;15mod haystack;16mod index;17mod logger;18mod search;1920// Since Rust no longer uses jemalloc by default, ripgrep will, by default,21// use the system allocator. On Linux, this would normally be glibc's22// allocator, which is pretty good. In particular, ripgrep does not have a23// particularly allocation heavy workload, so there really isn't much24// difference (for ripgrep's purposes) between glibc's allocator and jemalloc.25//26// However, when ripgrep is built with musl, this means ripgrep will use musl's27// allocator, which appears to be substantially worse. (musl's goal is not to28// have the fastest version of everything. Its goal is to be small and amenable29// to static compilation.) Even though ripgrep isn't particularly allocation30// heavy, musl's allocator appears to slow down ripgrep quite a bit. Therefore,31// when building with musl, we use jemalloc.32//33// We don't unconditionally use jemalloc because it can be nice to use the34// system's default allocator by default. Moreover, jemalloc seems to increase35// compilation times by a bit.36//37// Moreover, we only do this on 64-bit systems since jemalloc doesn't support38// i686.39#[cfg(all(target_env = "musl", target_pointer_width = "64"))]40#[global_allocator]41static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;4243/// Then, as it was, then again it will be.44fn main() -> ExitCode {45    match run(flags::parse()) {46        Ok(code) => code,47        Err(err) => {48            // Look for a broken pipe error. In this case, we generally want49            // to exit "gracefully" with a success exit code. This matches50            // existing Unix convention. We need to handle this explicitly51            // since the Rust runtime doesn't ask for PIPE signals, and thus52            // we get an I/O error instead. Traditional C Unix applications53            // quit by getting a PIPE signal that they don't handle, and thus54            // the unhandled signal causes the process to unceremoniously55            // terminate.56            for cause in err.chain() {57                if let Some(ioerr) = cause.downcast_ref::<std::io::Error>() {58                    if ioerr.kind() == std::io::ErrorKind::BrokenPipe {59                        return ExitCode::from(0);60                    }61                }62            }63            eprintln_locked!("{:#}", err);64            ExitCode::from(2)65        }66    }67}6869/// The main entry point for ripgrep.70///71/// The given parse result determines ripgrep's behavior. The parse72/// result should be the result of parsing CLI arguments in a low level73/// representation, and then followed by an attempt to convert them into a74/// higher level representation. The higher level representation has some nicer75/// abstractions, for example, instead of representing the `-g/--glob` flag76/// as a `Vec<String>` (as in the low level representation), the globs are77/// converted into a single matcher.78fn run(result: crate::flags::ParseResult<HiArgs>) -> anyhow::Result<ExitCode> {79    use crate::flags::{Mode, ParseResult};8081    let args = match result {82        ParseResult::Err(err) => return Err(err),83        ParseResult::Special(mode) => return special(mode),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)?,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),99    };100    Ok(if matched && (args.quiet() || !messages::errored()) {101        ExitCode::from(0)102    } else if messages::errored() {103        ExitCode::from(2)104    } else {105        ExitCode::from(1)106    })107}108109/// The top-level entry point for single-threaded search.110///111/// This recursively steps through the file list (current directory by default)112/// and searches each file sequentially.113fn search(args: &HiArgs, mode: SearchMode) -> anyhow::Result<bool> {114    let started_at = std::time::Instant::now();115    let haystack_builder = args.haystack_builder();116    let unsorted = args117        .walk_builder()?118        .build()119        .filter_map(|result| haystack_builder.build_from_result(result));120    let haystacks = args.sort(unsorted);121122    let mut matched = false;123    let mut searched = false;124    let mut stats = args.stats();125    let mut searcher = args.search_worker(126        args.matcher()?,127        args.searcher()?,128        args.printer(mode, args.stdout()),129    )?;130    for haystack in haystacks {131        searched = true;132        let search_result = match searcher.search(&haystack) {133            Ok(search_result) => search_result,134            // A broken pipe means graceful termination.135            Err(err) if err.kind() == std::io::ErrorKind::BrokenPipe => break,136            Err(err) => {137                err_message!("{}: {}", haystack.path().display(), err);138                continue;139            }140        };141        matched = matched || search_result.has_match();142        if let Some(ref mut stats) = stats {143            *stats += search_result.stats().unwrap();144        }145        if matched && args.quit_after_match() {146            break;147        }148    }149    if args.has_implicit_path() && !searched {150        eprint_nothing_searched();151    }152    if let Some(ref stats) = stats {153        let wtr = searcher.printer().get_mut();154        let _ = print_stats(mode, stats, started_at, wtr);155    }156    Ok(matched)157}158159/// The top-level entry point for multi-threaded search.160///161/// The parallelism is itself achieved by the recursive directory traversal.162/// All we need to do is feed it a worker for performing a search on each file.163///164/// Requesting a sorted output from ripgrep (such as with `--sort path`) will165/// automatically disable parallelism and hence sorting is not handled here.166fn search_parallel(args: &HiArgs, mode: SearchMode) -> anyhow::Result<bool> {167    use std::sync::atomic::{AtomicBool, Ordering};168169    let started_at = std::time::Instant::now();170    let haystack_builder = args.haystack_builder();171    let bufwtr = args.buffer_writer();172    let stats = args.stats().map(std::sync::Mutex::new);173    let matched = AtomicBool::new(false);174    let searched = AtomicBool::new(false);175176    let mut searcher = args.search_worker(177        args.matcher()?,178        args.searcher()?,179        args.printer(mode, bufwtr.buffer()),180    )?;181    args.walk_builder()?.build_parallel().run(|| {182        let bufwtr = &bufwtr;183        let stats = &stats;184        let matched = &matched;185        let searched = &searched;186        let haystack_builder = &haystack_builder;187        let mut searcher = searcher.clone();188189        Box::new(move |result| {190            let haystack = match haystack_builder.build_from_result(result) {191                Some(haystack) => haystack,192                None => return WalkState::Continue,193            };194            searched.store(true, Ordering::SeqCst);195            searcher.printer().get_mut().clear();196            let search_result = match searcher.search(&haystack) {197                Ok(search_result) => search_result,198                Err(err) => {199                    err_message!("{}: {}", haystack.path().display(), err);200                    return WalkState::Continue;201                }202            };203            if search_result.has_match() {204                matched.store(true, Ordering::SeqCst);205            }206            if let Some(ref locked_stats) = *stats {207                let mut stats = locked_stats.lock().unwrap();208                *stats += search_result.stats().unwrap();209            }210            if let Err(err) = bufwtr.print(searcher.printer().get_mut()) {211                // A broken pipe means graceful termination.212                if err.kind() == std::io::ErrorKind::BrokenPipe {213                    return WalkState::Quit;214                }215                // Otherwise, we continue on our merry way.216                err_message!("{}: {}", haystack.path().display(), err);217            }218            if matched.load(Ordering::SeqCst) && args.quit_after_match() {219                WalkState::Quit220            } else {221                WalkState::Continue222            }223        })224    });225    if args.has_implicit_path() && !searched.load(Ordering::SeqCst) {226        eprint_nothing_searched();227    }228    if let Some(ref locked_stats) = stats {229        let stats = locked_stats.lock().unwrap();230        let mut wtr = searcher.printer().get_mut();231        let _ = print_stats(mode, &stats, started_at, &mut wtr);232        let _ = bufwtr.print(&mut wtr);233    }234    Ok(matched.load(Ordering::SeqCst))235}236237/// The top-level entry point for file listing without searching.238///239/// This recursively steps through the file list (current directory by default)240/// and prints each path sequentially using a single thread.241fn files(args: &HiArgs) -> anyhow::Result<bool> {242    let haystack_builder = args.haystack_builder();243    let unsorted = args244        .walk_builder()?245        .build()246        .filter_map(|result| haystack_builder.build_from_result(result));247    let haystacks = args.sort(unsorted);248249    let mut matched = false;250    let mut path_printer = args.path_printer_builder().build(args.stdout());251    for haystack in haystacks {252        matched = true;253        if args.quit_after_match() {254            break;255        }256        if let Err(err) = path_printer.write(haystack.path()) {257            // A broken pipe means graceful termination.258            if err.kind() == std::io::ErrorKind::BrokenPipe {259                break;260            }261            // Otherwise, we have some other error that's preventing us from262            // writing to stdout, so we should bubble it up.263            return Err(err.into());264        }265    }266    Ok(matched)267}268269/// The top-level entry point for multi-threaded file listing without270/// searching.271///272/// This recursively steps through the file list (current directory by default)273/// and prints each path sequentially using multiple threads.274///275/// Requesting a sorted output from ripgrep (such as with `--sort path`) will276/// automatically disable parallelism and hence sorting is not handled here.277fn files_parallel(args: &HiArgs) -> anyhow::Result<bool> {278    use std::{279        sync::{280            atomic::{AtomicBool, Ordering},281            mpsc,282        },283        thread,284    };285286    let haystack_builder = args.haystack_builder();287    let mut path_printer = args.path_printer_builder().build(args.stdout());288    let matched = AtomicBool::new(false);289    let (tx, rx) = mpsc::channel::<crate::haystack::Haystack>();290291    // We spawn a single printing thread to make sure we don't tear writes.292    // We use a channel here under the presumption that it's probably faster293    // than using a mutex in the worker threads below, but this has never been294    // seriously litigated.295    let print_thread = thread::spawn(move || -> std::io::Result<()> {296        for haystack in rx.iter() {297            path_printer.write(haystack.path())?;298        }299        Ok(())300    });301    args.walk_builder()?.build_parallel().run(|| {302        let haystack_builder = &haystack_builder;303        let matched = &matched;304        let tx = tx.clone();305306        Box::new(move |result| {307            let haystack = match haystack_builder.build_from_result(result) {308                Some(haystack) => haystack,309                None => return WalkState::Continue,310            };311            matched.store(true, Ordering::SeqCst);312            if args.quit_after_match() {313                WalkState::Quit314            } else {315                match tx.send(haystack) {316                    Ok(_) => WalkState::Continue,317                    Err(_) => WalkState::Quit,318                }319            }320        })321    });322    drop(tx);323    if let Err(err) = print_thread.join().unwrap() {324        // A broken pipe means graceful termination, so fall through.325        // Otherwise, something bad happened while writing to stdout, so bubble326        // it up.327        if err.kind() != std::io::ErrorKind::BrokenPipe {328            return Err(err.into());329        }330    }331    Ok(matched.load(Ordering::SeqCst))332}333334/// The top-level entry point for `--type-list`.335fn types(args: &HiArgs) -> anyhow::Result<ExitCode> {336    let mut count = 0;337    let mut stdout = args.stdout();338    for def in args.types().definitions() {339        count += 1;340        stdout.write_all(def.name().as_bytes())?;341        stdout.write_all(b": ")?;342343        let mut first = true;344        for glob in def.globs() {345            if !first {346                stdout.write_all(b", ")?;347            }348            stdout.write_all(glob.as_bytes())?;349            first = false;350        }351        stdout.write_all(b"\n")?;352    }353    Ok(ExitCode::from(if count == 0 { 1 } else { 0 }))354}355356/// Implements ripgrep's "generate" modes.357///358/// These modes correspond to generating some kind of ancillary data related359/// to ripgrep. At present, this includes ripgrep's man page (in roff format)360/// and supported shell completions.361fn generate(mode: crate::flags::GenerateMode) -> anyhow::Result<ExitCode> {362    use crate::flags::GenerateMode;363364    let output = match mode {365        GenerateMode::Man => flags::generate_man_page(),366        GenerateMode::CompleteBash => flags::generate_complete_bash(),367        GenerateMode::CompleteZsh => flags::generate_complete_zsh(),368        GenerateMode::CompleteFish => flags::generate_complete_fish(),369        GenerateMode::CompletePowerShell => {370            flags::generate_complete_powershell()371        }372    };373    writeln!(std::io::stdout(), "{}", output.trim_end())?;374    Ok(ExitCode::from(0))375}376377/// Implements ripgrep's "special" modes.378///379/// A special mode is one that generally short-circuits most (not all) of380/// ripgrep's initialization logic and skips right to this routine. The381/// special modes essentially consist of printing help and version output. The382/// idea behind the short circuiting is to ensure there is as little as possible383/// (within reason) that would prevent ripgrep from emitting help output.384///385/// For example, part of the initialization logic that is skipped (among386/// other things) is accessing the current working directory. If that fails,387/// ripgrep emits an error. We don't want to emit an error if it fails and388/// the user requested version or help information.389fn special(mode: crate::flags::SpecialMode) -> anyhow::Result<ExitCode> {390    use crate::flags::SpecialMode;391392    let mut exit = ExitCode::from(0);393    let output = match mode {394        SpecialMode::HelpShort => flags::generate_help_short(),395        SpecialMode::HelpLong => flags::generate_help_long(),396        SpecialMode::VersionShort => flags::generate_version_short(),397        SpecialMode::VersionLong => flags::generate_version_long(),398        // --pcre2-version is a little special because it emits an error399        // exit code if this build of ripgrep doesn't support PCRE2.400        SpecialMode::VersionPCRE2 => {401            let (output, available) = flags::generate_version_pcre2();402            if !available {403                exit = ExitCode::from(1);404            }405            output406        }407    };408    writeln!(std::io::stdout(), "{}", output.trim_end())?;409    Ok(exit)410}411412/// Prints a heuristic error messages when nothing is searched.413///414/// This can happen if an applicable ignore file has one or more rules that415/// are too broad and cause ripgrep to ignore everything.416///417/// We only show this error message when the user does *not* provide an418/// explicit path to search. This is because the message can otherwise be419/// noisy, e.g., when it is intended that there is nothing to search.420fn eprint_nothing_searched() {421    err_message!(422        "No files were searched, which means ripgrep probably \423         applied a filter you didn't expect.\n\424         Running with --debug will show why files are being skipped."425    );426}427428/// Prints the statistics given to the writer given.429///430/// The search mode given determines whether the stats should be printed in431/// a plain text format or in a JSON format.432///433/// The `started` time should be the time at which ripgrep started working.434///435/// If an error occurs while writing, then writing stops and the error is436/// returned. Note that callers should probably ignore this error, since437/// whether stats fail to print or not generally shouldn't cause ripgrep to438/// enter into an "error" state. And usually the only way for this to fail is439/// if writing to stdout itself fails.440fn print_stats<W: Write>(441    mode: SearchMode,442    stats: &grep::printer::Stats,443    started: std::time::Instant,444    mut wtr: W,445) -> std::io::Result<()> {446    let elapsed = std::time::Instant::now().duration_since(started);447    if matches!(mode, SearchMode::JSON) {448        // We specifically match the format laid out by the JSON printer in449        // the grep-printer crate. We simply "extend" it with the 'summary'450        // message type.451        serde_json::to_writer(452            &mut wtr,453            &serde_json::json!({454                "type": "summary",455                "data": {456                    "stats": stats,457                    "elapsed_total": {458                        "secs": elapsed.as_secs(),459                        "nanos": elapsed.subsec_nanos(),460                        "human": format!("{:0.6}s", elapsed.as_secs_f64()),461                    },462                }463            }),464        )?;465        write!(wtr, "\n")466    } else {467        write!(468            wtr,469            "470{matches} matches471{lines} matched lines472{searches_with_match} files contained matches473{searches} files searched474{bytes_printed} bytes printed475{bytes_searched} bytes searched476{search_time:0.6} seconds spent searching477{process_time:0.6} seconds total478",479            matches = stats.matches(),480            lines = stats.matched_lines(),481            searches_with_match = stats.searches_with_match(),482            searches = stats.searches(),483            bytes_printed = stats.bytes_printed(),484            bytes_searched = stats.bytes_searched(),485            search_time = stats.elapsed().as_secs_f64(),486            process_time = elapsed.as_secs_f64(),487        )488    }489}