Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
ryuichiueda committed Dec 31, 2023
1 parent 5f15c80 commit db1ccc6
Showing 1 changed file with 37 additions and 12 deletions.
49 changes: 37 additions & 12 deletions src/core/builtins/cd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,33 @@
use crate::ShellCore;
use super::utils;

pub fn cd(core: &mut ShellCore, args: &mut Vec<String>) -> i32 {
if args.len() > 2 {
eprintln!("sush: cd: too many arguments");
fn cd_1arg(core: &mut ShellCore, args: &mut Vec<String>) -> i32 {
let var = "~".to_string();
args.push(var);
set_oldpwd(core);
change_directory(core, args)
}

fn cd_oldpwd(core: &mut ShellCore, args: &mut Vec<String>) -> i32 {
if let Some(old) = core.vars.get("OLDPWD") {
println!("{}", &old);
args[1] = old.to_string();
}else {
eprintln!("sush: cd: OLDPWD not set");
return 1;
}

if args.len() == 1 { //only "cd"
let var = "~".to_string();
args.push(var);
}else if args.len() == 2 && args[1] == "-" { // cd -
if let Some(old) = core.vars.get("OLDPWD") {
println!("{}", &old);
args[1] = old.to_string();
}
};
set_oldpwd(core);
change_directory(core, args)
}

fn set_oldpwd(core: &mut ShellCore) {
if let Some(old) = core.get_current_directory().clone() {
core.vars.insert("OLDPWD".to_string(), old.display().to_string());
};
}

fn change_directory(core: &mut ShellCore, args: &mut Vec<String>) -> i32 {
let path = utils::make_canonical_path(utils::make_absolute_path(core, &args[1]));
if core.set_current_directory(&path).is_ok() {
core.vars.insert("PWD".to_string(), path.display().to_string());
Expand All @@ -34,3 +41,21 @@ pub fn cd(core: &mut ShellCore, args: &mut Vec<String>) -> i32 {
1
}
}

pub fn cd(core: &mut ShellCore, args: &mut Vec<String>) -> i32 {
if args.len() > 2 {
eprintln!("sush: cd: too many arguments");
return 1;
}

if args.len() == 1 { //only "cd"
return cd_1arg(core, args);
}

if args[1] == "-" { // cd -
cd_oldpwd(core, args)
}else{ // cd /some/dir
set_oldpwd(core);
change_directory(core, args)
}
}

0 comments on commit db1ccc6

Please sign in to comment.