Brijesh's Git Server — bsh @ 3d7aa100971d1182386de49054e85b37e6ef1ef7

my own shell program

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
commit

3d7aa100971d1182386de49054e85b37e6ef1ef7

parent

476de6711bde624186baf0ab1b748a04341e0644

3 files changed, 48 insertions(+), 8 deletions(-)

jump to
M src/main.rssrc/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.rssrc/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();