From f74dd33ba9213e85e08ee96ba25558d1a89f1fb2 Mon Sep 17 00:00:00 2001 From: YizhePKU Date: Mon, 27 May 2024 01:24:00 +0800 Subject: [PATCH] Fix `touch --reference` using PWD from the environment (#12976) This PR fixes `touch --reference path` so that it resolves `path` using PWD from the engine state. --- crates/nu-command/src/filesystem/touch.rs | 12 +++++------- crates/nu-command/tests/commands/touch.rs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/crates/nu-command/src/filesystem/touch.rs b/crates/nu-command/src/filesystem/touch.rs index 08843b11f0..0253e7e317 100644 --- a/crates/nu-command/src/filesystem/touch.rs +++ b/crates/nu-command/src/filesystem/touch.rs @@ -1,10 +1,9 @@ use filetime::FileTime; -#[allow(deprecated)] -use nu_engine::{command_prelude::*, current_dir}; +use nu_engine::command_prelude::*; use nu_path::expand_path_with; use nu_protocol::NuGlob; -use std::{fs::OpenOptions, path::Path, time::SystemTime}; +use std::{fs::OpenOptions, time::SystemTime}; use super::util::get_rest_for_glob_pattern; @@ -69,6 +68,8 @@ impl Command for Touch { let no_create: bool = call.has_flag(engine_state, stack, "no-create")?; let files: Vec> = get_rest_for_glob_pattern(engine_state, stack, call, 0)?; + let cwd = engine_state.cwd(Some(stack))?; + if files.is_empty() { return Err(ShellError::MissingParameter { param_name: "requires file paths".to_string(), @@ -86,7 +87,7 @@ impl Command for Touch { } if let Some(reference) = reference { - let reference_path = Path::new(&reference.item); + let reference_path = nu_path::expand_path_with(reference.item, &cwd, true); if !reference_path.exists() { return Err(ShellError::FileNotFoundCustom { msg: "Reference path not found".into(), @@ -114,9 +115,6 @@ impl Command for Touch { })?; } - #[allow(deprecated)] - let cwd = current_dir(engine_state, stack)?; - for glob in files { let path = expand_path_with(glob.item.as_ref(), &cwd, glob.item.is_expand()); diff --git a/crates/nu-command/tests/commands/touch.rs b/crates/nu-command/tests/commands/touch.rs index 26d0325729..5f454cdec4 100644 --- a/crates/nu-command/tests/commands/touch.rs +++ b/crates/nu-command/tests/commands/touch.rs @@ -515,3 +515,16 @@ fn respects_cwd() { assert!(path.exists()); }) } + +#[test] +fn reference_respects_cwd() { + Playground::setup("touch_reference_respects_cwd", |dirs, _sandbox| { + nu!( + cwd: dirs.test(), + "mkdir 'dir'; cd 'dir'; touch 'ref.txt'; touch --reference 'ref.txt' 'foo.txt'" + ); + + let path = dirs.test().join("dir/foo.txt"); + assert!(path.exists()); + }) +}