nushell/src/commands/cd.rs

87 lines
2.3 KiB
Rust
Raw Normal View History

2019-08-02 21:15:07 +02:00
use crate::commands::StaticCommand;
2019-05-11 09:00:33 +02:00
use crate::errors::ShellError;
use crate::prelude::*;
2019-05-18 04:53:20 +02:00
use std::env;
2019-08-02 21:15:07 +02:00
use std::path::PathBuf;
2019-05-11 09:00:33 +02:00
2019-08-02 21:15:07 +02:00
pub struct Cd;
2019-06-13 23:47:25 +02:00
2019-08-02 21:15:07 +02:00
#[derive(Deserialize)]
pub struct CdArgs {
2019-08-09 06:51:21 +02:00
target: Option<Tagged<PathBuf>>,
2019-08-02 21:15:07 +02:00
}
impl StaticCommand for Cd {
fn name(&self) -> &str {
"cd"
}
fn signature(&self) -> Signature {
Signature::build("cd")
.optional("target", SyntaxType::Path)
.filter()
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, cd)?.run()
// cd(args, registry)
}
}
pub fn cd(CdArgs { target }: CdArgs, context: RunnableContext) -> Result<OutputStream, ShellError> {
let cwd = context.cwd().to_path_buf();
let path = match &target {
2019-07-16 21:10:25 +02:00
None => match dirs::home_dir() {
Some(o) => o,
_ => {
2019-08-09 06:51:21 +02:00
return Err(ShellError::labeled_error(
2019-07-16 21:10:25 +02:00
"Can not change to home directory",
"can not go to home",
2019-08-02 21:15:07 +02:00
context.name,
2019-07-16 21:10:25 +02:00
))
}
},
Some(v) => {
2019-08-02 21:15:07 +02:00
// let target = v.item.as_string()?;
match dunce::canonicalize(cwd.join(&v.item()).as_path()) {
2019-07-16 21:10:25 +02:00
Ok(p) => p,
2019-06-08 00:35:07 +02:00
Err(_) => {
2019-07-16 21:10:25 +02:00
return Err(ShellError::labeled_error(
"Can not change to directory",
"directory not found",
2019-08-09 06:51:21 +02:00
v.span(),
2019-07-16 21:10:25 +02:00
));
2019-06-08 00:35:07 +02:00
}
}
2019-06-03 09:41:28 +02:00
}
2019-07-16 21:10:25 +02:00
};
let mut stream = VecDeque::new();
match env::set_current_dir(&path) {
Ok(_) => {}
Err(_) => {
2019-08-02 21:15:07 +02:00
if let Some(path) = target {
2019-07-16 21:10:25 +02:00
return Err(ShellError::labeled_error(
"Can not change to directory",
"directory not found",
2019-08-09 06:51:21 +02:00
path.span(),
2019-07-16 21:10:25 +02:00
));
} else {
return Err(ShellError::string("Can not change to directory"));
}
2019-06-08 00:35:07 +02:00
}
}
2019-08-09 06:51:21 +02:00
stream.push_back(ReturnSuccess::change_cwd(
path.to_string_lossy().to_string(),
));
2019-07-16 21:10:25 +02:00
Ok(stream.into())
2019-08-09 06:51:21 +02:00
// pub fn cd(args: CommandArgs) -> Result<OutputStream, ShellError> {
// args.shell_manager.cd(args.call_info, args.input)
2019-05-11 09:00:33 +02:00
}