Skip to content
Myr

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

4 files+112 added−7 removed

modified:src/app.rs+24 added-4 removed
3 unmodified lines
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.88use std::collections::HashMap;910use clap::{App, AppSettings, Arg};11
2 unmodified lines
14 long: &'static str,15}1617macro_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 lines
145 .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 lines
261 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')");257265 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 lines
13use std::time;1415use exec::CommandTemplate;16use lscolors::LsColors;17use regex::RegexSet;17use regex::{Regex, RegexSet};18use regex_syntax::hir::Hir;19use regex_syntax::Parser;2021lazy_static! {22 static ref SIZE_CAPTURES: Regex = { Regex::new(r"^(\+|-)(\d+)([a-zA-Z]{1,2})$").unwrap() };23}2425/// Whether or not to show26pub struct FileTypes {27 pub files: bool,28 pub directories: bool,
11 unmodified lines
40 }41 }42}4344enum SizeLimitType {45 Max,46 Min,47}4849pub struct SizeFilter {50 size: u64,51 limit_type: SizeLimitType,52}5354impl 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}6263const KILO: u64 = 1024;64const MEGA: u64 = KILO * 1024;65const GIGA: u64 = MEGA * 1024;66const TERA: u64 = GIGA * 1024;6768impl<'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 };7879 let quantity = captures.get(2).unwrap().as_str().parse::<u64>().unwrap();8081 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 };8889 SizeFilter {90 size: quantity * multiplier,91 limit_type: limit,92 }93 }94}9596/// Configuration options for *fd*.97pub struct FdOptions {98 /// Whether the search is case-sensitive or case-insensitive.99 pub case_sensitive: bool,
51 unmodified lines
151 pub exclude_patterns: Vec<String>,152153 /// A list of custom ignore files.154 pub ignore_files: Vec<PathBuf>,155156 /// The given constraints on the size of returned files157 pub size_constraints: Vec<SizeFilter>,158}159160/// Print error message to stderr and exit with status `1`.161pub fn error(message: &str) -> ! {
155 unmodified lines
modified:src/main.rs+18 added-2 removed
32 unmodified lines
33use std::sync::Arc;34use std::time;3536use atty::Stream;37use regex::{RegexBuilder, RegexSetBuilder};37use regex::{RegexBuilder, RegexSetBuilder, Regex};3839use exec::CommandTemplate;40use internal::{error, pattern_has_uppercase_char, transform_args_with_exec, FdOptions, FileTypes};40use internal::{error, pattern_has_uppercase_char, transform_args_with_exec, FdOptions, FileTypes,41 SizeFilter};42use lscolors::LsColors;4344lazy_static! {45 static ref VALIDATE_SIZE: Regex = { Regex::new(r"^[\+-]{1}\d+[bBkKmMgGTt]{1,2}$").unwrap() };46}4748fn 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 lines
136 };137138 let command = matches.values_of("exec").map(CommandTemplate::new);139140 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![]);149150 let config = FdOptions {151 case_sensitive,152 search_full_path: matches.is_present("full-path"),153 ignore_hidden: !(matches.is_present("hidden")
55 unmodified lines
209 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 };215216 match RegexBuilder::new(&pattern_regex)217 .case_insensitive(!config.case_sensitive)
13 unmodified lines
modified:src/walk.rs+10 added
246 unmodified lines
247 return ignore::WalkState::Continue;248 }249 }250251 // 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 }260261 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