nushell/crates/nu-command/src/filesystem/mkdir.rs
Jakub Žádník 74dcd91cc3
Use only $nu.env.PWD for getting the current directory (#587)
* Use only $nu.env.PWD for getting current directory

Because setting and reading to/from std::env changes the global state
shich is problematic if we call `cd` from multiple threads (e.g., in a
`par-each` block).

With this change, when engine-q starts, it will either inherit existing
PWD env var, or create a new one from `std::env::current_dir()`.
Otherwise, everything that needs the current directory will get it from
`$nu.env.PWD`. Each spawned external command will get its current
directory per-process which should be thread-safe.

One thing left to do is to patch nu-path for this as well since it uses
`std::env::current_dir()` in its expansions.

* Rename nu-path functions

*_with is not *_relative which should be more descriptive and frees
"with" for use in a followup commit.

* Clone stack every each iter; Fix some commands

Cloning the stack each iteration of `each` makes sure we're not reusing
PWD between iterations.

Some fixes in commands to make them use the new PWD.

* Post-rebase cleanup, fmt, clippy

* Change back _relative to _with in nu-path funcs

Didn't use the idea I had for the new "_with".

* Remove leftover current_dir from rebase

* Add cwd sync at merge_delta()

This makes sure the parser and completer always have up-to-date cwd.

* Always pass absolute path to glob in ls

* Do not allow PWD a relative path; Allow recovery

Makes it possible to recover PWD by proceeding with the REPL cycle.

* Clone stack in each also for byte/string stream

* (WIP) Start moving env variables to engine state

* (WIP) Move env vars to engine state (ugly)

Quick and dirty code.

* (WIP) Remove unused mut and args; Fmt

* (WIP) Fix dataframe tests

* (WIP) Fix missing args after rebase

* (WIP) Clone only env vars, not the whole stack

* (WIP) Add env var clone to `for` loop as well

* Minor edits

* Refactor merge_delta() to include stack merging.

Less error-prone than doing it manually.

* Clone env for each `update` command iteration

* Mark env var hidden only when found in eng. state

* Fix clippt warnings

* Add TODO about env var reading

* Do not clone empty environment in loops

* Remove extra cwd collection

* Split current_dir() into str and path; Fix autocd

* Make completions respect PWD env var
2022-01-05 09:30:34 +11:00

81 lines
2.3 KiB
Rust

use std::collections::VecDeque;
use nu_engine::env::current_dir;
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, SyntaxShape,
Value,
};
#[derive(Clone)]
pub struct Mkdir;
impl Command for Mkdir {
fn name(&self) -> &str {
"mkdir"
}
fn signature(&self) -> Signature {
Signature::build("mkdir")
.rest(
"rest",
SyntaxShape::Filepath,
"the name(s) of the path(s) to create",
)
.switch("show-created-paths", "show the path(s) created.", Some('s'))
.category(Category::FileSystem)
}
fn usage(&self) -> &str {
"Make directories, creates intermediary directories as required."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let path = current_dir(engine_state, stack)?;
let mut directories = call
.rest::<String>(engine_state, stack, 0)?
.into_iter()
.map(|dir| path.join(dir))
.peekable();
let show_created_paths = call.has_flag("show-created-paths");
let mut stream: VecDeque<Value> = VecDeque::new();
if directories.peek().is_none() {
return Err(ShellError::MissingParameter(
"requires directory paths".to_string(),
call.head,
));
}
for (i, dir) in directories.enumerate() {
let span = call.positional[i].span;
let dir_res = std::fs::create_dir_all(&dir);
if let Err(reason) = dir_res {
return Err(ShellError::CreateNotPossible(
format!("failed to create directory: {}", reason),
call.positional[i].span,
));
}
if show_created_paths {
let val = format!("{:}", dir.to_string_lossy());
stream.push_back(Value::String { val, span });
}
}
Ok(stream
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()))
}
}