Split internals.rs into module and multiple files
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This PR splits `internals.rs` into the `internal` module with multiple files, and moves `FdOptions` into `opts.rs`. The main motivation behind this is to move logic for constructing `FdOptions` out of the main function and more readable and easier to understand in the `opts` module. The goal will eventually to be able to write `FdOptions::from(matches)` and have the options constructed.
authored by Josh Leeb-du Toit · committed by David Peter · parent 984f04f · Browse files · 10 files·+593 added−572 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+593 added−572 removed
- other:+593 added−572 removed
Provenance
- Commit
8543ca6- Tree
88dc191- Author
Josh Leeb-du Toit <josh.leebdutoit@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
984f04f
10 files changed+593 added−572 removed
added:src/internal/filter/mod.rs+5 added
1+pub use self::size::SizeFilter;2+pub use self::time::TimeFilter;3+4+mod size;5+mod time;added:src/internal/filter/size.rs+208 added
1+use regex::Regex;2+3+lazy_static! {4+ static ref SIZE_CAPTURES: Regex = { Regex::new(r"(?i)^([+-])(\d+)(b|[kmgt]i?b?)$").unwrap() };5+}6+7+#[derive(Clone, Copy, Debug, PartialEq)]8+pub enum SizeFilter {9+ Max(u64),10+ Min(u64),11+}12+13+// SI prefixes (powers of 10)14+const KILO: u64 = 1000;15+const MEGA: u64 = KILO * 1000;16+const GIGA: u64 = MEGA * 1000;17+const TERA: u64 = GIGA * 1000;18+19+// Binary prefixes (powers of 2)20+const KIBI: u64 = 1024;21+const MEBI: u64 = KIBI * 1024;22+const GIBI: u64 = MEBI * 1024;23+const TEBI: u64 = GIBI * 1024;24+25+impl SizeFilter {26+ pub fn from_string<'a>(s: &str) -> Option<Self> {27+ if !SIZE_CAPTURES.is_match(s) {28+ return None;29+ }30+31+ let captures = SIZE_CAPTURES.captures(s)?;32+ let limit_kind = captures.get(1).map_or("+", |m| m.as_str());33+ let quantity = captures34+ .get(2)35+ .and_then(|v| v.as_str().parse::<u64>().ok())?;36+37+ let multiplier = match &captures.get(3).map_or("b", |m| m.as_str()).to_lowercase()[..] {38+ v if v.starts_with("ki") => KIBI,39+ v if v.starts_with("k") => KILO,40+ v if v.starts_with("mi") => MEBI,41+ v if v.starts_with("m") => MEGA,42+ v if v.starts_with("gi") => GIBI,43+ v if v.starts_with("g") => GIGA,44+ v if v.starts_with("ti") => TEBI,45+ v if v.starts_with("t") => TERA,46+ "b" => 1,47+ _ => return None,48+ };49+50+ let size = quantity * multiplier;51+ Some(match limit_kind {52+ "+" => SizeFilter::Min(size),53+ _ => SizeFilter::Max(size),54+ })55+ }56+57+ pub fn is_within(&self, size: u64) -> bool {58+ match self {59+ &SizeFilter::Max(limit) => size <= limit,60+ &SizeFilter::Min(limit) => size >= limit,61+ }62+ }63+}64+65+#[cfg(test)]66+mod tests {67+ use super::*;68+69+ macro_rules! gen_size_filter_parse_test {70+ ($($name: ident: $val: expr,)*) => {71+ $(72+ #[test]73+ fn $name() {74+ let (txt, expected) = $val;75+ let actual = SizeFilter::from_string(txt).unwrap();76+ assert_eq!(actual, expected);77+ }78+ )*79+ };80+ }81+82+ /// Parsing and size conversion tests data. Ensure that each type gets properly interpreted.83+ /// Call with higher base values to ensure expected multiplication (only need a couple)84+ gen_size_filter_parse_test! {85+ byte_plus: ("+1b", SizeFilter::Min(1)),86+ byte_plus_multiplier: ("+10b", SizeFilter::Min(10)),87+ byte_minus: ("-1b", SizeFilter::Max(1)),88+ kilo_plus: ("+1k", SizeFilter::Min(1000)),89+ kilo_plus_suffix: ("+1kb", SizeFilter::Min(1000)),90+ kilo_minus: ("-1k", SizeFilter::Max(1000)),91+ kilo_minus_multiplier: ("-100k", SizeFilter::Max(100000)),92+ kilo_minus_suffix: ("-1kb", SizeFilter::Max(1000)),93+ kilo_plus_upper: ("+1K", SizeFilter::Min(1000)),94+ kilo_plus_suffix_upper: ("+1KB", SizeFilter::Min(1000)),95+ kilo_minus_upper: ("-1K", SizeFilter::Max(1000)),96+ kilo_minus_suffix_upper: ("-1Kb", SizeFilter::Max(1000)),97+ kibi_plus: ("+1ki", SizeFilter::Min(1024)),98+ kibi_plus_multiplier: ("+10ki", SizeFilter::Min(10240)),99+ kibi_plus_suffix: ("+1kib", SizeFilter::Min(1024)),100+ kibi_minus: ("-1ki", SizeFilter::Max(1024)),101+ kibi_minus_multiplier: ("-100ki", SizeFilter::Max(102400)),102+ kibi_minus_suffix: ("-1kib", SizeFilter::Max(1024)),103+ kibi_plus_upper: ("+1KI", SizeFilter::Min(1024)),104+ kibi_plus_suffix_upper: ("+1KiB", SizeFilter::Min(1024)),105+ kibi_minus_upper: ("-1Ki", SizeFilter::Max(1024)),106+ kibi_minus_suffix_upper: ("-1KIB", SizeFilter::Max(1024)),107+ mega_plus: ("+1m", SizeFilter::Min(1000000)),108+ mega_plus_suffix: ("+1mb", SizeFilter::Min(1000000)),109+ mega_minus: ("-1m", SizeFilter::Max(1000000)),110+ mega_minus_suffix: ("-1mb", SizeFilter::Max(1000000)),111+ mega_plus_upper: ("+1M", SizeFilter::Min(1000000)),112+ mega_plus_suffix_upper: ("+1MB", SizeFilter::Min(1000000)),113+ mega_minus_upper: ("-1M", SizeFilter::Max(1000000)),114+ mega_minus_suffix_upper: ("-1Mb", SizeFilter::Max(1000000)),115+ mebi_plus: ("+1mi", SizeFilter::Min(1048576)),116+ mebi_plus_suffix: ("+1mib", SizeFilter::Min(1048576)),117+ mebi_minus: ("-1mi", SizeFilter::Max(1048576)),118+ mebi_minus_suffix: ("-1mib", SizeFilter::Max(1048576)),119+ mebi_plus_upper: ("+1MI", SizeFilter::Min(1048576)),120+ mebi_plus_suffix_upper: ("+1MiB", SizeFilter::Min(1048576)),121+ mebi_minus_upper: ("-1Mi", SizeFilter::Max(1048576)),122+ mebi_minus_suffix_upper: ("-1MIB", SizeFilter::Max(1048576)),123+ giga_plus: ("+1g", SizeFilter::Min(1000000000)),124+ giga_plus_suffix: ("+1gb", SizeFilter::Min(1000000000)),125+ giga_minus: ("-1g", SizeFilter::Max(1000000000)),126+ giga_minus_suffix: ("-1gb", SizeFilter::Max(1000000000)),127+ giga_plus_upper: ("+1G", SizeFilter::Min(1000000000)),128+ giga_plus_suffix_upper: ("+1GB", SizeFilter::Min(1000000000)),129+ giga_minus_upper: ("-1G", SizeFilter::Max(1000000000)),130+ giga_minus_suffix_upper: ("-1Gb", SizeFilter::Max(1000000000)),131+ gibi_plus: ("+1gi", SizeFilter::Min(1073741824)),132+ gibi_plus_suffix: ("+1gib", SizeFilter::Min(1073741824)),133+ gibi_minus: ("-1gi", SizeFilter::Max(1073741824)),134+ gibi_minus_suffix: ("-1gib", SizeFilter::Max(1073741824)),135+ gibi_plus_upper: ("+1GI", SizeFilter::Min(1073741824)),136+ gibi_plus_suffix_upper: ("+1GiB", SizeFilter::Min(1073741824)),137+ gibi_minus_upper: ("-1Gi", SizeFilter::Max(1073741824)),138+ gibi_minus_suffix_upper: ("-1GIB", SizeFilter::Max(1073741824)),139+ tera_plus: ("+1t", SizeFilter::Min(1000000000000)),140+ tera_plus_suffix: ("+1tb", SizeFilter::Min(1000000000000)),141+ tera_minus: ("-1t", SizeFilter::Max(1000000000000)),142+ tera_minus_suffix: ("-1tb", SizeFilter::Max(1000000000000)),143+ tera_plus_upper: ("+1T", SizeFilter::Min(1000000000000)),144+ tera_plus_suffix_upper: ("+1TB", SizeFilter::Min(1000000000000)),145+ tera_minus_upper: ("-1T", SizeFilter::Max(1000000000000)),146+ tera_minus_suffix_upper: ("-1Tb", SizeFilter::Max(1000000000000)),147+ tebi_plus: ("+1ti", SizeFilter::Min(1099511627776)),148+ tebi_plus_suffix: ("+1tib", SizeFilter::Min(1099511627776)),149+ tebi_minus: ("-1ti", SizeFilter::Max(1099511627776)),150+ tebi_minus_suffix: ("-1tib", SizeFilter::Max(1099511627776)),151+ tebi_plus_upper: ("+1TI", SizeFilter::Min(1099511627776)),152+ tebi_plus_suffix_upper: ("+1TiB", SizeFilter::Min(1099511627776)),153+ tebi_minus_upper: ("-1Ti", SizeFilter::Max(1099511627776)),154+ tebi_minus_suffix_upper: ("-1TIB", SizeFilter::Max(1099511627776)),155+ }156+157+ /// Invalid parse testing158+ macro_rules! gen_size_filter_failure {159+ ($($name:ident: $value:expr,)*) => {160+ $(161+ #[test]162+ fn $name() {163+ let i = SizeFilter::from_string($value);164+ assert!(i.is_none());165+ }166+ )*167+ };168+ }169+170+ /// Invalid parse data171+ gen_size_filter_failure! {172+ ensure_missing_symbol_returns_none: "10M",173+ ensure_missing_number_returns_none: "+g",174+ ensure_missing_unit_returns_none: "+18",175+ ensure_bad_format_returns_none_1: "$10M",176+ ensure_bad_format_returns_none_2: "badval",177+ ensure_bad_format_returns_none_3: "9999",178+ ensure_invalid_unit_returns_none_1: "+50a",179+ ensure_invalid_unit_returns_none_2: "-10v",180+ ensure_invalid_unit_returns_none_3: "+1Mv",181+ ensure_bib_format_returns_none: "+1bib",182+ ensure_bb_format_returns_none: "+1bb",183+ }184+185+ #[test]186+ fn is_within_less_than() {187+ let f = SizeFilter::from_string("-1k").unwrap();188+ assert!(f.is_within(999));189+ }190+191+ #[test]192+ fn is_within_less_than_equal() {193+ let f = SizeFilter::from_string("-1k").unwrap();194+ assert!(f.is_within(1000));195+ }196+197+ #[test]198+ fn is_within_greater_than() {199+ let f = SizeFilter::from_string("+1k").unwrap();200+ assert!(f.is_within(1001));201+ }202+203+ #[test]204+ fn is_within_greater_than_equal() {205+ let f = SizeFilter::from_string("+1K").unwrap();206+ assert!(f.is_within(1000));207+ }208+}added:src/internal/filter/time.rs+102 added
1+use std::time::SystemTime;2+3+/// Filter based on time ranges.4+#[derive(Debug, PartialEq)]5+pub enum TimeFilter {6+ Before(SystemTime),7+ After(SystemTime),8+}9+10+impl TimeFilter {11+ fn from_str(ref_time: &SystemTime, s: &str) -> Option<SystemTime> {12+ use humantime;13+ humantime::parse_duration(s)14+ .map(|duration| *ref_time - duration)15+ .or_else(|_| humantime::parse_rfc3339_weak(s))16+ .ok()17+ }18+19+ pub fn before(ref_time: &SystemTime, s: &str) -> Option<TimeFilter> {20+ TimeFilter::from_str(ref_time, s).map(TimeFilter::Before)21+ }22+23+ pub fn after(ref_time: &SystemTime, s: &str) -> Option<TimeFilter> {24+ TimeFilter::from_str(ref_time, s).map(TimeFilter::After)25+ }26+27+ pub fn applies_to(&self, t: &SystemTime) -> bool {28+ match self {29+ TimeFilter::Before(limit) => t <= limit,30+ TimeFilter::After(limit) => t >= limit,31+ }32+ }33+}34+35+#[cfg(test)]36+mod tests {37+ use super::*;38+ use std::time::Duration;39+40+ #[test]41+ fn is_time_filter_applicable() {42+ use humantime;43+44+ let ref_time = humantime::parse_rfc3339("2010-10-10T10:10:10Z").unwrap();45+ assert!(46+ TimeFilter::after(&ref_time, "1min")47+ .unwrap()48+ .applies_to(&ref_time)49+ );50+ assert!(51+ !TimeFilter::before(&ref_time, "1min")52+ .unwrap()53+ .applies_to(&ref_time)54+ );55+56+ let t1m_ago = ref_time - Duration::from_secs(60);57+ assert!(58+ !TimeFilter::after(&ref_time, "30sec")59+ .unwrap()60+ .applies_to(&t1m_ago)61+ );62+ assert!(63+ TimeFilter::after(&ref_time, "2min")64+ .unwrap()65+ .applies_to(&t1m_ago)66+ );67+68+ assert!(69+ TimeFilter::before(&ref_time, "30sec")70+ .unwrap()71+ .applies_to(&t1m_ago)72+ );73+ assert!(74+ !TimeFilter::before(&ref_time, "2min")75+ .unwrap()76+ .applies_to(&t1m_ago)77+ );78+79+ let t10s_before = "2010-10-10 10:10:00";80+ assert!(81+ !TimeFilter::before(&ref_time, t10s_before)82+ .unwrap()83+ .applies_to(&ref_time)84+ );85+ assert!(86+ TimeFilter::before(&ref_time, t10s_before)87+ .unwrap()88+ .applies_to(&t1m_ago)89+ );90+91+ assert!(92+ TimeFilter::after(&ref_time, t10s_before)93+ .unwrap()94+ .applies_to(&ref_time)95+ );96+ assert!(97+ !TimeFilter::after(&ref_time, t10s_before)98+ .unwrap()99+ .applies_to(&t1m_ago)100+ );101+ }102+}added:src/internal/file_types.rs+20 added
1+/// Whether or not to show2+pub struct FileTypes {3+ pub files: bool,4+ pub directories: bool,5+ pub symlinks: bool,6+ pub executables_only: bool,7+ pub empty_only: bool,8+}9+10+impl Default for FileTypes {11+ fn default() -> FileTypes {12+ FileTypes {13+ files: false,14+ directories: false,15+ symlinks: false,16+ executables_only: false,17+ empty_only: false,18+ }19+ }20+}added:src/internal/mod.rs+178 added
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.8+9+use regex_syntax::hir::Hir;10+use regex_syntax::Parser;11+use std::ffi::OsString;12+13+pub use self::file_types::FileTypes;14+15+mod file_types;16+pub mod filter;17+pub mod opts;18+19+macro_rules! print_error {20+ ($($arg:tt)*) => (eprintln!($($arg)*))21+}22+23+macro_rules! print_error_and_exit {24+ ($($arg:tt)*) => {25+ print_error!($($arg)*);26+ ::std::process::exit(1);27+ };28+}29+30+/// Determine if a regex pattern contains a literal uppercase character.31+pub fn pattern_has_uppercase_char(pattern: &str) -> bool {32+ Parser::new()33+ .parse(pattern)34+ .map(|hir| hir_has_uppercase_char(&hir))35+ .unwrap_or(false)36+}37+38+/// Determine if a regex expression contains a literal uppercase character.39+fn hir_has_uppercase_char(hir: &Hir) -> bool {40+ use regex_syntax::hir::*;41+42+ match *hir.kind() {43+ HirKind::Literal(Literal::Unicode(c)) => c.is_uppercase(),44+ HirKind::Class(Class::Unicode(ref ranges)) => ranges45+ .iter()46+ .any(|r| r.start().is_uppercase() || r.end().is_uppercase()),47+ HirKind::Group(Group { ref hir, .. }) | HirKind::Repetition(Repetition { ref hir, .. }) => {48+ hir_has_uppercase_char(hir)49+ }50+ HirKind::Concat(ref hirs) | HirKind::Alternation(ref hirs) => {51+ hirs.iter().any(hir_has_uppercase_char)52+ }53+ _ => false,54+ }55+}56+57+/// Maximum size of the output buffer before flushing results to the console58+pub const MAX_BUFFER_LENGTH: usize = 1000;59+60+/// Traverse args_os, looking for -exec and replacing it with --exec.61+///62+/// # Returns63+///64+/// * The args, with substitution if required65+pub fn transform_args_with_exec<I>(original: I) -> Vec<OsString>66+where67+ I: Iterator<Item = OsString>,68+{69+ let mut in_exec_opt = false;70+ let target = OsString::from("-exec");71+ let long_start = OsString::from("--exec");72+ let short_start = OsString::from("-x");73+ let exec_end = OsString::from(";");74+75+ original.fold(vec![], |mut args, curr| {76+ if in_exec_opt {77+ if curr == exec_end {78+ in_exec_opt = false;79+ }80+ args.push(curr);81+ return args;82+ }83+84+ if curr == target || curr == long_start || curr == short_start {85+ args.push(if curr == target {86+ OsString::from("--exec")87+ } else {88+ curr89+ });90+ in_exec_opt = true;91+ } else {92+ args.push(curr);93+ }94+ args95+ })96+}97+98+#[cfg(test)]99+mod tests {100+ use super::*;101+102+ fn oss(v: &str) -> OsString {103+ OsString::from(v)104+ }105+106+ /// Ensure that -exec gets transformed into --exec107+ #[test]108+ fn normal_exec_substitution() {109+ let original = vec![oss("fd"), oss("foo"), oss("-exec"), oss("cmd")];110+ let expected = vec![oss("fd"), oss("foo"), oss("--exec"), oss("cmd")];111+112+ let actual = transform_args_with_exec(original.into_iter());113+ assert_eq!(expected, actual);114+ }115+116+ /// Ensure that --exec is not touched117+ #[test]118+ fn passthru_of_original_exec() {119+ let original = vec![oss("fd"), oss("foo"), oss("--exec"), oss("cmd")];120+ let expected = vec![oss("fd"), oss("foo"), oss("--exec"), oss("cmd")];121+122+ let actual = transform_args_with_exec(original.into_iter());123+ assert_eq!(expected, actual);124+ }125+126+ #[test]127+ fn temp_check_that_exec_context_observed() {128+ let original = vec![129+ oss("fd"),130+ oss("foo"),131+ oss("-exec"),132+ oss("cmd"),133+ oss("-exec"),134+ oss("ls"),135+ oss(";"),136+ oss("-exec"),137+ oss("rm"),138+ oss(";"),139+ oss("--exec"),140+ oss("find"),141+ oss("-exec"),142+ oss("rm"),143+ oss(";"),144+ oss("-x"),145+ oss("foo"),146+ oss("-exec"),147+ oss("something"),148+ oss(";"),149+ oss("-exec"),150+ ];151+ let expected = vec![152+ oss("fd"),153+ oss("foo"),154+ oss("--exec"),155+ oss("cmd"),156+ oss("-exec"),157+ oss("ls"),158+ oss(";"),159+ oss("--exec"),160+ oss("rm"),161+ oss(";"),162+ oss("--exec"),163+ oss("find"),164+ oss("-exec"),165+ oss("rm"),166+ oss(";"),167+ oss("-x"),168+ oss("foo"),169+ oss("-exec"),170+ oss("something"),171+ oss(";"),172+ oss("--exec"),173+ ];174+175+ let actual = transform_args_with_exec(original.into_iter());176+ assert_eq!(expected, actual);177+ }178+}added:src/internal/opts.rs+75 added
1+use exec::CommandTemplate;2+use internal::{3+ filter::{SizeFilter, TimeFilter},4+ FileTypes,5+};6+use lscolors::LsColors;7+use regex::RegexSet;8+use std::{path::PathBuf, time::Duration};9+10+/// Configuration options for *fd*.11+pub struct FdOptions {12+ /// Whether the search is case-sensitive or case-insensitive.13+ pub case_sensitive: bool,14+15+ /// Whether to search within the full file path or just the base name (filename or directory16+ /// name).17+ pub search_full_path: bool,18+19+ /// Whether to ignore hidden files and directories (or not).20+ pub ignore_hidden: bool,21+22+ /// Whether to respect `.fdignore` files or not.23+ pub read_fdignore: bool,24+25+ /// Whether to respect VCS ignore files (`.gitignore`, ..) or not.26+ pub read_vcsignore: bool,27+28+ /// Whether to follow symlinks or not.29+ pub follow_links: bool,30+31+ /// Whether elements of output should be separated by a null character32+ pub null_separator: bool,33+34+ /// The maximum search depth, or `None` if no maximum search depth should be set.35+ ///36+ /// A depth of `1` includes all files under the current directory, a depth of `2` also includes37+ /// all files under subdirectories of the current directory, etc.38+ pub max_depth: Option<usize>,39+40+ /// The number of threads to use.41+ pub threads: usize,42+43+ /// Time to buffer results internally before streaming to the console. This is useful to44+ /// provide a sorted output, in case the total execution time is shorter than45+ /// `max_buffer_time`.46+ pub max_buffer_time: Option<Duration>,47+48+ /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines49+ /// how to style different filetypes.50+ pub ls_colors: Option<LsColors>,51+52+ /// The type of file to search for. If set to `None`, all file types are displayed. If53+ /// set to `Some(..)`, only the types that are specified are shown.54+ pub file_types: Option<FileTypes>,55+56+ /// The extension to search for. Only entries matching the extension will be included.57+ ///58+ /// The value (if present) will be a lowercase string without leading dots.59+ pub extensions: Option<RegexSet>,60+61+ /// If a value is supplied, each item found will be used to generate and execute commands.62+ pub command: Option<CommandTemplate>,63+64+ /// A list of glob patterns that should be excluded from the search.65+ pub exclude_patterns: Vec<String>,66+67+ /// A list of custom ignore files.68+ pub ignore_files: Vec<PathBuf>,69+70+ /// The given constraints on the size of returned files71+ pub size_constraints: Vec<SizeFilter>,72+73+ /// Constraints on last modification time of files74+ pub time_constraints: Vec<TimeFilter>,75+}deleted:src/internal.rs-568 removed
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.8-9-use std::ffi::OsString;10-use std::path::PathBuf;11-use std::time::{self, SystemTime};12-13-use exec::CommandTemplate;14-use lscolors::LsColors;15-use regex::{Regex, RegexSet};16-use regex_syntax::hir::Hir;17-use regex_syntax::Parser;18-19-lazy_static! {20- static ref SIZE_CAPTURES: Regex = { Regex::new(r"(?i)^([+-])(\d+)(b|[kmgt]i?b?)$").unwrap() };21-}22-23-/// Whether or not to show24-pub struct FileTypes {25- pub files: bool,26- pub directories: bool,27- pub symlinks: bool,28- pub executables_only: bool,29- pub empty_only: bool,30-}31-32-impl Default for FileTypes {33- fn default() -> FileTypes {34- FileTypes {35- files: false,36- directories: false,37- symlinks: false,38- executables_only: false,39- empty_only: false,40- }41- }42-}43-44-#[derive(Clone, Copy, Debug, PartialEq)]45-pub enum SizeFilter {46- Max(u64),47- Min(u64),48-}49-50-// SI prefixes (powers of 10)51-const KILO: u64 = 1000;52-const MEGA: u64 = KILO * 1000;53-const GIGA: u64 = MEGA * 1000;54-const TERA: u64 = GIGA * 1000;55-56-// Binary prefixes (powers of 2)57-const KIBI: u64 = 1024;58-const MEBI: u64 = KIBI * 1024;59-const GIBI: u64 = MEBI * 1024;60-const TEBI: u64 = GIBI * 1024;61-62-impl SizeFilter {63- pub fn from_string<'a>(s: &str) -> Option<Self> {64- if !SIZE_CAPTURES.is_match(s) {65- return None;66- }67-68- let captures = SIZE_CAPTURES.captures(s)?;69- let limit_kind = captures.get(1).map_or("+", |m| m.as_str());70- let quantity = captures71- .get(2)72- .and_then(|v| v.as_str().parse::<u64>().ok())?;73-74- let multiplier = match &captures.get(3).map_or("b", |m| m.as_str()).to_lowercase()[..] {75- v if v.starts_with("ki") => KIBI,76- v if v.starts_with("k") => KILO,77- v if v.starts_with("mi") => MEBI,78- v if v.starts_with("m") => MEGA,79- v if v.starts_with("gi") => GIBI,80- v if v.starts_with("g") => GIGA,81- v if v.starts_with("ti") => TEBI,82- v if v.starts_with("t") => TERA,83- "b" => 1,84- _ => return None,85- };86-87- let size = quantity * multiplier;88- Some(match limit_kind {89- "+" => SizeFilter::Min(size),90- _ => SizeFilter::Max(size),91- })92- }93-94- pub fn is_within(&self, size: u64) -> bool {95- match self {96- &SizeFilter::Max(limit) => size <= limit,97- &SizeFilter::Min(limit) => size >= limit,98- }99- }100-}101-102-/// Filter based on time ranges103-#[derive(Debug, PartialEq)]104-pub enum TimeFilter {105- Before(SystemTime),106- After(SystemTime),107-}108-109-impl TimeFilter {110- fn from_str(ref_time: &SystemTime, s: &str) -> Option<SystemTime> {111- use humantime;112- humantime::parse_duration(s)113- .map(|duration| *ref_time - duration)114- .or_else(|_| humantime::parse_rfc3339_weak(s))115- .ok()116- }117-118- pub fn before(ref_time: &SystemTime, s: &str) -> Option<TimeFilter> {119- TimeFilter::from_str(ref_time, s).map(TimeFilter::Before)120- }121-122- pub fn after(ref_time: &SystemTime, s: &str) -> Option<TimeFilter> {123- TimeFilter::from_str(ref_time, s).map(TimeFilter::After)124- }125-126- pub fn applies_to(&self, t: &SystemTime) -> bool {127- match self {128- TimeFilter::Before(limit) => t <= limit,129- TimeFilter::After(limit) => t >= limit,130- }131- }132-}133-134-/// Configuration options for *fd*.135-pub struct FdOptions {136- /// Whether the search is case-sensitive or case-insensitive.137- pub case_sensitive: bool,138-139- /// Whether to search within the full file path or just the base name (filename or directory140- /// name).141- pub search_full_path: bool,142-143- /// Whether to ignore hidden files and directories (or not).144- pub ignore_hidden: bool,145-146- /// Whether to respect `.fdignore` files or not.147- pub read_fdignore: bool,148-149- /// Whether to respect VCS ignore files (`.gitignore`, ..) or not.150- pub read_vcsignore: bool,151-152- /// Whether to follow symlinks or not.153- pub follow_links: bool,154-155- /// Whether elements of output should be separated by a null character156- pub null_separator: bool,157-158- /// The maximum search depth, or `None` if no maximum search depth should be set.159- ///160- /// A depth of `1` includes all files under the current directory, a depth of `2` also includes161- /// all files under subdirectories of the current directory, etc.162- pub max_depth: Option<usize>,163-164- /// The number of threads to use.165- pub threads: usize,166-167- /// Time to buffer results internally before streaming to the console. This is useful to168- /// provide a sorted output, in case the total execution time is shorter than169- /// `max_buffer_time`.170- pub max_buffer_time: Option<time::Duration>,171-172- /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines173- /// how to style different filetypes.174- pub ls_colors: Option<LsColors>,175-176- /// The type of file to search for. If set to `None`, all file types are displayed. If177- /// set to `Some(..)`, only the types that are specified are shown.178- pub file_types: Option<FileTypes>,179-180- /// The extension to search for. Only entries matching the extension will be included.181- ///182- /// The value (if present) will be a lowercase string without leading dots.183- pub extensions: Option<RegexSet>,184-185- /// If a value is supplied, each item found will be used to generate and execute commands.186- pub command: Option<CommandTemplate>,187-188- /// A list of glob patterns that should be excluded from the search.189- pub exclude_patterns: Vec<String>,190-191- /// A list of custom ignore files.192- pub ignore_files: Vec<PathBuf>,193-194- /// The given constraints on the size of returned files195- pub size_constraints: Vec<SizeFilter>,196-197- /// Constraints on last modification time of files198- pub time_constraints: Vec<TimeFilter>,199-}200-201-macro_rules! print_error {202- ($($arg:tt)*) => (eprintln!($($arg)*))203-}204-205-macro_rules! print_error_and_exit {206- ($($arg:tt)*) => {207- print_error!($($arg)*);208- ::std::process::exit(1);209- };210-}211-212-/// Determine if a regex pattern contains a literal uppercase character.213-pub fn pattern_has_uppercase_char(pattern: &str) -> bool {214- Parser::new()215- .parse(pattern)216- .map(|hir| hir_has_uppercase_char(&hir))217- .unwrap_or(false)218-}219-220-/// Determine if a regex expression contains a literal uppercase character.221-fn hir_has_uppercase_char(hir: &Hir) -> bool {222- use regex_syntax::hir::*;223-224- match *hir.kind() {225- HirKind::Literal(Literal::Unicode(c)) => c.is_uppercase(),226- HirKind::Class(Class::Unicode(ref ranges)) => ranges227- .iter()228- .any(|r| r.start().is_uppercase() || r.end().is_uppercase()),229- HirKind::Group(Group { ref hir, .. }) | HirKind::Repetition(Repetition { ref hir, .. }) => {230- hir_has_uppercase_char(hir)231- }232- HirKind::Concat(ref hirs) | HirKind::Alternation(ref hirs) => {233- hirs.iter().any(hir_has_uppercase_char)234- }235- _ => false,236- }237-}238-239-/// Maximum size of the output buffer before flushing results to the console240-pub const MAX_BUFFER_LENGTH: usize = 1000;241-242-/// Traverse args_os, looking for -exec and replacing it with --exec.243-///244-/// # Returns245-///246-/// * The args, with substitution if required247-pub fn transform_args_with_exec<I>(original: I) -> Vec<OsString>248-where249- I: Iterator<Item = OsString>,250-{251- let mut in_exec_opt = false;252- let target = OsString::from("-exec");253- let long_start = OsString::from("--exec");254- let short_start = OsString::from("-x");255- let exec_end = OsString::from(";");256-257- original.fold(vec![], |mut args, curr| {258- if in_exec_opt {259- if curr == exec_end {260- in_exec_opt = false;261- }262- args.push(curr);263- return args;264- }265-266- if curr == target || curr == long_start || curr == short_start {267- args.push(if curr == target {268- OsString::from("--exec")269- } else {270- curr271- });272- in_exec_opt = true;273- } else {274- args.push(curr);275- }276- args277- })278-}279-280-#[cfg(test)]281-mod tests {282- use super::*;283-284- fn oss(v: &str) -> OsString {285- OsString::from(v)286- }287-288- /// Ensure that -exec gets transformed into --exec289- #[test]290- fn normal_exec_substitution() {291- let original = vec![oss("fd"), oss("foo"), oss("-exec"), oss("cmd")];292- let expected = vec![oss("fd"), oss("foo"), oss("--exec"), oss("cmd")];293-294- let actual = transform_args_with_exec(original.into_iter());295- assert_eq!(expected, actual);296- }297-298- /// Ensure that --exec is not touched299- #[test]300- fn passthru_of_original_exec() {301- let original = vec![oss("fd"), oss("foo"), oss("--exec"), oss("cmd")];302- let expected = vec![oss("fd"), oss("foo"), oss("--exec"), oss("cmd")];303-304- let actual = transform_args_with_exec(original.into_iter());305- assert_eq!(expected, actual);306- }307-308- #[test]309- fn temp_check_that_exec_context_observed() {310- let original = vec![311- oss("fd"),312- oss("foo"),313- oss("-exec"),314- oss("cmd"),315- oss("-exec"),316- oss("ls"),317- oss(";"),318- oss("-exec"),319- oss("rm"),320- oss(";"),321- oss("--exec"),322- oss("find"),323- oss("-exec"),324- oss("rm"),325- oss(";"),326- oss("-x"),327- oss("foo"),328- oss("-exec"),329- oss("something"),330- oss(";"),331- oss("-exec"),332- ];333- let expected = vec![334- oss("fd"),335- oss("foo"),336- oss("--exec"),337- oss("cmd"),338- oss("-exec"),339- oss("ls"),340- oss(";"),341- oss("--exec"),342- oss("rm"),343- oss(";"),344- oss("--exec"),345- oss("find"),346- oss("-exec"),347- oss("rm"),348- oss(";"),349- oss("-x"),350- oss("foo"),351- oss("-exec"),352- oss("something"),353- oss(";"),354- oss("--exec"),355- ];356-357- let actual = transform_args_with_exec(original.into_iter());358- assert_eq!(expected, actual);359- }360-361- /// Parsing and size conversion tests362- mod size_parsing {363- use super::*;364-365- macro_rules! gen_size_filter_parse_test {366- ($($name: ident: $val: expr,)*) => {367- $(368- #[test]369- fn $name() {370- let (txt, expected) = $val;371- let actual = SizeFilter::from_string(txt).unwrap();372- assert_eq!(actual, expected);373- }374- )*375- };376- }377-378- /// Parsing and size conversion tests data. Ensure that each type gets properly interpreted.379- /// Call with higher base values to ensure expected multiplication (only need a couple)380- gen_size_filter_parse_test! {381- byte_plus: ("+1b", SizeFilter::Min(1)),382- byte_plus_multiplier: ("+10b", SizeFilter::Min(10)),383- byte_minus: ("-1b", SizeFilter::Max(1)),384- kilo_plus: ("+1k", SizeFilter::Min(1000)),385- kilo_plus_suffix: ("+1kb", SizeFilter::Min(1000)),386- kilo_minus: ("-1k", SizeFilter::Max(1000)),387- kilo_minus_multiplier: ("-100k", SizeFilter::Max(100000)),388- kilo_minus_suffix: ("-1kb", SizeFilter::Max(1000)),389- kilo_plus_upper: ("+1K", SizeFilter::Min(1000)),390- kilo_plus_suffix_upper: ("+1KB", SizeFilter::Min(1000)),391- kilo_minus_upper: ("-1K", SizeFilter::Max(1000)),392- kilo_minus_suffix_upper: ("-1Kb", SizeFilter::Max(1000)),393- kibi_plus: ("+1ki", SizeFilter::Min(1024)),394- kibi_plus_multiplier: ("+10ki", SizeFilter::Min(10240)),395- kibi_plus_suffix: ("+1kib", SizeFilter::Min(1024)),396- kibi_minus: ("-1ki", SizeFilter::Max(1024)),397- kibi_minus_multiplier: ("-100ki", SizeFilter::Max(102400)),398- kibi_minus_suffix: ("-1kib", SizeFilter::Max(1024)),399- kibi_plus_upper: ("+1KI", SizeFilter::Min(1024)),400- kibi_plus_suffix_upper: ("+1KiB", SizeFilter::Min(1024)),401- kibi_minus_upper: ("-1Ki", SizeFilter::Max(1024)),402- kibi_minus_suffix_upper: ("-1KIB", SizeFilter::Max(1024)),403- mega_plus: ("+1m", SizeFilter::Min(1000000)),404- mega_plus_suffix: ("+1mb", SizeFilter::Min(1000000)),405- mega_minus: ("-1m", SizeFilter::Max(1000000)),406- mega_minus_suffix: ("-1mb", SizeFilter::Max(1000000)),407- mega_plus_upper: ("+1M", SizeFilter::Min(1000000)),408- mega_plus_suffix_upper: ("+1MB", SizeFilter::Min(1000000)),409- mega_minus_upper: ("-1M", SizeFilter::Max(1000000)),410- mega_minus_suffix_upper: ("-1Mb", SizeFilter::Max(1000000)),411- mebi_plus: ("+1mi", SizeFilter::Min(1048576)),412- mebi_plus_suffix: ("+1mib", SizeFilter::Min(1048576)),413- mebi_minus: ("-1mi", SizeFilter::Max(1048576)),414- mebi_minus_suffix: ("-1mib", SizeFilter::Max(1048576)),415- mebi_plus_upper: ("+1MI", SizeFilter::Min(1048576)),416- mebi_plus_suffix_upper: ("+1MiB", SizeFilter::Min(1048576)),417- mebi_minus_upper: ("-1Mi", SizeFilter::Max(1048576)),418- mebi_minus_suffix_upper: ("-1MIB", SizeFilter::Max(1048576)),419- giga_plus: ("+1g", SizeFilter::Min(1000000000)),420- giga_plus_suffix: ("+1gb", SizeFilter::Min(1000000000)),421- giga_minus: ("-1g", SizeFilter::Max(1000000000)),422- giga_minus_suffix: ("-1gb", SizeFilter::Max(1000000000)),423- giga_plus_upper: ("+1G", SizeFilter::Min(1000000000)),424- giga_plus_suffix_upper: ("+1GB", SizeFilter::Min(1000000000)),425- giga_minus_upper: ("-1G", SizeFilter::Max(1000000000)),426- giga_minus_suffix_upper: ("-1Gb", SizeFilter::Max(1000000000)),427- gibi_plus: ("+1gi", SizeFilter::Min(1073741824)),428- gibi_plus_suffix: ("+1gib", SizeFilter::Min(1073741824)),429- gibi_minus: ("-1gi", SizeFilter::Max(1073741824)),430- gibi_minus_suffix: ("-1gib", SizeFilter::Max(1073741824)),431- gibi_plus_upper: ("+1GI", SizeFilter::Min(1073741824)),432- gibi_plus_suffix_upper: ("+1GiB", SizeFilter::Min(1073741824)),433- gibi_minus_upper: ("-1Gi", SizeFilter::Max(1073741824)),434- gibi_minus_suffix_upper: ("-1GIB", SizeFilter::Max(1073741824)),435- tera_plus: ("+1t", SizeFilter::Min(1000000000000)),436- tera_plus_suffix: ("+1tb", SizeFilter::Min(1000000000000)),437- tera_minus: ("-1t", SizeFilter::Max(1000000000000)),438- tera_minus_suffix: ("-1tb", SizeFilter::Max(1000000000000)),439- tera_plus_upper: ("+1T", SizeFilter::Min(1000000000000)),440- tera_plus_suffix_upper: ("+1TB", SizeFilter::Min(1000000000000)),441- tera_minus_upper: ("-1T", SizeFilter::Max(1000000000000)),442- tera_minus_suffix_upper: ("-1Tb", SizeFilter::Max(1000000000000)),443- tebi_plus: ("+1ti", SizeFilter::Min(1099511627776)),444- tebi_plus_suffix: ("+1tib", SizeFilter::Min(1099511627776)),445- tebi_minus: ("-1ti", SizeFilter::Max(1099511627776)),446- tebi_minus_suffix: ("-1tib", SizeFilter::Max(1099511627776)),447- tebi_plus_upper: ("+1TI", SizeFilter::Min(1099511627776)),448- tebi_plus_suffix_upper: ("+1TiB", SizeFilter::Min(1099511627776)),449- tebi_minus_upper: ("-1Ti", SizeFilter::Max(1099511627776)),450- tebi_minus_suffix_upper: ("-1TIB", SizeFilter::Max(1099511627776)),451- }452- }453-454- /// Invalid parse testing455- macro_rules! gen_size_filter_failure {456- ($($name:ident: $value:expr,)*) => {457- $(458- #[test]459- fn $name() {460- let i = SizeFilter::from_string($value);461- assert!(i.is_none());462- }463- )*464- };465-}466-467- /// Invalid parse data468- gen_size_filter_failure! {469- ensure_missing_symbol_returns_none: "10M",470- ensure_missing_number_returns_none: "+g",471- ensure_missing_unit_returns_none: "+18",472- ensure_bad_format_returns_none_1: "$10M",473- ensure_bad_format_returns_none_2: "badval",474- ensure_bad_format_returns_none_3: "9999",475- ensure_invalid_unit_returns_none_1: "+50a",476- ensure_invalid_unit_returns_none_2: "-10v",477- ensure_invalid_unit_returns_none_3: "+1Mv",478- ensure_bib_format_returns_none: "+1bib",479- ensure_bb_format_returns_none: "+1bb",480- }481-482- #[test]483- fn is_within_less_than() {484- let f = SizeFilter::from_string("-1k").unwrap();485- assert!(f.is_within(999));486- }487-488- #[test]489- fn is_within_less_than_equal() {490- let f = SizeFilter::from_string("-1k").unwrap();491- assert!(f.is_within(1000));492- }493-494- #[test]495- fn is_within_greater_than() {496- let f = SizeFilter::from_string("+1k").unwrap();497- assert!(f.is_within(1001));498- }499-500- #[test]501- fn is_within_greater_than_equal() {502- let f = SizeFilter::from_string("+1K").unwrap();503- assert!(f.is_within(1000));504- }505-506- #[test]507- fn is_time_filter_applicable() {508- use humantime;509-510- let ref_time = humantime::parse_rfc3339("2010-10-10T10:10:10Z").unwrap();511- assert!(512- TimeFilter::after(&ref_time, "1min")513- .unwrap()514- .applies_to(&ref_time)515- );516- assert!(517- !TimeFilter::before(&ref_time, "1min")518- .unwrap()519- .applies_to(&ref_time)520- );521-522- let t1m_ago = ref_time - time::Duration::from_secs(60);523- assert!(524- !TimeFilter::after(&ref_time, "30sec")525- .unwrap()526- .applies_to(&t1m_ago)527- );528- assert!(529- TimeFilter::after(&ref_time, "2min")530- .unwrap()531- .applies_to(&t1m_ago)532- );533-534- assert!(535- TimeFilter::before(&ref_time, "30sec")536- .unwrap()537- .applies_to(&t1m_ago)538- );539- assert!(540- !TimeFilter::before(&ref_time, "2min")541- .unwrap()542- .applies_to(&t1m_ago)543- );544-545- let t10s_before = "2010-10-10 10:10:00";546- assert!(547- !TimeFilter::before(&ref_time, t10s_before)548- .unwrap()549- .applies_to(&ref_time)550- );551- assert!(552- TimeFilter::before(&ref_time, t10s_before)553- .unwrap()554- .applies_to(&t1m_ago)555- );556-557- assert!(558- TimeFilter::after(&ref_time, t10s_before)559- .unwrap()560- .applies_to(&ref_time)561- );562- assert!(563- !TimeFilter::after(&ref_time, t10s_before)564- .unwrap()565- .applies_to(&t1m_ago)566- );567- }568-}modified:src/main.rs+3 added-2 removed
40 unmodified lines41 use regex::{RegexBuilder, RegexSetBuilder};42 43 use exec::CommandTemplate;44 use internal::{45- pattern_has_uppercase_char, transform_args_with_exec, FdOptions, FileTypes, SizeFilter,46- TimeFilter,45+ filter::{SizeFilter, TimeFilter},46+ opts::FdOptions,47+ pattern_has_uppercase_char, transform_args_with_exec, FileTypes,48 };49 use lscolors::LsColors;50 51 fn main() {218 unmodified linesmodified:src/output.rs+1 added-1 removed
6 unmodified lines7 // according to those terms.8 9 use exit_codes::ExitCode;10 use fshelper::is_executable;11-use internal::FdOptions;11+use internal::opts::FdOptions;12 use lscolors::LsColors;13 14 use std::io::{self, Write};15 use std::ops::Deref;123 unmodified linesmodified:src/walk.rs+1 added-1 removed
9 unmodified lines10 11 use exec;12 use exit_codes::ExitCode;13 use fshelper;14-use internal::{FdOptions, MAX_BUFFER_LENGTH};14+use internal::{opts::FdOptions, MAX_BUFFER_LENGTH};15 use output;16 17 use std::error::Error;18 use std::path::PathBuf;329 unmodified lines