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.
This commit is contained in:
YizhePKU 2024-05-27 01:24:00 +08:00 committed by GitHub
parent a1fc41db22
commit f74dd33ba9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 7 deletions

View File

@ -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<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(),
@ -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());

View File

@ -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());
})
}