1
0
mirror of https://github.com/nushell/nushell.git synced 2025-05-28 22:07:40 +02:00
YizhePKU bdb6daa4b5
Migrate to a new PWD API ()
This is the first PR towards migrating to a new `$env.PWD` API that
returns potentially un-canonicalized paths. Refer to PR  for
motivations.

## New API: `EngineState::cwd()`

The goal of the new API is to cover both parse-time and runtime use
case, and avoid unintentional misuse. It takes an `Option<Stack>` as
argument, which if supplied, will search for `$env.PWD` on the stack in
additional to the engine state. I think with this design, there's less
confusion over parse-time and runtime environments. If you have access
to a stack, just supply it; otherwise supply `None`.

## Deprecation of other PWD-related APIs

Other APIs are re-implemented using `EngineState::cwd()` and properly
documented. They're marked deprecated, but their behavior is unchanged.
Unused APIs are deleted, and code that accesses `$env.PWD` directly
without using an API is rewritten.

Deprecated APIs:

* `EngineState::current_work_dir()`
* `StateWorkingSet::get_cwd()`
* `env::current_dir()`
* `env::current_dir_str()`
* `env::current_dir_const()`
* `env::current_dir_str_const()`

Other changes:

* `EngineState::get_cwd()` (deleted)
* `StateWorkingSet::list_env()` (deleted)
* `repl::do_run_cmd()` (rewritten with `env::current_dir_str()`)

## `cd` and `pwd` now use logical paths by default

This pulls the changes from PR . It's currently somewhat broken
because using non-canonicalized paths exposed a bug in our path
normalization logic (Issue ). Once that is fixed, this should
work.

## Future plans

This PR needs some tests. Which test helpers should I use, and where
should I put those tests?

I noticed that unquoted paths are expanded within `eval_filepath()` and
`eval_directory()` before they even reach the `cd` command. This means
every paths is expanded twice. Is this intended?

Once this PR lands, the plan is to review all usages of the deprecated
APIs and migrate them to `EngineState::cwd()`. In the meantime, these
usages are annotated with `#[allow(deprecated)]` to avoid breaking CI.

---------

Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2024-05-03 14:33:09 +03:00

130 lines
4.5 KiB
Rust

#[allow(deprecated)]
use nu_engine::{command_prelude::*, env::current_dir};
use std::path::PathBuf;
#[derive(Clone)]
pub struct Mktemp;
impl Command for Mktemp {
fn name(&self) -> &str {
"mktemp"
}
fn usage(&self) -> &str {
"Create temporary files or directories using uutils/coreutils mktemp."
}
fn search_terms(&self) -> Vec<&str> {
vec![
"create",
"directory",
"file",
"folder",
"temporary",
"coreutils",
]
}
fn signature(&self) -> Signature {
Signature::build("mktemp")
.input_output_types(vec![(Type::Nothing, Type::String)])
.optional(
"template",
SyntaxShape::String,
"Optional pattern from which the name of the file or directory is derived. Must contain at least three 'X's in last component.",
)
.named("suffix", SyntaxShape::String, "Append suffix to template; must not contain a slash.", None)
.named("tmpdir-path", SyntaxShape::Filepath, "Interpret TEMPLATE relative to tmpdir-path. If tmpdir-path is not set use $TMPDIR", Some('p'))
.switch("tmpdir", "Interpret TEMPLATE relative to the system temporary directory.", Some('t'))
.switch("directory", "Create a directory instead of a file.", Some('d'))
.category(Category::FileSystem)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Make a temporary file with the given suffix in the current working directory.",
example: "mktemp --suffix .txt",
result: Some(Value::test_string("<WORKING_DIR>/tmp.lekjbhelyx.txt")),
},
Example {
description: "Make a temporary file named testfile.XXX with the 'X's as random characters in the current working directory.",
example: "mktemp testfile.XXX",
result: Some(Value::test_string("<WORKING_DIR>/testfile.4kh")),
},
Example {
description: "Make a temporary file with a template in the system temp directory.",
example: "mktemp -t testfile.XXX",
result: Some(Value::test_string("/tmp/testfile.4kh")),
},
Example {
description: "Make a temporary directory with randomly generated name in the temporary directory.",
example: "mktemp -d",
result: Some(Value::test_string("/tmp/tmp.NMw9fJr8K0")),
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let template = call
.rest(engine_state, stack, 0)?
.first()
.cloned()
.map(|i: Spanned<String>| i.item)
.unwrap_or("tmp.XXXXXXXXXX".to_string()); // same as default in coreutils
let directory = call.has_flag(engine_state, stack, "directory")?;
let suffix = call.get_flag(engine_state, stack, "suffix")?;
let tmpdir = call.has_flag(engine_state, stack, "tmpdir")?;
let tmpdir_path = call
.get_flag(engine_state, stack, "tmpdir-path")?
.map(|i: Spanned<PathBuf>| i.item);
let tmpdir = if tmpdir_path.is_some() {
tmpdir_path
} else if directory || tmpdir {
Some(std::env::temp_dir())
} else {
#[allow(deprecated)]
Some(current_dir(engine_state, stack)?)
};
let options = uu_mktemp::Options {
directory,
dry_run: false,
quiet: false,
suffix,
template,
tmpdir,
treat_as_template: true,
};
let res = match uu_mktemp::mktemp(&options) {
Ok(res) => {
res.into_os_string()
.into_string()
.map_err(|e| ShellError::IOErrorSpanned {
msg: e.to_string_lossy().to_string(),
span,
})?
}
Err(e) => {
return Err(ShellError::GenericError {
error: format!("{}", e),
msg: format!("{}", e),
span: None,
help: None,
inner: vec![],
});
}
};
Ok(PipelineData::Value(Value::string(res, span), None))
}
}