Merge pull request #98 from xiuxiu62/main

port `cp` to fs commands
This commit is contained in:
JT 2021-10-06 11:20:18 +13:00 committed by GitHub
commit b35d47c500
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 284 additions and 0 deletions

View file

@ -17,6 +17,7 @@ pub fn create_default_context() -> Rc<RefCell<EngineState>> {
working_set.add_decl(Box::new(Benchmark));
working_set.add_decl(Box::new(BuildString));
working_set.add_decl(Box::new(Cd));
working_set.add_decl(Box::new(Cp));
working_set.add_decl(Box::new(Def));
working_set.add_decl(Box::new(Do));
working_set.add_decl(Box::new(Each));

View file

@ -0,0 +1,169 @@
use std::env::current_dir;
use std::path::PathBuf;
use nu_engine::CallExt;
use nu_path::canonicalize_with;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EvaluationContext};
use nu_protocol::{ShellError, Signature, SyntaxShape, Value};
use crate::filesystem::util::FileStructure;
pub struct Cp;
impl Command for Cp {
fn name(&self) -> &str {
"cp"
}
fn usage(&self) -> &str {
"Copy files."
}
fn signature(&self) -> Signature {
Signature::build("cp")
.required("source", SyntaxShape::GlobPattern, "the place to copy from")
.required("destination", SyntaxShape::Filepath, "the place to copy to")
.switch(
"recursive",
"copy recursively through subdirectories",
Some('r'),
)
}
fn run(
&self,
context: &EvaluationContext,
call: &Call,
_input: Value,
) -> Result<Value, ShellError> {
let source: String = call.req(context, 0)?;
let destination: String = call.req(context, 1)?;
let path: PathBuf = current_dir().unwrap();
let source = path.join(source.as_str());
let destination = path.join(destination.as_str());
let sources =
glob::glob(&source.to_string_lossy()).map_or_else(|_| Vec::new(), Iterator::collect);
if sources.is_empty() {
return Err(ShellError::FileNotFound(call.positional[0].span));
}
if sources.len() > 1 && !destination.is_dir() {
return Err(ShellError::MoveNotPossible {
source_message: "Can't move many files".to_string(),
source_span: call.positional[0].span,
destination_message: "into single file".to_string(),
destination_span: call.positional[1].span,
});
}
let any_source_is_dir = sources.iter().any(|f| matches!(f, Ok(f) if f.is_dir()));
let recursive = call.named.iter().any(|p| &p.0 == "recursive");
if any_source_is_dir && !recursive {
return Err(ShellError::MoveNotPossibleSingle(
"Directories must be copied using \"--recursive\"".to_string(),
call.positional[0].span,
));
}
for entry in sources.into_iter().flatten() {
let mut sources = FileStructure::new();
sources.walk_decorate(&entry)?;
if entry.is_file() {
let sources = sources.paths_applying_with(|(source_file, _depth_level)| {
if destination.is_dir() {
let mut dest = canonicalize_with(&destination, &path)?;
if let Some(name) = entry.file_name() {
dest.push(name);
}
Ok((source_file, dest))
} else {
Ok((source_file, destination.clone()))
}
})?;
for (src, dst) in sources {
if src.is_file() {
std::fs::copy(&src, dst).map_err(|e| {
ShellError::MoveNotPossibleSingle(
format!(
"failed to move containing file \"{}\": {}",
src.to_string_lossy(),
e
),
call.positional[0].span,
)
})?;
}
}
} else if entry.is_dir() {
let destination = if !destination.exists() {
destination.clone()
} else {
match entry.file_name() {
Some(name) => destination.join(name),
None => {
return Err(ShellError::FileNotFoundCustom(
format!("containing \"{:?}\" is not a valid path", entry),
call.positional[0].span,
))
}
}
};
std::fs::create_dir_all(&destination).map_err(|e| {
ShellError::MoveNotPossibleSingle(
format!("failed to recursively fill destination: {}", e),
call.positional[1].span,
)
})?;
let sources = sources.paths_applying_with(|(source_file, depth_level)| {
let mut dest = destination.clone();
let path = canonicalize_with(&source_file, &path)?;
let components = path
.components()
.map(|fragment| fragment.as_os_str())
.rev()
.take(1 + depth_level);
components.for_each(|fragment| dest.push(fragment));
Ok((PathBuf::from(&source_file), dest))
})?;
for (src, dst) in sources {
if src.is_dir() && !dst.exists() {
std::fs::create_dir_all(&dst).map_err(|e| {
ShellError::MoveNotPossibleSingle(
format!(
"failed to create containing directory \"{}\": {}",
dst.to_string_lossy(),
e
),
call.positional[1].span,
)
})?;
}
if src.is_file() {
std::fs::copy(&src, &dst).map_err(|e| {
ShellError::MoveNotPossibleSingle(
format!(
"failed to move containing file \"{}\": {}",
src.to_string_lossy(),
e
),
call.positional[0].span,
)
})?;
}
}
}
}
Ok(Value::Nothing { span: call.head })
}
}

View file

@ -1,7 +1,10 @@
mod cd;
mod cp;
mod ls;
mod mv;
mod util;
pub use cd::Cd;
pub use cp::Cp;
pub use ls::Ls;
pub use mv::Mv;

View file

@ -0,0 +1,81 @@
use std::path::{Path, PathBuf};
use nu_path::canonicalize_with;
use nu_protocol::ShellError;
#[derive(Default)]
pub struct FileStructure {
pub resources: Vec<Resource>,
}
#[allow(dead_code)]
impl FileStructure {
pub fn new() -> FileStructure {
FileStructure { resources: vec![] }
}
pub fn contains_more_than_one_file(&self) -> bool {
self.resources.len() > 1
}
pub fn contains_files(&self) -> bool {
!self.resources.is_empty()
}
pub fn paths_applying_with<F>(
&mut self,
to: F,
) -> Result<Vec<(PathBuf, PathBuf)>, Box<dyn std::error::Error>>
where
F: Fn((PathBuf, usize)) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>>,
{
self.resources
.iter()
.map(|f| (PathBuf::from(&f.location), f.at))
.map(to)
.collect()
}
pub fn walk_decorate(&mut self, start_path: &Path) -> Result<(), ShellError> {
self.resources = Vec::<Resource>::new();
self.build(start_path, 0)?;
self.resources.sort();
Ok(())
}
fn build(&mut self, src: &Path, lvl: usize) -> Result<(), ShellError> {
let source = canonicalize_with(src, std::env::current_dir()?)?;
if source.is_dir() {
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
self.build(&path, lvl + 1)?;
}
self.resources.push(Resource {
location: path.to_path_buf(),
at: lvl,
});
}
} else {
self.resources.push(Resource {
location: source,
at: lvl,
});
}
Ok(())
}
}
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Resource {
pub at: usize,
pub location: PathBuf,
}
impl Resource {}

View file

@ -83,10 +83,18 @@ pub enum ShellError {
#[diagnostic(code(nu::shell::file_not_found), url(docsrs))]
FileNotFound(#[label("file not found")] Span),
#[error("File not found")]
#[diagnostic(code(nu::shell::file_not_found), url(docsrs))]
FileNotFoundCustom(String, #[label("{0}")] Span),
#[error("Directory not found")]
#[diagnostic(code(nu::shell::directory_not_found), url(docsrs))]
DirectoryNotFound(#[label("directory not found")] Span),
#[error("File not found")]
#[diagnostic(code(nu::shell::file_not_found), url(docsrs))]
DirectoryNotFoundCustom(String, #[label("{0}")] Span),
#[error("Move not possible")]
#[diagnostic(code(nu::shell::move_not_possible), url(docsrs))]
MoveNotPossible {
@ -97,4 +105,26 @@ pub enum ShellError {
#[label("{destination_message}")]
destination_span: Span,
},
#[error("Move not possible")]
#[diagnostic(code(nu::shell::move_not_possible_single), url(docsrs))]
MoveNotPossibleSingle(String, #[label("{0}")] Span),
}
impl From<std::io::Error> for ShellError {
fn from(input: std::io::Error) -> ShellError {
ShellError::InternalError(format!("{:?}", input))
}
}
impl std::convert::From<Box<dyn std::error::Error>> for ShellError {
fn from(input: Box<dyn std::error::Error>) -> ShellError {
ShellError::InternalError(input.to_string())
}
}
impl From<Box<dyn std::error::Error + Send + Sync>> for ShellError {
fn from(input: Box<dyn std::error::Error + Send + Sync>) -> ShellError {
ShellError::InternalError(format!("{:?}", input))
}
}