feat(prompt): make the prompt show current path and git branch name
Brijesh Wawdhane brijesh@wawdhane.com
Sun, 27 Oct 2024 01:06:03 +0530
3 files changed,
48 insertions(+),
8 deletions(-)
M
src/main.rs
→
src/main.rs
@@ -4,6 +4,7 @@ mod colours;
mod error; mod executor; mod parser; +mod prompt; mod shell; mod tests;
A
src/prompt.rs
@@ -0,0 +1,42 @@
+use crate::colours::{blue, green, yellow}; +use std::env; +use std::path::Path; +use std::process::Command; + +pub fn generate_prompt() -> String { + let current_dir = env::current_dir().unwrap_or_else(|_| Path::new("").to_path_buf()); + let current_dir_str = current_dir.to_str().unwrap_or(""); + + let home_dir = env::var("HOME").unwrap_or_else(|_| String::from("/")); + let display_dir = if current_dir_str.starts_with(&home_dir) { + current_dir_str.replacen(&home_dir, "~", 1) + } else { + current_dir_str.to_string() + }; + + let branch_name = if current_dir.join(".git").exists() { + Command::new("git") + .args(&["rev-parse", "--abbrev-ref", "HEAD"]) + .output() + .ok() + .and_then(|output| { + if output.status.success() { + String::from_utf8(output.stdout) + .ok() + .map(|s| s.trim().to_string()) + } else { + None + } + }) + .unwrap_or_else(|| "".to_string()) + } else { + "".to_string() + }; + + format!( + "{} {} {} ", + blue(&display_dir), + green(&branch_name), + yellow("❯") + ) +}
M
src/shell.rs
→
src/shell.rs
@@ -1,21 +1,18 @@
use crate::colours::red; -use crate::{error::ShellError, executor}; +use crate::{error::ShellError, executor, prompt}; use std::io::{self, Write}; -pub struct Shell { - prompt: String, -} +pub struct Shell; impl Shell { pub fn new() -> Self { - Self { - prompt: "bsh> ".to_string(), - } + Self } pub fn run(&mut self) -> Result<(), ShellError> { loop { - print!("{}", self.prompt); + let prompt = prompt::generate_prompt(); + print!("{}", prompt); io::stdout().flush().map_err(ShellError::from)?; let mut input = String::new();