Skip to content

Commit

Permalink
feat: implement cd for user_shell
Browse files Browse the repository at this point in the history
fix: path handling
  • Loading branch information
Yttehs-HDX committed Dec 3, 2024
1 parent d8187be commit 7573b99
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 7 deletions.
4 changes: 2 additions & 2 deletions kernel/src/fs/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl PathUtil {

pub fn parent(&self) -> String {
let mut split = self.split();
if split.len() == 1 {
if split.len() == 1 || split.len() == 0 {
return ROOT_DIR.to_string();
}
split.pop();
Expand All @@ -75,7 +75,7 @@ impl PathUtil {
pub fn name(&self) -> String {
let mut split = self.split();
if split.len() == 0 {
return ROOT_DIR.to_string();
return "".to_string();
}
split.pop().unwrap().to_string()
}
Expand Down
11 changes: 8 additions & 3 deletions kernel/src/syscall/fs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use crate::{
fs::{self, Inode, InodeType, OpenFlags, PathUtil},
syscall::translate_str,
task,
config::ROOT_DIR, fs::{self, Inode, InodeType, OpenFlags, PathUtil}, syscall::translate_str, task
};
use alloc::string::ToString;

Expand All @@ -28,6 +26,13 @@ pub fn sys_write(fd: usize, buffer: *const u8, len: usize) -> isize {
pub fn sys_chdir(path_ptr: *const u8) -> isize {
let path = translate_str(path_ptr);
let path = PathUtil::from_user(path).to_string();

if path == ROOT_DIR {
// '/' could not be opened
task::get_processor().current().inner_mut().set_cwd(ROOT_DIR.to_string());
return 0;
}

let inode = fs::open_file(&path, OpenFlags::RDONLY);
if let Some(inode) = inode {
if inode.get_type() == InodeType::Dir {
Expand Down
Binary file modified test/test.img
Binary file not shown.
10 changes: 8 additions & 2 deletions user/src/bin/user_shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#![no_main]

use user_lib::{
alloc::string::String, exec, exit, fork, get_char, init_heap, print, println, waitpid,
alloc::string::String, chdir, exec, exit, fork, get_char, init_heap, print, println, waitpid
};

extern crate user_lib;
Expand Down Expand Up @@ -37,6 +37,12 @@ fn main() -> i32 {
print!("\x1b[H\x1b[2J");
}
"exit" => break,
_ if input.starts_with("cd ") => {
let path = input.strip_prefix("cd ").unwrap();
if chdir(path) != 0 {
println!("{}: cd: {}: No such file or directory", SHELL_NAME, path);
}
}
_ => {
// mark input as path
input.push('\0');
Expand All @@ -61,7 +67,7 @@ fn main() -> i32 {
}
}
print_prompt();
input.clear();
input = String::new();
}
BS | DL => {
if !input.is_empty() {
Expand Down

0 comments on commit 7573b99

Please sign in to comment.