Make --strip-cwd-prefix apply to -x/-X
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #898.
authored by Tavian Barnes · committed by David Peter · parent 5039d2d · Browse files · 7 files·+66 added−44 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+66 added−44 removed
- tests:+15 added−0 removed
- other:+51 added−44 removed
Provenance
- Commit
4ffc349- Tree
c88964c- Author
Tavian Barnes <tavianator@tavianator.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
5039d2d
7 files changed+66 added−44 removed
modified:src/exec/job.rs+15 added-13 removed
1 use std::sync::mpsc::Receiver;2 use std::sync::{Arc, Mutex};3 4+use crate::config::Config;5 use crate::dir_entry::DirEntry;6 use crate::error::print_error;7 use crate::exit_codes::{merge_exitcodes, ExitCode};8 use crate::walk::WorkerResult;6 unmodified lines15 pub fn job(16 rx: Arc<Mutex<Receiver<WorkerResult>>>,17 cmd: Arc<CommandSet>,18 out_perm: Arc<Mutex<()>>,18- show_filesystem_errors: bool,19- buffer_output: bool,19+ config: &Config,20 ) -> ExitCode {21+ // Output should be buffered when only running a single thread22+ let buffer_output: bool = config.threads > 1;23+24 let mut results: Vec<ExitCode> = Vec::new();25 loop {26 // Create a lock on the shared receiver for this thread.27 let lock = rx.lock().unwrap();2 unmodified lines30 // has closed, exit from the loop31 let dir_entry: DirEntry = match lock.recv() {32 Ok(WorkerResult::Entry(dir_entry)) => dir_entry,33 Ok(WorkerResult::Error(err)) => {31- if show_filesystem_errors {34+ if config.show_filesystem_errors {35 print_error(err.to_string());36 }37 continue;38 }2 unmodified lines41 42 // Drop the lock so that other threads can read from the receiver.43 drop(lock);44 // Generate a command, execute it and store its exit code.42- results.push(cmd.execute(dir_entry.path(), Arc::clone(&out_perm), buffer_output))45+ results.push(cmd.execute(46+ dir_entry.stripped_path(config),47+ Arc::clone(&out_perm),48+ buffer_output,49+ ))50 }51 // Returns error in case of any error.52 merge_exitcodes(results)53 }54 48-pub fn batch(49- rx: Receiver<WorkerResult>,50- cmd: &CommandSet,51- show_filesystem_errors: bool,52- limit: usize,53-) -> ExitCode {55+pub fn batch(rx: Receiver<WorkerResult>, cmd: &CommandSet, config: &Config) -> ExitCode {56 let paths = rx57 .into_iter()58 .filter_map(|worker_result| match worker_result {57- WorkerResult::Entry(dir_entry) => Some(dir_entry.into_path()),59+ WorkerResult::Entry(dir_entry) => Some(dir_entry.into_stripped_path(config)),60 WorkerResult::Error(err) => {59- if show_filesystem_errors {61+ if config.show_filesystem_errors {62 print_error(err.to_string());63 }64 None65 }66 });67 66- cmd.execute_batch(paths, limit)68+ cmd.execute_batch(paths, config.batch_size)69 }modified:src/app.rs+4 added-2 removed
722 unmodified lines723 .conflicts_with_all(&["path", "search-path"])724 .hide_short_help(true)725 .help("strip './' prefix from -0/--print0 output")726 .long_help(727- "By default, relative paths are prefixed with './' when -0/--print0 is given, to \728- make them safer for use with xargs. Use this flag to disable this behaviour."727+ "By default, relative paths are prefixed with './' when -x/--exec, \728+ -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a \729+ path starting with '-' being treated as a command line option. Use \730+ this flag to disable this behaviour."731 )732 );733 734 if cfg!(unix) {45 unmodified linesmodified:src/dir_entry.rs+21 added
3 unmodified lines4 };5 6 use once_cell::unsync::OnceCell;7 8+use crate::config::Config;9+use crate::filesystem::strip_current_dir;10+11 enum DirEntryInner {12 Normal(ignore::DirEntry),13 BrokenSymlink(PathBuf),14 }32 unmodified lines47 DirEntryInner::BrokenSymlink(p) => p,48 }49 }50 51+ /// Returns the path as it should be presented to the user.52+ pub fn stripped_path(&self, config: &Config) -> &Path {53+ if config.strip_cwd_prefix {54+ strip_current_dir(self.path())55+ } else {56+ self.path()57+ }58+ }59+60+ /// Returns the path as it should be presented to the user.61+ pub fn into_stripped_path(self, config: &Config) -> PathBuf {62+ if config.strip_cwd_prefix {63+ self.stripped_path(config).to_path_buf()64+ } else {65+ self.into_path()66+ }67+ }68+69 pub fn file_type(&self) -> Option<FileType> {70 match &self.inner {71 DirEntryInner::Normal(e) => e.file_type(),72 DirEntryInner::BrokenSymlink(_) => self.metadata().map(|m| m.file_type()),41 unmodified linesmodified:src/main.rs+5 added-2 removed
381 unmodified lines382 } else {383 None384 }385 }),386- strip_cwd_prefix: (!matches.is_present("path")386+ strip_cwd_prefix: !matches.is_present("path")387 && !matches.is_present("search-path")388- && (!matches.is_present("null_separator") || matches.is_present("strip-cwd-prefix"))),388+ && (matches.is_present("strip-cwd-prefix")389+ || !(matches.is_present("null_separator")390+ || matches.is_present("exec")391+ || matches.is_present("exec-batch"))),392 })393 }394 395 fn extract_command(175 unmodified linesmodified:src/output.rs+3 added-14 removed
1 use std::borrow::Cow;2 use std::io::{self, Write};3-use std::path::Path;3 4 use lscolors::{Indicator, LsColors, Style};5 6 use crate::config::Config;7 use crate::dir_entry::DirEntry;8 use crate::error::print_error;9 use crate::exit_codes::ExitCode;11-use crate::filesystem::strip_current_dir;10 11 fn replace_path_separator(path: &str, new_path_separator: &str) -> String {12 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)13 }14 17-fn stripped_path<'a>(entry: &'a DirEntry, config: &Config) -> &'a Path {18- let path = entry.path();19- if config.strip_cwd_prefix {20- strip_current_dir(path)21- } else {22- path23- }24-}25-15 // TODO: this function is performance critical and can probably be optimized16 pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) {17 let r = if let Some(ref ls_colors) = config.ls_colors {18 print_entry_colorized(stdout, entry, config, ls_colors)43 unmodified lines62 ls_colors: &LsColors,63 ) -> io::Result<()> {64 // Split the path between the parent and the last component65 let mut offset = 0;77- let path = stripped_path(entry, config);66+ let path = entry.stripped_path(config);67 let path_str = path.to_string_lossy();68 69 if let Some(parent) = path.parent() {70 offset = parent.to_string_lossy().len();47 unmodified lines118 entry: &DirEntry,119 config: &Config,120 ) -> io::Result<()> {121 let separator = if config.null_separator { "\0" } else { "\n" };133- let path = stripped_path(entry, config);122+ let path = entry.stripped_path(config);123 124 let mut path_string = path.to_string_lossy();125 if let Some(ref separator) = config.path_separator {126 *path_string.to_mut() = replace_path_separator(&path_string, separator);25 unmodified lines152 print_entry_uncolorized_base(stdout, entry, config)153 } else {154 // Print path as raw bytes, allowing invalid UTF-8 filenames to be passed to other processes155 let separator = if config.null_separator { b"\0" } else { b"\n" };167- stdout.write_all(stripped_path(entry, config).as_os_str().as_bytes())?;156+ stdout.write_all(entry.stripped_path(config).as_os_str().as_bytes())?;157 print_trailing_slash(stdout, entry, config, None)?;158 stdout.write_all(separator)159 }160 }modified:src/walk.rs+3 added-13 removed
339 unmodified lines340 let config = Arc::clone(config);341 let quit_flag = Arc::clone(quit_flag);342 let interrupt_flag = Arc::clone(interrupt_flag);343 344- let show_filesystem_errors = config.show_filesystem_errors;344 let threads = config.threads;346- // This will be used to check if output should be buffered when only running a single thread347- let enable_output_buffering: bool = threads > 1;345 thread::spawn(move || {346 // This will be set to `Some` if the `--exec` argument was supplied.347 if let Some(ref cmd) = config.command {348 if cmd.in_batch_mode() {352- exec::batch(rx, cmd, show_filesystem_errors, config.batch_size)349+ exec::batch(rx, cmd, &config)350 } else {351 let shared_rx = Arc::new(Mutex::new(rx));352 353 let out_perm = Arc::new(Mutex::new(()));354 355 // Each spawned job will store it's thread handle in here.356 let mut handles = Vec::with_capacity(threads);357 for _ in 0..threads {358+ let config = Arc::clone(&config);359 let rx = Arc::clone(&shared_rx);360 let cmd = Arc::clone(cmd);361 let out_perm = Arc::clone(&out_perm);362 363 // Spawn a job thread that will listen for and execute inputs.366- let handle = thread::spawn(move || {367- exec::job(368- rx,369- cmd,370- out_perm,371- show_filesystem_errors,372- enable_output_buffering,373- )374- });364+ let handle = thread::spawn(move || exec::job(rx, cmd, out_perm, &config));365 366 // Push the handle of the spawned thread into the vector for later joining.367 handles.push(handle);368 }184 unmodified linesmodified:tests/tests.rs+15 added
1326 unmodified lines1327 ./one/two/three/directory_foo",1328 );1329 1330 te.assert_output(1331+ &["foo", "--strip-cwd-prefix", "--exec", "echo", "{}"],1332+ "a.foo1333+ one/b.foo1334+ one/two/C.Foo21335+ one/two/c.foo1336+ one/two/three/d.foo1337+ one/two/three/directory_foo",1338+ );1339+1340+ te.assert_output(1341 &["foo", "--exec", "echo", "{.}"],1342 "a1343 one/b1344 one/two/C117 unmodified lines1462 "./a.foo ./one/b.foo ./one/two/C.Foo2 ./one/two/c.foo ./one/two/three/d.foo ./one/two/three/directory_foo",1463 );1464 1465 te.assert_output(1466+ &["foo", "--strip-cwd-prefix", "--exec-batch", "echo", "{}"],1467+ "a.foo one/b.foo one/two/C.Foo2 one/two/c.foo one/two/three/d.foo one/two/three/directory_foo",1468+ );1469+1470+ te.assert_output(1471 &["foo", "--exec-batch", "echo", "{/}"],1472 "a.foo b.foo C.Foo2 c.foo d.foo directory_foo",1473 );1474 668 unmodified lines