From f9206e16de858b4600777aee59ac712c885e883a Mon Sep 17 00:00:00 2001 From: fdai7451 Date: Sat, 21 Jan 2023 17:08:02 +0100 Subject: [PATCH] feat: change directory to home if no argument is given to cd --- Cargo.lock | 21 +++++++++++++++++++++ Cargo.toml | 1 + src/builtins/cd.rs | 13 ++++++++++--- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a21cffb..08a8f0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,6 +60,15 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "dirs" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" +dependencies = [ + "dirs-sys", +] + [[package]] name = "dirs-next" version = "2.0.0" @@ -70,6 +79,17 @@ dependencies = [ "dirs-sys-next", ] +[[package]] +name = "dirs-sys" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + [[package]] name = "dirs-sys-next" version = "0.1.2" @@ -210,6 +230,7 @@ version = "0.1.0" dependencies = [ "crossbeam-channel", "ctrlc", + "dirs", "once_cell", "rustyline", "shlex", diff --git a/Cargo.toml b/Cargo.toml index 15abb06..11a2d1d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] crossbeam-channel = "0.5" ctrlc = "3.2" +dirs = "4.0" once_cell = "1.17" rustyline = "10.1.0" shlex = "1.1" diff --git a/src/builtins/cd.rs b/src/builtins/cd.rs index 5b03ffe..877c3f1 100644 --- a/src/builtins/cd.rs +++ b/src/builtins/cd.rs @@ -1,5 +1,6 @@ use crate::builtins::{Builtin, BuiltinConfig}; use std::env::set_current_dir; +use std::path::Path; use crate::error::ShellError; @@ -7,11 +8,17 @@ pub struct Cd; impl Builtin for Cd { fn execute(&mut self, _: &mut BuiltinConfig, args: Vec) -> Result<(), ShellError> { - let Some(first) = args.get(0) else { - return Err(ShellError::ExecuteFailure("no argument given".to_string())) + let dir = match args.get(0) { + Some(first) => Path::new(first).to_path_buf(), + None => { + let Some(home) = dirs::home_dir() else { + return Ok(()) + }; + home + } }; - set_current_dir(first).map_err(|e| ShellError::ExecuteFailure(e.to_string())) + set_current_dir(dir).map_err(|e| ShellError::ExecuteFailure(e.to_string())) } }