Skip to content

Commit

Permalink
Fix touch --reference using PWD from the environment (#12976)
Browse files Browse the repository at this point in the history
This PR fixes `touch --reference path` so that it resolves `path` using
PWD from the engine state.
  • Loading branch information
YizhePKU committed May 26, 2024
1 parent a1fc41d commit f74dd33
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
12 changes: 5 additions & 7 deletions crates/nu-command/src/filesystem/touch.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -69,6 +68,8 @@ impl Command for Touch {
let no_create: bool = call.has_flag(engine_state, stack, "no-create")?;
let files: Vec<Spanned<NuGlob>> = 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(),
Expand All @@ -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(),
Expand Down Expand Up @@ -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());

Expand Down
13 changes: 13 additions & 0 deletions crates/nu-command/tests/commands/touch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
})
}

0 comments on commit f74dd33

Please sign in to comment.