Initial impl of size constraints.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This adds find-style size constraints with + or - indicating greater or less than, a numerical size, and a unit
authored by Steve Pentland · committed by David Peter · parent fea85db · Browse files · 4 files·+112 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+112 added−7 removed
- other:+112 added−7 removed
Provenance
- Commit
0207c13- Tree
c77a90e- Author
Steve Pentland <stevepentland@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
fea85db
4 files changed+112 added−7 removed
modified:src/app.rs+24 added-4 removed
3 unmodified lines4 // 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-8 use std::collections::HashMap;9 10 use clap::{App, AppSettings, Arg};11 2 unmodified lines14 long: &'static str,15 }16 17 macro_rules! doc {19- ($map:expr, $name:expr, $short:expr) => {18+ ($map: expr, $name: expr, $short: expr) => {19 doc!($map, $name, $short, $short)20 };22- ($map:expr, $name:expr, $short:expr, $long:expr) => {21+ ($map: expr, $name: expr, $short: expr, $long: expr) => {22 $map.insert(23 $name,24 Help {25 short: $short,119 unmodified lines145 .takes_value(true)146 .value_name("num"),147 )148 .arg(149+ arg("size")150+ .long("size")151+ .short("S")152+ .takes_value(true)153+ .number_of_values(1)154+ .allow_hyphen_values(true)155+ .multiple(true),156+ )157+ .arg(158 arg("max-buffer-time")159 .long("max-buffer-time")160 .takes_value(true)161 .hidden(true),99 unmodified lines261 If omitted, search the current working directory.");262 doc!(h, "rg-alias-hidden-ignore"263 , "Alias for no-ignore and/or hidden"264 , "Alias for no-ignore ('u') and no-ignore and hidden ('uu')");257-265+ doc!(h, "size"266+ , "Limit results based on the size of files."267+ , "Limit results based on the size of files using the format <+-><NUM><UN>.\n \268+ '+': file size must be greater than this\n \269+ '-': file size must be less than this\n \270+ 'NUM': The numeric size (e.g. 500)\n \271+ 'UN': The units for NUM.\n\272+ Allowed unit values:\n \273+ 'b' or 'B': bytes\n \274+ 'k' or 'K': kilobytes\n \275+ 'm' or 'M': megabytes\n \276+ 'g' or 'G': gigabytes\n \277+ 't' or 'T': terabytes");278 h279 }modified:src/internal.rs+60 added-1 removed
12 unmodified lines13 use std::time;14 15 use exec::CommandTemplate;16 use lscolors::LsColors;17-use regex::RegexSet;17+use regex::{Regex, RegexSet};18 use regex_syntax::hir::Hir;19 use regex_syntax::Parser;20 21+lazy_static! {22+ static ref SIZE_CAPTURES: Regex = { Regex::new(r"^(\+|-)(\d+)([a-zA-Z]{1,2})$").unwrap() };23+}24+25 /// Whether or not to show26 pub struct FileTypes {27 pub files: bool,28 pub directories: bool,11 unmodified lines40 }41 }42 }43 44+enum SizeLimitType {45+ Max,46+ Min,47+}48+49+pub struct SizeFilter {50+ size: u64,51+ limit_type: SizeLimitType,52+}53+54+impl SizeFilter {55+ pub fn is_within(&self, size: u64) -> bool {56+ match self.limit_type {57+ SizeLimitType::Max => size <= self.size,58+ SizeLimitType::Min => size >= self.size,59+ }60+ }61+}62+63+const KILO: u64 = 1024;64+const MEGA: u64 = KILO * 1024;65+const GIGA: u64 = MEGA * 1024;66+const TERA: u64 = GIGA * 1024;67+68+impl<'a> From<&'a str> for SizeFilter {69+ /// Create the `SizeFilter` from the given `&str`.70+ /// It is imperative that the incoming value has been validated for71+ /// proper format.72+ fn from(s: &str) -> Self {73+ let captures = SIZE_CAPTURES.captures(s).unwrap();74+ let limit = match captures.get(1).map_or("+", |m| m.as_str()) {75+ "+" => SizeLimitType::Min,76+ _ => SizeLimitType::Max,77+ };78+79+ let quantity = captures.get(2).unwrap().as_str().parse::<u64>().unwrap();80+81+ let multiplier = match &captures.get(3).map_or("m", |m| m.as_str()).to_lowercase()[..] {82+ "k" => KILO,83+ "m" => MEGA,84+ "g" => GIGA,85+ "t" => TERA,86+ _ => 1, // Any we don't understand we'll just say the number of bytes87+ };88+89+ SizeFilter {90+ size: quantity * multiplier,91+ limit_type: limit,92+ }93+ }94+}95+96 /// Configuration options for *fd*.97 pub struct FdOptions {98 /// Whether the search is case-sensitive or case-insensitive.99 pub case_sensitive: bool,51 unmodified lines151 pub exclude_patterns: Vec<String>,152 153 /// A list of custom ignore files.154 pub ignore_files: Vec<PathBuf>,155+156+ /// The given constraints on the size of returned files157+ pub size_constraints: Vec<SizeFilter>,158 }159 160 /// Print error message to stderr and exit with status `1`.161 pub fn error(message: &str) -> ! {155 unmodified linesmodified:src/main.rs+18 added-2 removed
32 unmodified lines33 use std::sync::Arc;34 use std::time;35 36 use atty::Stream;37-use regex::{RegexBuilder, RegexSetBuilder};37+use regex::{RegexBuilder, RegexSetBuilder, Regex};38 39 use exec::CommandTemplate;40-use internal::{error, pattern_has_uppercase_char, transform_args_with_exec, FdOptions, FileTypes};40+use internal::{error, pattern_has_uppercase_char, transform_args_with_exec, FdOptions, FileTypes,41+ SizeFilter};42 use lscolors::LsColors;43 44+lazy_static! {45+ static ref VALIDATE_SIZE: Regex = { Regex::new(r"^[\+-]{1}\d+[bBkKmMgGTt]{1,2}$").unwrap() };46+}47+48 fn main() {49 let checked_args = transform_args_with_exec(env::args_os());50 let matches = app::build_app().get_matches_from(checked_args);51 84 unmodified lines136 };137 138 let command = matches.values_of("exec").map(CommandTemplate::new);139 140+ let size_limits: Vec<SizeFilter> = matches141+ .values_of("size")142+ .map(|v| v.map(|sf| {143+ if !VALIDATE_SIZE.is_match(sf) {144+ error(&format!("Error: {} is not a valid size constraint.", sf));145+ }146+ sf.into()147+ }).collect())148+ .unwrap_or_else(|| vec![]);149+150 let config = FdOptions {151 case_sensitive,152 search_full_path: matches.is_present("full-path"),153 ignore_hidden: !(matches.is_present("hidden")55 unmodified lines209 ignore_files: matches210 .values_of("ignore-file")211 .map(|vs| vs.map(PathBuf::from).collect())212 .unwrap_or_else(|| vec![]),213+ size_constraints: size_limits,214 };215 216 match RegexBuilder::new(&pattern_regex)217 .case_insensitive(!config.case_sensitive)13 unmodified linesmodified:src/walk.rs+10 added
246 unmodified lines247 return ignore::WalkState::Continue;248 }249 }250 251+ // Filter out unwanted sizes if it is a file and we have been given size constraints.252+ if entry_path.is_file() && config.size_constraints.len() > 0 {253+ if let Ok(metadata) = entry_path.metadata() {254+ let file_size = metadata.len();255+ if config.size_constraints.iter().any(|sc| !sc.is_within(file_size)) {256+ return ignore::WalkState::Continue;257+ }258+ }259+ }260+261 let search_str_o = if config.search_full_path {262 match fshelper::path_absolute_form(entry_path) {263 Ok(path_abs_buf) => Some(path_abs_buf.to_string_lossy().into_owned().into()),264 Err(_) => error("Error: unable to get full path."),27 unmodified lines