From 38dff41e25eef626a11cb63c3e8567509fdb3f23 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 12 Jun 2023 01:31:33 +0300 Subject: [PATCH] Userspace: Shell processes PS1 '\~' as cwd and implement cd --- userspace/Shell/main.cpp | 49 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/userspace/Shell/main.cpp b/userspace/Shell/main.cpp index 388a8228..087ca82f 100644 --- a/userspace/Shell/main.cpp +++ b/userspace/Shell/main.cpp @@ -72,6 +72,31 @@ int execute_command(BAN::StringView command) setenv(name, value, true); } } + else if (args.front() == "cd"sv) + { + if (args.size() > 2) + { + printf("cd: too many arguments\n"); + return 1; + } + + const char* path = nullptr; + + if (args.size() == 1) + { + path = getenv("HOME"); + if (path == nullptr) + return 0; + } + else + path = args[1]; + + if (chdir(args.size() == 2 ? args[1] : getenv("HOME")) == -1) + { + perror("chdir"); + return 1; + } + } else { pid_t pid = fork(); @@ -121,7 +146,7 @@ BAN::String get_prompt() { const char* raw_prompt = getenv("PS1"); if (raw_prompt == nullptr) - raw_prompt = "\e[32muser@host\e[m:\e[34m/\e[m$ "; + raw_prompt = "\e[32muser@host\e[m:\e[34m\\~\e[m$ "; BAN::String prompt; for (int i = 0; raw_prompt[i]; i++) @@ -140,6 +165,26 @@ BAN::String get_prompt() case '\\': MUST(prompt.push_back('\\')); break; + case '~': + { + char buffer[256]; + if (getcwd(buffer, sizeof(buffer)) == nullptr) + strcpy(buffer, strerrorname_np(errno)); + + const char* home = getenv("HOME"); + size_t home_len = home ? strlen(home) : 0; + if (home && strncmp(buffer, home, home_len) == 0) + { + MUST(prompt.push_back('~')); + MUST(prompt.append(buffer + home_len)); + } + else + { + MUST(prompt.append(buffer)); + } + + break; + } case '\0': MUST(prompt.push_back('\\')); break; @@ -154,7 +199,7 @@ BAN::String get_prompt() MUST(prompt.push_back(ch)); } } - + return prompt; }