Skip to content
Myr

main.rs

This file

Path

src/main.rs

165 lines · 5.1 KiB · Rust

Last changed by

Move 'win' crate back into local modulesharkdpbefore adoptionb3f1e18

History of this file

Take it

1// Copyright (c) 2017 fd developers2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.89extern crate ansi_term;10extern crate atty;11#[macro_use]12extern crate clap;13extern crate ignore;14#[macro_use]15extern crate lazy_static;16#[cfg(all(unix, not(target_os = "redox")))]17extern crate libc;18extern crate num_cpus;19extern crate regex;20extern crate regex_syntax;21extern crate shell_escape;2223pub mod fshelper;24pub mod lscolors;25mod app;26mod exec;27mod internal;28mod output;29mod walk;3031#[cfg(windows)]32mod windows;3334use std::env;35use std::error::Error;36use std::path::{Path, PathBuf};37use std::sync::Arc;38use std::time;3940use atty::Stream;41use regex::RegexBuilder;4243use exec::TokenizedCommand;44use internal::{error, pattern_has_uppercase_char, FdOptions, PathDisplay};45use lscolors::LsColors;46use walk::FileType;4748fn main() {49    let matches = app::build_app().get_matches();5051    // Get the search pattern52    let empty_pattern = String::new();53    let pattern = matches.value_of("pattern").unwrap_or(&empty_pattern);5455    // Get the current working directory56    let current_dir = Path::new(".");57    if !fshelper::is_dir(current_dir) {58        error("Error: could not get current directory.");59    }6061    // Get the root directory for the search62    let mut root_dir_buf = match matches.value_of("path") {63        Some(path) => {64            #[cfg(windows)]65            let path = path.replace('/', "\\");6667            PathBuf::from(path)68        }69        None => current_dir.to_path_buf(),70    };71    if !fshelper::is_dir(&root_dir_buf) {72        error(&format!(73            "Error: '{}' is not a directory.",74            root_dir_buf.to_string_lossy()75        ));76    }7778    let path_display = if matches.is_present("absolute-path") || root_dir_buf.is_absolute() {79        PathDisplay::Absolute80    } else {81        PathDisplay::Relative82    };8384    if path_display == PathDisplay::Absolute && root_dir_buf.is_relative() {85        root_dir_buf = fshelper::absolute_path(root_dir_buf.as_path()).unwrap();86    }87    let root_dir = root_dir_buf.as_path();8889    // The search will be case-sensitive if the command line flag is set or90    // if the pattern has an uppercase character (smart case).91    let case_sensitive = !matches.is_present("ignore-case") &&92        (matches.is_present("case-sensitive") || pattern_has_uppercase_char(pattern));9394    let colored_output = match matches.value_of("color") {95        Some("always") => true,96        Some("never") => false,97        _ => atty::is(Stream::Stdout),98    };99100    #[cfg(windows)]101    let colored_output = colored_output && windows::enable_colored_output();102103    let ls_colors = if colored_output {104        Some(105            env::var("LS_COLORS")106                .ok()107                .map(|val| LsColors::from_string(&val))108                .unwrap_or_default(),109        )110    } else {111        None112    };113114    let command = matches.value_of("exec").map(|x| TokenizedCommand::new(x));115116    let config = FdOptions {117        case_sensitive,118        search_full_path: matches.is_present("full-path"),119        ignore_hidden: !(matches.is_present("hidden") ||120                             matches.occurrences_of("rg-alias-hidden-ignore") >= 2),121        read_ignore: !(matches.is_present("no-ignore") ||122                           matches.is_present("rg-alias-hidden-ignore")),123        follow_links: matches.is_present("follow"),124        null_separator: matches.is_present("null_separator"),125        max_depth: matches.value_of("depth").and_then(|n| {126            usize::from_str_radix(n, 10).ok()127        }),128        threads: std::cmp::max(129            matches130                .value_of("threads")131                .and_then(|n| usize::from_str_radix(n, 10).ok())132                .unwrap_or_else(num_cpus::get),133            1,134        ),135        max_buffer_time: matches136            .value_of("max-buffer-time")137            .and_then(|n| u64::from_str_radix(n, 10).ok())138            .map(time::Duration::from_millis),139        path_display,140        ls_colors,141        file_type: match matches.value_of("file-type") {142            Some("f") | Some("file") => FileType::RegularFile,143            Some("d") |144            Some("directory") => FileType::Directory,145            Some("l") | Some("symlink") => FileType::SymLink,146            _ => FileType::Any,147        },148        extension: matches.value_of("extension").map(|e| {149            e.trim_left_matches('.').to_lowercase()150        }),151        command,152        exclude_patterns: matches153            .values_of("exclude")154            .map(|v| v.map(|p| String::from("!") + p).collect())155            .unwrap_or_else(|| vec![]),156    };157158    match RegexBuilder::new(pattern)159        .case_insensitive(!config.case_sensitive)160        .dot_matches_new_line(true)161        .build() {162        Ok(re) => walk::scan(root_dir, Arc::new(re), Arc::new(config)),163        Err(err) => error(err.description()),164    }165}