nushell/src/commands/cd.rs

53 lines
1.6 KiB
Rust
Raw Normal View History

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-05-11 09:00:33 +02:00
pub fn cd(args: CommandArgs) -> Result<OutputStream, ShellError> {
2019-06-13 23:47:25 +02:00
let env = args.env.lock().unwrap();
2019-07-16 21:10:25 +02:00
let cwd = env.path().to_path_buf();
2019-06-13 23:47:25 +02:00
2019-07-16 21:10:25 +02:00
let path = match args.nth(0) {
None => match dirs::home_dir() {
Some(o) => o,
_ => {
return Err(ShellError::labeled_error(
2019-07-16 21:10:25 +02:00
"Can not change to home directory",
"can not go to home",
args.call_info.name_span,
2019-07-16 21:10:25 +02:00
))
}
},
Some(v) => {
let target = v.as_string()?;
match dunce::canonicalize(cwd.join(target).as_path()) {
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-01 03:58:42 +02:00
v.span().clone(),
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(_) => {
if args.len() > 0 {
return Err(ShellError::labeled_error(
"Can not change to directory",
"directory not found",
2019-08-01 03:58:42 +02:00
args.nth(0).unwrap().span().clone(),
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-07-16 21:10:25 +02:00
stream.push_back(ReturnSuccess::change_cwd(path));
Ok(stream.into())
2019-05-11 09:00:33 +02:00
}