nushell/crates/nu-cli/src/shell/filesystem_shell.rs

1168 lines
44 KiB
Rust
Raw Normal View History

use crate::commands::command::EvaluatedWholeStreamCommandArgs;
2019-08-21 19:03:59 +02:00
use crate::commands::cp::CopyArgs;
use crate::commands::ls::LsArgs;
2019-08-21 19:03:59 +02:00
use crate::commands::mkdir::MkdirArgs;
use crate::commands::mv::MoveArgs;
use crate::commands::rm::RemoveArgs;
use crate::data::dir_entry_dict;
use crate::path::{canonicalize_existing, normalize};
2019-08-07 19:49:11 +02:00
use crate::prelude::*;
2019-08-09 07:36:43 +02:00
use crate::shell::completer::NuCompleter;
2019-08-07 19:49:11 +02:00
use crate::shell::shell::Shell;
2019-08-21 19:03:59 +02:00
use crate::utils::FileStructure;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, UntaggedValue};
2019-08-09 07:36:43 +02:00
use rustyline::completion::FilenameCompleter;
2019-08-07 19:49:11 +02:00
use rustyline::hint::{Hinter, HistoryHinter};
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
2019-08-22 07:15:14 +02:00
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
2019-08-07 19:49:11 +02:00
pub struct FilesystemShell {
pub(crate) path: String,
pub(crate) last_path: String,
2019-08-07 19:49:11 +02:00
completer: NuCompleter,
hinter: HistoryHinter,
}
impl std::fmt::Debug for FilesystemShell {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "FilesystemShell @ {}", self.path)
}
}
2019-08-07 19:49:11 +02:00
impl Clone for FilesystemShell {
fn clone(&self) -> Self {
FilesystemShell {
path: self.path.clone(),
last_path: self.path.clone(),
2019-08-07 19:49:11 +02:00
completer: NuCompleter {
file_completer: FilenameCompleter::new(),
2019-08-10 07:02:15 +02:00
commands: self.completer.commands.clone(),
Restructure and streamline token expansion (#1123) Restructure and streamline token expansion The purpose of this commit is to streamline the token expansion code, by removing aspects of the code that are no longer relevant, removing pointless duplication, and eliminating the need to pass the same arguments to `expand_syntax`. The first big-picture change in this commit is that instead of a handful of `expand_` functions, which take a TokensIterator and ExpandContext, a smaller number of methods on the `TokensIterator` do the same job. The second big-picture change in this commit is fully eliminating the coloring traits, making coloring a responsibility of the base expansion implementations. This also means that the coloring tracer is merged into the expansion tracer, so you can follow a single expansion and see how the expansion process produced colored tokens. One side effect of this change is that the expander itself is marginally more error-correcting. The error correction works by switching from structured expansion to `BackoffColoringMode` when an unexpected token is found, which guarantees that all spans of the source are colored, but may not be the most optimal error recovery strategy. That said, because `BackoffColoringMode` only extends as far as a closing delimiter (`)`, `]`, `}`) or pipe (`|`), it does result in fairly granular correction strategy. The current code still produces an `Err` (plus a complete list of colored shapes) from the parsing process if any errors are encountered, but this could easily be addressed now that the underlying expansion is error-correcting. This commit also colors any spans that are syntax errors in red, and causes the parser to include some additional information about what tokens were expected at any given point where an error was encountered, so that completions and hinting could be more robust in the future. Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com> Co-authored-by: Andrés N. Robalino <andres@androbtech.com>
2020-01-21 23:45:03 +01:00
homedir: self.homedir(),
2019-08-07 19:49:11 +02:00
},
hinter: HistoryHinter {},
}
}
}
impl FilesystemShell {
2019-08-10 07:02:15 +02:00
pub fn basic(commands: CommandRegistry) -> Result<FilesystemShell, std::io::Error> {
2019-08-07 19:49:11 +02:00
let path = std::env::current_dir()?;
Ok(FilesystemShell {
path: path.to_string_lossy().to_string(),
last_path: path.to_string_lossy().to_string(),
2019-08-07 19:49:11 +02:00
completer: NuCompleter {
file_completer: FilenameCompleter::new(),
2019-08-10 07:02:15 +02:00
commands,
Restructure and streamline token expansion (#1123) Restructure and streamline token expansion The purpose of this commit is to streamline the token expansion code, by removing aspects of the code that are no longer relevant, removing pointless duplication, and eliminating the need to pass the same arguments to `expand_syntax`. The first big-picture change in this commit is that instead of a handful of `expand_` functions, which take a TokensIterator and ExpandContext, a smaller number of methods on the `TokensIterator` do the same job. The second big-picture change in this commit is fully eliminating the coloring traits, making coloring a responsibility of the base expansion implementations. This also means that the coloring tracer is merged into the expansion tracer, so you can follow a single expansion and see how the expansion process produced colored tokens. One side effect of this change is that the expander itself is marginally more error-correcting. The error correction works by switching from structured expansion to `BackoffColoringMode` when an unexpected token is found, which guarantees that all spans of the source are colored, but may not be the most optimal error recovery strategy. That said, because `BackoffColoringMode` only extends as far as a closing delimiter (`)`, `]`, `}`) or pipe (`|`), it does result in fairly granular correction strategy. The current code still produces an `Err` (plus a complete list of colored shapes) from the parsing process if any errors are encountered, but this could easily be addressed now that the underlying expansion is error-correcting. This commit also colors any spans that are syntax errors in red, and causes the parser to include some additional information about what tokens were expected at any given point where an error was encountered, so that completions and hinting could be more robust in the future. Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com> Co-authored-by: Andrés N. Robalino <andres@androbtech.com>
2020-01-21 23:45:03 +01:00
homedir: dirs::home_dir(),
2019-08-07 19:49:11 +02:00
},
hinter: HistoryHinter {},
})
}
pub fn with_location(path: String, commands: CommandRegistry) -> FilesystemShell {
let last_path = path.clone();
FilesystemShell {
2019-08-07 19:49:11 +02:00
path,
last_path,
2019-08-07 19:49:11 +02:00
completer: NuCompleter {
file_completer: FilenameCompleter::new(),
2019-08-10 07:02:15 +02:00
commands,
Restructure and streamline token expansion (#1123) Restructure and streamline token expansion The purpose of this commit is to streamline the token expansion code, by removing aspects of the code that are no longer relevant, removing pointless duplication, and eliminating the need to pass the same arguments to `expand_syntax`. The first big-picture change in this commit is that instead of a handful of `expand_` functions, which take a TokensIterator and ExpandContext, a smaller number of methods on the `TokensIterator` do the same job. The second big-picture change in this commit is fully eliminating the coloring traits, making coloring a responsibility of the base expansion implementations. This also means that the coloring tracer is merged into the expansion tracer, so you can follow a single expansion and see how the expansion process produced colored tokens. One side effect of this change is that the expander itself is marginally more error-correcting. The error correction works by switching from structured expansion to `BackoffColoringMode` when an unexpected token is found, which guarantees that all spans of the source are colored, but may not be the most optimal error recovery strategy. That said, because `BackoffColoringMode` only extends as far as a closing delimiter (`)`, `]`, `}`) or pipe (`|`), it does result in fairly granular correction strategy. The current code still produces an `Err` (plus a complete list of colored shapes) from the parsing process if any errors are encountered, but this could easily be addressed now that the underlying expansion is error-correcting. This commit also colors any spans that are syntax errors in red, and causes the parser to include some additional information about what tokens were expected at any given point where an error was encountered, so that completions and hinting could be more robust in the future. Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com> Co-authored-by: Andrés N. Robalino <andres@androbtech.com>
2020-01-21 23:45:03 +01:00
homedir: dirs::home_dir(),
2019-08-07 19:49:11 +02:00
},
hinter: HistoryHinter {},
}
2019-08-07 19:49:11 +02:00
}
}
impl Shell for FilesystemShell {
fn name(&self) -> String {
2019-08-07 19:49:11 +02:00
"filesystem".to_string()
}
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
fn homedir(&self) -> Option<PathBuf> {
dirs::home_dir()
}
fn ls(
&self,
LsArgs {
path,
all,
full,
short_names,
with_symlink_targets,
}: LsArgs,
context: &RunnablePerItemContext,
) -> Result<OutputStream, ShellError> {
let ctrl_c = context.ctrl_c.clone();
let name_tag = context.name.clone();
let (path, p_tag) = match path {
Some(p) => {
let p_tag = p.tag;
let mut p = normalize(p.item);
if p.is_dir() {
if is_empty_dir(&p) {
return Ok(OutputStream::empty());
}
p.push("*");
}
(p, p_tag)
}
None => {
if is_empty_dir(&self.path()) {
return Ok(OutputStream::empty());
2019-08-23 06:51:43 +02:00
} else {
(PathBuf::from("./*"), context.name.clone())
2019-08-23 06:51:43 +02:00
}
}
};
2019-08-07 19:49:11 +02:00
let mut paths = glob::glob(&path.to_string_lossy())
.map_err(|e| ShellError::labeled_error("Glob error", e.to_string(), &p_tag))?
.peekable();
if paths.peek().is_none() {
return Err(ShellError::labeled_error(
"Invalid File or Pattern",
"invalid file or pattern",
&p_tag,
));
}
// Generated stream: impl Stream<Item = Result<ReturnSuccess, ShellError>
let stream = async_stream::try_stream! {
for path in paths {
let path = path.map_err(|e| ShellError::from(e.into_error()))?;
if !all && is_hidden_dir(&path) {
continue;
}
let metadata = match std::fs::symlink_metadata(&path) {
Ok(metadata) => Ok(Some(metadata)),
Err(e) => if let PermissionDenied = e.kind() {
Ok(None)
} else {
Err(e)
},
}?;
let entry = dir_entry_dict(
&path,
metadata.as_ref(),
name_tag.clone(),
full,
short_names,
with_symlink_targets
)
.map(|entry| ReturnSuccess::Value(entry.into()))?;
yield entry;
2019-08-07 19:49:11 +02:00
}
};
Ok(stream.interruptible(ctrl_c).to_output_stream())
2019-08-07 19:49:11 +02:00
}
2019-08-15 07:02:02 +02:00
fn cd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<OutputStream, ShellError> {
2019-08-09 21:42:23 +02:00
let path = match args.nth(0) {
2019-08-07 19:49:11 +02:00
None => match dirs::home_dir() {
Some(o) => o,
_ => {
return Err(ShellError::labeled_error(
"Cannot change to home directory",
"cannot go to home",
&args.call_info.name_tag,
2019-08-07 19:49:11 +02:00
))
}
},
Some(v) => {
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
let target = v.as_path()?;
if target == Path::new("-") {
2019-09-08 11:55:49 +02:00
PathBuf::from(&self.last_path)
} else {
let path = canonicalize_existing(self.path(), target).map_err(|_| {
ShellError::labeled_error(
"Cannot change to directory",
"directory not found",
&v.tag,
)
})?;
2019-09-08 11:55:49 +02:00
if !path.is_dir() {
return Err(ShellError::labeled_error(
"Cannot change to directory",
"is not a directory",
&v.tag,
));
}
#[cfg(unix)]
{
let has_exec = path
.metadata()
.map(|m| {
umask::Mode::from(m.permissions().mode()).has(umask::USER_READ)
})
.map_err(|e| {
ShellError::labeled_error(
"Cannot change to directory",
format!("cannot stat ({})", e),
&v.tag,
)
})?;
if !has_exec {
2019-09-08 11:55:49 +02:00
return Err(ShellError::labeled_error(
"Cannot change to directory",
"permission denied",
&v.tag,
));
}
2019-08-07 19:49:11 +02:00
}
path
2019-08-07 19:49:11 +02:00
}
}
};
let mut stream = VecDeque::new();
2019-09-08 11:55:49 +02:00
2019-09-11 16:36:50 +02:00
stream.push_back(ReturnSuccess::change_cwd(
2019-08-07 19:49:11 +02:00
path.to_string_lossy().to_string(),
));
2019-08-07 19:49:11 +02:00
Ok(stream.into())
}
2019-08-21 19:03:59 +02:00
fn cp(
&self,
CopyArgs {
src,
dst,
recursive,
}: CopyArgs,
name: Tag,
path: &str,
2019-08-24 21:36:19 +02:00
) -> Result<OutputStream, ShellError> {
let name_tag = name;
2019-08-21 19:09:23 +02:00
let path = Path::new(path);
let source = normalize(path.join(&src.item));
let mut destination = normalize(path.join(&dst.item));
2019-08-21 19:03:59 +02:00
let sources: Vec<_> = match glob::glob(&source.to_string_lossy()) {
Ok(files) => files.collect(),
Err(_) => {
return Err(ShellError::labeled_error(
"Invalid pattern",
"invalid pattern",
2019-08-21 19:03:59 +02:00
src.tag,
))
}
};
if sources.len() == 1 {
if let Ok(entry) = &sources[0] {
if entry.is_dir() && !recursive.item {
return Err(ShellError::labeled_error(
"is a directory (not copied). Try using \"--recursive\".",
"is a directory (not copied). Try using \"--recursive\".",
src.tag,
));
}
let mut sources: FileStructure = FileStructure::new();
sources.walk_decorate(&entry)?;
if entry.is_file() {
let strategy = |(source_file, _depth_level)| {
if destination.is_dir() {
2019-08-21 19:03:59 +02:00
let mut new_dst = dunce::canonicalize(destination.clone())?;
if let Some(name) = entry.file_name() {
new_dst.push(name);
}
Ok((source_file, new_dst))
} else {
Ok((source_file, destination.clone()))
}
};
let sources = sources.paths_applying_with(strategy)?;
for (ref src, ref dst) in sources {
if src.is_file() {
match std::fs::copy(src, dst) {
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
name_tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
};
}
}
}
if entry.is_dir() {
if !destination.exists() {
match std::fs::create_dir_all(&destination) {
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
dst.tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
};
let strategy = |(source_file, depth_level)| {
let mut new_dst = destination.clone();
let path = dunce::canonicalize(&source_file)?;
let mut comps: Vec<_> = path
.components()
.map(|fragment| fragment.as_os_str())
.rev()
.take(1 + depth_level)
.collect();
comps.reverse();
for fragment in comps.iter() {
new_dst.push(fragment);
}
Ok((PathBuf::from(&source_file), new_dst))
2019-08-21 19:03:59 +02:00
};
let sources = sources.paths_applying_with(strategy)?;
let dst_tag = dst.tag;
2019-08-21 19:03:59 +02:00
for (ref src, ref dst) in sources {
if src.is_dir() && !dst.exists() {
match std::fs::create_dir_all(dst) {
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
dst_tag,
));
}
Ok(o) => o,
};
2019-08-21 19:03:59 +02:00
}
if src.is_file() {
match std::fs::copy(src, dst) {
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
name_tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
};
}
}
} else {
match entry.file_name() {
Some(name) => destination.push(name),
None => {
return Err(ShellError::labeled_error(
"Copy aborted. Not a valid path",
"not a valid path",
dst.tag,
2019-08-21 19:03:59 +02:00
))
}
}
match std::fs::create_dir_all(&destination) {
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
dst.tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
};
let strategy = |(source_file, depth_level)| {
let mut new_dst = dunce::canonicalize(&destination)?;
let path = dunce::canonicalize(&source_file)?;
let mut comps: Vec<_> = path
.components()
.map(|fragment| fragment.as_os_str())
.rev()
.take(1 + depth_level)
.collect();
comps.reverse();
for fragment in comps.iter() {
new_dst.push(fragment);
}
Ok((PathBuf::from(&source_file), new_dst))
2019-08-21 19:03:59 +02:00
};
let sources = sources.paths_applying_with(strategy)?;
let dst_tag = dst.tag;
2019-08-21 19:03:59 +02:00
for (ref src, ref dst) in sources {
if src.is_dir() && !dst.exists() {
match std::fs::create_dir_all(dst) {
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
dst_tag,
));
}
Ok(o) => o,
};
2019-08-21 19:03:59 +02:00
}
if src.is_file() {
match std::fs::copy(src, dst) {
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
name_tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
};
}
}
}
}
}
} else if destination.exists() {
if !sources.iter().all(|x| match x {
Ok(f) => f.is_file(),
Err(_) => false,
}) {
return Err(ShellError::labeled_error(
2019-08-21 19:03:59 +02:00
"Copy aborted (directories found). Recursive copying in patterns not supported yet (try copying the directory directly)",
"recursive copying in patterns not supported",
2019-08-21 19:03:59 +02:00
src.tag,
));
}
2019-08-21 19:03:59 +02:00
for entry in sources {
if let Ok(entry) = entry {
let mut to = PathBuf::from(&destination);
2019-08-21 19:03:59 +02:00
match entry.file_name() {
Some(name) => to.push(name),
2019-08-21 19:03:59 +02:00
None => {
return Err(ShellError::labeled_error(
"Copy aborted. Not a valid path",
"not a valid path",
dst.tag,
2019-08-21 19:03:59 +02:00
))
}
}
if entry.is_file() {
match std::fs::copy(&entry, &to) {
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
src.tag,
));
}
Ok(o) => o,
};
}
}
2019-08-21 19:03:59 +02:00
}
} else {
let destination_file_name = {
match destination.file_name() {
Some(name) => PathBuf::from(name),
None => {
return Err(ShellError::labeled_error(
"Copy aborted. Not a valid destination",
"not a valid destination",
dst.tag,
))
}
}
};
return Err(ShellError::labeled_error(
format!("Copy aborted. (Does {:?} exist?)", destination_file_name),
format!("copy aborted (does {:?} exist?)", destination_file_name),
dst.tag,
));
2019-08-21 19:03:59 +02:00
}
2019-08-24 21:36:19 +02:00
Ok(OutputStream::empty())
2019-08-21 19:03:59 +02:00
}
fn mkdir(
&self,
MkdirArgs { rest: directories }: MkdirArgs,
name: Tag,
path: &str,
2019-08-24 21:36:19 +02:00
) -> Result<OutputStream, ShellError> {
let path = Path::new(path);
2019-08-21 19:03:59 +02:00
if directories.is_empty() {
2019-08-21 19:03:59 +02:00
return Err(ShellError::labeled_error(
"mkdir requires directory paths",
"needs parameter",
name,
));
}
for dir in directories.iter() {
let create_at = normalize(path.join(&dir.item));
2019-08-21 19:03:59 +02:00
let dir_res = std::fs::create_dir_all(create_at);
if let Err(reason) = dir_res {
return Err(ShellError::labeled_error(
reason.to_string(),
reason.to_string(),
dir.tag(),
));
2019-08-21 19:03:59 +02:00
}
}
2019-08-24 21:36:19 +02:00
Ok(OutputStream::empty())
2019-08-21 19:03:59 +02:00
}
fn mv(
&self,
MoveArgs { src, dst }: MoveArgs,
name: Tag,
path: &str,
2019-08-24 21:36:19 +02:00
) -> Result<OutputStream, ShellError> {
let name_tag = name;
2019-08-21 19:09:23 +02:00
let path = Path::new(path);
let source = normalize(path.join(&src.item));
let mut destination = normalize(path.join(&dst.item));
2019-08-21 19:03:59 +02:00
let sources: Vec<_> = match glob::glob(&source.to_string_lossy()) {
Ok(files) => files.collect(),
Err(_) => {
return Err(ShellError::labeled_error(
"Invalid pattern.",
"invalid pattern",
2019-08-21 19:03:59 +02:00
src.tag,
))
}
};
if sources.is_empty() {
return Err(ShellError::labeled_error(
"Invalid file or pattern.",
"invalid file or pattern",
src.tag,
));
}
2019-08-21 19:03:59 +02:00
let destination_file_name = {
match destination.file_name() {
Some(name) => PathBuf::from(name),
None => {
let name_maybe =
destination.components().next_back().and_then(
|component| match component {
Component::RootDir => Some(PathBuf::from("/")),
Component::ParentDir => destination
.parent()
.and_then(|parent| parent.file_name())
.map(PathBuf::from),
_ => None,
},
);
if let Some(name) = name_maybe {
name
} else {
return Err(ShellError::labeled_error(
"Rename aborted. Not a valid destination",
"not a valid destination",
dst.tag,
));
}
2019-08-21 19:03:59 +02:00
}
}
};
if sources.is_empty() {
return Err(ShellError::labeled_error(
"Move aborted. Not a valid destination",
"not a valid destination",
src.tag,
));
}
2019-08-21 19:03:59 +02:00
if sources.len() == 1 {
if let Ok(entry) = &sources[0] {
let entry_file_name = match entry.file_name() {
Some(name) => name,
None => {
return Err(ShellError::labeled_error(
"Rename aborted. Not a valid entry name",
"not a valid entry name",
src.tag,
2019-08-21 19:03:59 +02:00
))
}
};
if destination.exists() && destination.is_dir() {
destination = match dunce::canonicalize(&destination) {
Ok(path) => path,
Err(e) => {
return Err(ShellError::labeled_error(
format!("Rename aborted. {:}", e.to_string()),
e.to_string(),
dst.tag,
2019-08-21 19:03:59 +02:00
))
}
};
destination.push(entry_file_name);
}
if entry.is_file() {
#[cfg(not(windows))]
{
match std::fs::rename(&entry, &destination) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
));
}
Ok(o) => o,
};
}
#[cfg(windows)]
{
match std::fs::copy(&entry, &destination) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
));
}
Ok(_) => match std::fs::remove_file(&entry) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
));
}
Ok(o) => o,
},
};
}
2019-08-21 19:03:59 +02:00
}
if entry.is_dir() {
match std::fs::create_dir_all(&destination) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
};
#[cfg(not(windows))]
{
match std::fs::rename(&entry, &destination) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
};
}
#[cfg(windows)]
{
let mut sources: FileStructure = FileStructure::new();
sources.walk_decorate(&entry)?;
let strategy = |(source_file, depth_level)| {
let mut new_dst = destination.clone();
let path = dunce::canonicalize(&source_file)?;
let mut comps: Vec<_> = path
.components()
.map(|fragment| fragment.as_os_str())
.rev()
.take(1 + depth_level)
.collect();
comps.reverse();
for fragment in comps.iter() {
new_dst.push(fragment);
}
Ok((PathBuf::from(&source_file), new_dst))
2019-08-21 19:03:59 +02:00
};
let sources = sources.paths_applying_with(strategy)?;
for (ref src, ref dst) in sources {
if src.is_dir() && !dst.exists() {
match std::fs::create_dir_all(dst) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
));
2019-08-21 19:03:59 +02:00
}
Ok(o) => o,
2019-08-21 19:03:59 +02:00
}
} else if src.is_file() {
match std::fs::copy(src, dst) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Moving file {:?} to {:?} aborted. {:}",
src,
dst,
e.to_string(),
),
e.to_string(),
name_tag,
));
}
Ok(_o) => (),
}
2019-08-21 19:03:59 +02:00
}
}
2019-08-21 19:03:59 +02:00
if src.is_file() {
match std::fs::copy(&src, &dst) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
src,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
));
}
Ok(_) => match std::fs::remove_file(&src) {
2019-08-21 19:03:59 +02:00
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
2019-08-21 19:03:59 +02:00
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
},
};
2019-08-21 19:03:59 +02:00
}
match std::fs::remove_dir_all(entry) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
2019-08-21 19:03:59 +02:00
));
}
Ok(o) => o,
};
}
}
}
} else if destination.exists() {
let is_file = |x: &Result<PathBuf, _>| {
x.as_ref().map(|entry| entry.is_file()).unwrap_or_default()
};
if !sources.iter().all(is_file) {
return Err(ShellError::labeled_error(
2019-08-21 19:03:59 +02:00
"Rename aborted (directories found). Renaming in patterns not supported yet (try moving the directory directly)",
"renaming in patterns not supported yet (try moving the directory directly)",
2019-08-21 19:03:59 +02:00
src.tag,
));
}
2019-08-21 19:03:59 +02:00
for entry in sources {
if let Ok(entry) = entry {
let entry_file_name = match entry.file_name() {
Some(name) => name,
None => {
return Err(ShellError::labeled_error(
"Rename aborted. Not a valid entry name",
"not a valid entry name",
src.tag,
))
}
};
2019-08-21 19:03:59 +02:00
let mut to = PathBuf::from(&destination);
to.push(entry_file_name);
2019-08-21 19:03:59 +02:00
if entry.is_file() {
#[cfg(not(windows))]
{
match std::fs::rename(&entry, &to) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
));
}
Ok(o) => o,
};
}
#[cfg(windows)]
{
match std::fs::copy(&entry, &to) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Rename {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
));
}
Ok(_) => match std::fs::remove_file(&entry) {
Err(e) => {
return Err(ShellError::labeled_error(
format!(
"Remove {:?} to {:?} aborted. {:}",
entry_file_name,
destination_file_name,
e.to_string(),
),
e.to_string(),
name_tag,
));
}
Ok(o) => o,
},
};
2019-08-21 19:03:59 +02:00
}
}
}
}
} else {
return Err(ShellError::labeled_error(
format!("Rename aborted. (Does {:?} exist?)", destination_file_name),
format!("rename aborted (does {:?} exist?)", destination_file_name),
dst.tag,
));
2019-08-21 19:03:59 +02:00
}
2019-08-24 21:36:19 +02:00
Ok(OutputStream::empty())
2019-08-21 19:03:59 +02:00
}
fn rm(
&self,
2019-10-19 22:52:39 +02:00
RemoveArgs {
rest: targets,
2019-10-19 22:52:39 +02:00
recursive,
2020-04-11 08:53:53 +02:00
trash: _trash,
2019-10-19 22:52:39 +02:00
}: RemoveArgs,
name: Tag,
path: &str,
2019-08-24 21:36:19 +02:00
) -> Result<OutputStream, ShellError> {
let name_tag = name;
2019-08-21 19:09:23 +02:00
if targets.is_empty() {
2019-08-21 19:03:59 +02:00
return Err(ShellError::labeled_error(
"rm requires target paths",
"needs parameter",
name_tag,
2019-08-21 19:03:59 +02:00
));
}
let path = Path::new(path);
let mut all_targets: HashMap<PathBuf, Tag> = HashMap::new();
for target in targets {
let all_dots = target
.item
.to_str()
.map_or(false, |v| v.chars().all(|c| c == '.'));
if all_dots {
return Err(ShellError::labeled_error(
"Cannot remove any parent directory",
"cannot remove any parent directory",
target.tag,
));
}
2019-08-22 06:23:57 +02:00
let path = normalize(path.join(&target.item));
match glob::glob(&path.to_string_lossy()) {
Ok(files) => {
for file in files {
match file {
Ok(ref f) => {
all_targets
.entry(f.clone())
.or_insert_with(|| target.tag.clone());
}
Err(e) => {
return Err(ShellError::labeled_error(
format!("Could not remove {:}", path.to_string_lossy()),
e.to_string(),
&target.tag,
));
}
}
}
}
Err(e) => {
return Err(ShellError::labeled_error(
e.to_string(),
e.to_string(),
&name_tag,
))
}
};
}
if all_targets.is_empty() {
return Err(ShellError::labeled_error(
"No valid paths",
"no valid paths",
name_tag,
));
}
let stream = async_stream! {
for (f, tag) in all_targets.iter() {
let is_empty = || match f.read_dir() {
Ok(mut p) => p.next().is_none(),
Err(_) => false
};
if let Ok(metadata) = f.symlink_metadata() {
if metadata.is_file() || metadata.file_type().is_symlink() || recursive.item || is_empty() {
2020-04-11 08:53:53 +02:00
let result;
#[cfg(feature = "trash-support")]
{
result = if _trash.item {
trash::remove(f)
.map_err(|e| f.to_string_lossy())
} else if metadata.is_file() {
std::fs::remove_file(f)
.map_err(|e| f.to_string_lossy())
} else {
std::fs::remove_dir_all(f)
.map_err(|e| f.to_string_lossy())
};
}
#[cfg(not(feature = "trash-support"))]
{
result = if metadata.is_file() {
std::fs::remove_file(f)
.map_err(|e| f.to_string_lossy())
} else {
std::fs::remove_dir_all(f)
.map_err(|e| f.to_string_lossy())
};
}
if let Err(e) = result {
let msg = format!("Could not delete {:}", e);
yield Err(ShellError::labeled_error(msg, e, tag))
} else {
let val = format!("deleted {:}", f.to_string_lossy()).into();
yield Ok(ReturnSuccess::Value(val))
}
} else {
let msg = format!(
"Cannot remove {:}. try --recursive",
f.to_string_lossy()
);
yield Err(ShellError::labeled_error(
msg,
"cannot remove non-empty directory",
tag,
))
}
} else {
let msg = format!("no such file or directory: {:}", f.to_string_lossy());
yield Err(ShellError::labeled_error(
msg,
"no such file or directory",
tag,
))
2019-08-21 19:03:59 +02:00
}
}
};
Ok(stream.to_output_stream())
2019-08-21 19:03:59 +02:00
}
2019-08-07 19:49:11 +02:00
fn path(&self) -> String {
self.path.clone()
}
fn pwd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<OutputStream, ShellError> {
let path = PathBuf::from(self.path());
let p = match dunce::canonicalize(path.as_path()) {
Ok(p) => p,
Err(_) => {
return Err(ShellError::labeled_error(
"unable to show current directory",
"pwd command failed",
&args.call_info.name_tag,
));
}
};
let mut stream = VecDeque::new();
stream.push_back(ReturnSuccess::value(
UntaggedValue::Primitive(Primitive::String(p.to_string_lossy().to_string()))
.into_value(&args.call_info.name_tag),
));
Ok(stream.into())
}
2019-08-07 19:49:11 +02:00
fn set_path(&mut self, path: String) {
2019-08-08 02:52:29 +02:00
let pathbuf = PathBuf::from(&path);
let path = match dunce::canonicalize(pathbuf.as_path()) {
Ok(path) => {
let _ = std::env::set_current_dir(&path);
path
}
_ => {
// TODO: handle the case where the path cannot be canonicalized
pathbuf
}
};
self.last_path = self.path.clone();
2019-08-08 02:52:29 +02:00
self.path = path.to_string_lossy().to_string();
2019-08-07 19:49:11 +02:00
}
fn complete(
&self,
line: &str,
pos: usize,
ctx: &rustyline::Context<'_>,
2019-08-09 21:42:23 +02:00
) -> Result<(usize, Vec<rustyline::completion::Pair>), rustyline::error::ReadlineError> {
2019-08-07 19:49:11 +02:00
self.completer.complete(line, pos, ctx)
}
fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
2019-08-07 19:49:11 +02:00
self.hinter.hint(line, pos, ctx)
}
}
fn is_empty_dir(dir: impl AsRef<Path>) -> bool {
match dir.as_ref().read_dir() {
Err(_) => true,
Ok(mut s) => s.next().is_none(),
}
}
fn is_hidden_dir(dir: impl AsRef<Path>) -> bool {
cfg_if::cfg_if! {
if #[cfg(windows)] {
use std::os::windows::fs::MetadataExt;
if let Ok(metadata) = dir.as_ref().metadata() {
let attributes = metadata.file_attributes();
// https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants
(attributes & 0x2) != 0
} else {
false
}
} else {
dir.as_ref()
.file_name()
.map(|name| name.to_string_lossy().starts_with('.'))
.unwrap_or(false)
}
}
}