From 7b27e81c896920545734bee19b592636d282ddad Mon Sep 17 00:00:00 2001 From: candifloss Date: Thu, 21 Nov 2024 14:09:00 +0530 Subject: [PATCH 01/23] introduce modularity --- src/git.rs | 55 +++++++++++++++++++++++++++++++++++++ src/main.rs | 79 ++++++----------------------------------------------- src/ssh.rs | 10 +++++++ src/user.rs | 20 ++++++++++++++ 4 files changed, 94 insertions(+), 70 deletions(-) create mode 100644 src/git.rs create mode 100644 src/ssh.rs create mode 100644 src/user.rs diff --git a/src/git.rs b/src/git.rs new file mode 100644 index 0000000..24b006a --- /dev/null +++ b/src/git.rs @@ -0,0 +1,55 @@ +use colored::{ColoredString, Colorize}; +use std::process::Command; + +pub fn get_git_branch() -> String { + let git_status_cmd = Command::new("git") + .arg("status") + .output() + .expect("git_status_cmd_fail"); + let git_status_output = String::from_utf8_lossy(&git_status_cmd.stdout); + let git_err = String::from_utf8_lossy(&git_status_cmd.stderr); + + if git_err == "" { + git_status_output.split('\n').collect::>()[0] + .split(' ') + .collect::>()[2] + .to_string() + } else { + String::new() + } +} + +pub fn get_git_root() -> String { + let git_repo_root_cmd = Command::new("git") + .arg("rev-parse") + .arg("--show-toplevel") + .output() + .expect("git_repo_root_cmd_fail"); + let mut git_repo_path = String::from_utf8_lossy(&git_repo_root_cmd.stdout).to_string(); + let git_repo_err = String::from_utf8_lossy(&git_repo_root_cmd.stderr); + + if git_repo_err == "" { + let len = git_repo_path.trim_end_matches(&['\r', '\n'][..]).len(); + git_repo_path.truncate(len); + } else { + git_repo_path = String::new(); + } + git_repo_path +} + +pub fn get_git_repo_name(git_repo_root: &str) -> String { + let repo_path_split: Vec<&str> = git_repo_root.split('/').collect(); + let last_index = repo_path_split.len() - 1; + let git_repo_name = repo_path_split[last_index]; + + git_repo_name.to_string() +} + +pub fn get_git_char(git_branch: &str) -> ColoredString { + match git_branch { + "" => "".clear(), + "main" => " 󰊢 ".truecolor(178, 98, 44), + "master" => " 󰊢 ".truecolor(196, 132, 29), + _ => " 󰊢 ".truecolor(82, 82, 82), + } +} diff --git a/src/main.rs b/src/main.rs index 7bd6c8c..b1c24fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,11 @@ use colored::{ColoredString, Colorize}; use std::env::{args, current_dir, var_os}; -use std::process::Command; +mod git; +mod ssh; +mod user; +use crate::git::*; +use crate::ssh::*; +use crate::user::*; fn get_shell_char(shell: &str) -> String { let shell_char = match shell { @@ -15,59 +20,6 @@ fn get_shell_char(shell: &str) -> String { shell_char.to_string() } -fn get_git_branch() -> String { - let git_status_cmd = Command::new("git") - .arg("status") - .output() - .expect("git_status_cmd_fail"); - let git_status_output = String::from_utf8_lossy(&git_status_cmd.stdout); - let git_err = String::from_utf8_lossy(&git_status_cmd.stderr); - - if git_err == "" { - git_status_output.split('\n').collect::>()[0] - .split(' ') - .collect::>()[2] - .to_string() - } else { - String::new() - } -} - -fn get_git_root() -> String { - let git_repo_root_cmd = Command::new("git") - .arg("rev-parse") - .arg("--show-toplevel") - .output() - .expect("git_repo_root_cmd_fail"); - let mut git_repo_path = String::from_utf8_lossy(&git_repo_root_cmd.stdout).to_string(); - let git_repo_err = String::from_utf8_lossy(&git_repo_root_cmd.stderr); - - if git_repo_err == "" { - let len = git_repo_path.trim_end_matches(&['\r', '\n'][..]).len(); - git_repo_path.truncate(len); - } else { - git_repo_path = String::new(); - } - git_repo_path -} - -fn get_git_repo_name(git_repo_root: &str) -> String { - let repo_path_split: Vec<&str> = git_repo_root.split('/').collect(); - let last_index = repo_path_split.len() - 1; - let git_repo_name = repo_path_split[last_index]; - - git_repo_name.to_string() -} - -fn get_git_char(git_branch: &str) -> ColoredString { - match git_branch { - "" => "".clear(), - "main" => " 󰊢 ".truecolor(178, 98, 44), - "master" => " 󰊢 ".truecolor(196, 132, 29), - _ => " 󰊢 ".truecolor(82, 82, 82), - } -} - fn abrev_path(path: &str) -> String { let mut short_dir = path.to_string(); @@ -92,13 +44,6 @@ fn abrev_path(path: &str) -> String { fn main() -> std::io::Result<()> { let angle = "❯"; - //Root user indicator - let user = var_os("USER") - .expect("UnknownUser") - .to_str() - .expect("UnknownUser") - .to_string(); - let mut err: String = String::new(); let args: Vec = args().collect(); @@ -112,21 +57,15 @@ fn main() -> std::io::Result<()> { shell = "none".to_string(); } - let root_indicator = match user.as_str() { - "root" => angle.truecolor(255, 53, 94), - _ => angle.truecolor(0, 255, 180), - }; + let root_indicator = root_indicator(); let err_indicator = match err.as_str() { "0" => angle.truecolor(0, 255, 180), _ => angle.truecolor(255, 53, 94), }; - //SSH shell indicator - let ssh_char: ColoredString = match var_os("SSH_TTY") { - Some(_val) => " ".truecolor(0, 150, 180), - None => "".clear(), - }; + // SSH status + let ssh_char = ssh_char(); //Git status let git_branch = get_git_branch(); diff --git a/src/ssh.rs b/src/ssh.rs new file mode 100644 index 0000000..49f86f9 --- /dev/null +++ b/src/ssh.rs @@ -0,0 +1,10 @@ +use colored::{ColoredString, Colorize}; +use std::env::var_os; + +//SSH shell indicator +pub fn ssh_char() -> ColoredString { + match var_os("SSH_TTY") { + Some(_val) => " ".truecolor(0, 150, 180), + None => "".clear(), + } +} diff --git a/src/user.rs b/src/user.rs new file mode 100644 index 0000000..00ed681 --- /dev/null +++ b/src/user.rs @@ -0,0 +1,20 @@ +use colored::{ColoredString, Colorize}; +use std::env::var_os; + +//Root user indicator + +pub fn user() -> String { + var_os("USER") + .expect("UnknownUser") + .to_str() + .expect("UnknownUser") + .to_string() +} + +pub fn root_indicator() -> ColoredString { + let angle = "❯"; + match user().as_str() { + "root" => angle.truecolor(255, 53, 94), + _ => angle.truecolor(0, 255, 180), + } +} From d1fecadb51fc0c21076f6a8a6f9c393ac795f5f0 Mon Sep 17 00:00:00 2001 From: candifloss Date: Thu, 21 Nov 2024 14:11:13 +0530 Subject: [PATCH 02/23] unwanted files --- .idea/.gitignore | 5 ----- .idea/PrettyPrompt.iml | 11 ----------- .idea/modules.xml | 8 -------- .idea/vcs.xml | 6 ------ 4 files changed, 30 deletions(-) delete mode 100644 .idea/.gitignore delete mode 100644 .idea/PrettyPrompt.iml delete mode 100644 .idea/modules.xml delete mode 100644 .idea/vcs.xml diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index b58b603..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ diff --git a/.idea/PrettyPrompt.iml b/.idea/PrettyPrompt.iml deleted file mode 100644 index cf84ae4..0000000 --- a/.idea/PrettyPrompt.iml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 3792141..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1dd..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file From 4f90edceefb4286d0f815500799c22ca8e64e5e3 Mon Sep 17 00:00:00 2001 From: candifloss Date: Thu, 21 Nov 2024 16:28:26 +0530 Subject: [PATCH 03/23] sort out modules --- src/indicators/error.rs | 17 +++++++++++++ src/{ => indicators}/git.rs | 0 src/indicators/shell.rs | 20 +++++++++++++++ src/{ => indicators}/ssh.rs | 0 src/{ => indicators}/user.rs | 0 src/main.rs | 47 ++++++++++-------------------------- 6 files changed, 50 insertions(+), 34 deletions(-) create mode 100644 src/indicators/error.rs rename src/{ => indicators}/git.rs (100%) create mode 100644 src/indicators/shell.rs rename src/{ => indicators}/ssh.rs (100%) rename src/{ => indicators}/user.rs (100%) diff --git a/src/indicators/error.rs b/src/indicators/error.rs new file mode 100644 index 0000000..38681df --- /dev/null +++ b/src/indicators/error.rs @@ -0,0 +1,17 @@ +use colored::{ColoredString, Colorize}; + +pub fn err(args: Vec) -> String { + if args.len() > 2 { + args[2].clone() // Error status + } else { + "none".to_string() + } +} + +pub fn err_indicator(err: String) -> ColoredString { + let angle = "❯"; + match err.as_str() { + "0" => angle.truecolor(0, 255, 180), + _ => angle.truecolor(255, 53, 94), + } +} diff --git a/src/git.rs b/src/indicators/git.rs similarity index 100% rename from src/git.rs rename to src/indicators/git.rs diff --git a/src/indicators/shell.rs b/src/indicators/shell.rs new file mode 100644 index 0000000..513ea28 --- /dev/null +++ b/src/indicators/shell.rs @@ -0,0 +1,20 @@ +pub fn get_shell_char(shell: &str) -> String { + let shell_char = match shell { + "bash" | "/bin/bash" | "/usr/bin/bash" | "-bash" => " ", + "zsh" | "/bin/zsh" | "/usr/bin/zsh" | "-zsh" => "󰰶 ", + "fish" => "󰈺 ", + "nushell" => " ", + "ion" => " ", + "oursh" => "󱢇 ", + _ => "󱆃 ", + }; + shell_char.to_string() +} + +pub fn shell(args: Vec) -> String { + if args.len() > 1 { + args[1].clone() // Shell symbol + } else { + "none".to_string() + } +} diff --git a/src/ssh.rs b/src/indicators/ssh.rs similarity index 100% rename from src/ssh.rs rename to src/indicators/ssh.rs diff --git a/src/user.rs b/src/indicators/user.rs similarity index 100% rename from src/user.rs rename to src/indicators/user.rs diff --git a/src/main.rs b/src/main.rs index b1c24fb..4bb9529 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,24 +1,15 @@ -use colored::{ColoredString, Colorize}; +//use colored::{ColoredString, Colorize}; +use colored::Colorize; use std::env::{args, current_dir, var_os}; -mod git; -mod ssh; -mod user; -use crate::git::*; -use crate::ssh::*; -use crate::user::*; -fn get_shell_char(shell: &str) -> String { - let shell_char = match shell { - "bash" | "/bin/bash" | "/usr/bin/bash" | "-bash" => " ", - "zsh" | "/bin/zsh" | "/usr/bin/zsh" | "-zsh" => "󰰶 ", - "fish" => "󰈺 ", - "nushell" => " ", - "ion" => " ", - "oursh" => "󱢇 ", - _ => "󱆃 ", - }; - shell_char.to_string() +mod indicators { + pub mod error; + pub mod git; + pub mod shell; + pub mod ssh; + pub mod user; } +use crate::indicators::{error::*, git::*, shell::*, ssh::*, user::*}; fn abrev_path(path: &str) -> String { let mut short_dir = path.to_string(); @@ -42,27 +33,15 @@ fn abrev_path(path: &str) -> String { } fn main() -> std::io::Result<()> { - let angle = "❯"; - - let mut err: String = String::new(); + //let angle = "❯"; let args: Vec = args().collect(); - let shell: String; - if args.len() > 1 { - shell = args[1].clone(); // Shell symbol - if args.len() > 2 { - err.clone_from(&args[2]); // Error status - } - } else { - shell = "none".to_string(); - } + let shell: String = shell(args.clone()); let root_indicator = root_indicator(); - let err_indicator = match err.as_str() { - "0" => angle.truecolor(0, 255, 180), - _ => angle.truecolor(255, 53, 94), - }; + let err: String = err(args.clone()); + let err_indicator = err_indicator(err); // SSH status let ssh_char = ssh_char(); From 7ed36ce4711b620ff89148d5ed3621fb2b72e7ae Mon Sep 17 00:00:00 2001 From: candifloss Date: Thu, 21 Nov 2024 20:04:16 +0530 Subject: [PATCH 04/23] modularity --- .idea/workspace.xml | 102 +++++++++++++++++++++++++++++++++++++++++ src/indicators/path.rs | 31 +++++++++++++ src/main.rs | 30 ++---------- 3 files changed, 136 insertions(+), 27 deletions(-) create mode 100644 .idea/workspace.xml create mode 100644 src/indicators/path.rs diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..aaf8a4a --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + { + "associatedIndex": 2 +} + + + + + + + + + + + + + + + + + 1723662281778 + + + + + + \ No newline at end of file diff --git a/src/indicators/path.rs b/src/indicators/path.rs new file mode 100644 index 0000000..ff76519 --- /dev/null +++ b/src/indicators/path.rs @@ -0,0 +1,31 @@ +use std::env::{args, current_dir, var_os}; + +pub fn abrev_path(path: &str) -> String { + let mut short_dir = path.to_string(); + + let slashes = path.matches('/').count(); + + if slashes > 3 { + let parts: Vec<&str> = path.split('/').collect(); + let len = parts.len() - 1; + let mut ch1: String; + + for part in &parts[0..len] { + if part.to_string() != "" { + // to avoid the 1st "/" + ch1 = part.chars().next().expect(part).to_string(); // 1st char of each part + short_dir = short_dir.replace(part, &ch1); + } + } + } + short_dir +} + +//pwd +pub fn homedir() -> String { + var_os("HOME") + .expect("UnknownDir") + .to_str() + .expect("UnknownDir") + .to_string() +} diff --git a/src/main.rs b/src/main.rs index 4bb9529..df3d877 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,32 +5,12 @@ use std::env::{args, current_dir, var_os}; mod indicators { pub mod error; pub mod git; + pub mod path; pub mod shell; pub mod ssh; pub mod user; } -use crate::indicators::{error::*, git::*, shell::*, ssh::*, user::*}; - -fn abrev_path(path: &str) -> String { - let mut short_dir = path.to_string(); - - let slashes = path.matches('/').count(); - - if slashes > 3 { - let parts: Vec<&str> = path.split('/').collect(); - let len = parts.len() - 1; - let mut ch1: String; - - for part in &parts[0..len] { - if part.to_string() != "" { - // to avoid the 1st "/" - ch1 = part.chars().next().expect(part).to_string(); // 1st char of each part - short_dir = short_dir.replace(part, &ch1); - } - } - } - short_dir -} +use crate::indicators::{error::*, git::*, path::*, shell::*, ssh::*, user::*}; fn main() -> std::io::Result<()> { //let angle = "❯"; @@ -53,11 +33,7 @@ fn main() -> std::io::Result<()> { let git_char = get_git_char(&git_branch); //pwd - let homedir = var_os("HOME") - .expect("UnknownDir") - .to_str() - .expect("UnknownDir") - .to_string(); + let homedir = homedir(); let pwd = current_dir()?; let mut cur_dir = pwd.display().to_string(); cur_dir = cur_dir.replace(&git_repo_root, ""); // Remove git repo root From b823586d038b593664c34f9b48e791d423be30be Mon Sep 17 00:00:00 2001 From: candifloss Date: Sat, 23 Nov 2024 16:50:15 +0530 Subject: [PATCH 05/23] changed dependancy to ansi_term --- Cargo.lock | 83 ++++++++---------------------------------- Cargo.toml | 2 +- src/indicators/user.rs | 21 +++++++---- src/main.bkp.rs | 55 ++++++++++++++++++++++++++++ src/main.rs | 55 +++++----------------------- 5 files changed, 94 insertions(+), 122 deletions(-) create mode 100644 src/main.bkp.rs diff --git a/Cargo.lock b/Cargo.lock index 932f2f8..5e5dcd2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,90 +3,39 @@ version = 3 [[package]] -name = "colored" -version = "2.1.0" +name = "ansi_term" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8" +checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" dependencies = [ - "lazy_static", - "windows-sys", + "winapi", ] -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - [[package]] name = "prettyprompt" version = "0.1.0" dependencies = [ - "colored", + "ansi_term", ] [[package]] -name = "windows-sys" -version = "0.48.0" +name = "winapi" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ - "windows-targets", + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", ] [[package]] -name = "windows-targets" -version = "0.48.5" +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/Cargo.toml b/Cargo.toml index 5c2432d..886dff1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,4 +4,4 @@ version = "0.1.0" edition = "2021" [dependencies] -colored = "2.1.0" +ansi_term = "0.12" diff --git a/src/indicators/user.rs b/src/indicators/user.rs index 00ed681..a1193cb 100644 --- a/src/indicators/user.rs +++ b/src/indicators/user.rs @@ -1,9 +1,14 @@ -use colored::{ColoredString, Colorize}; +use ansi_term::ANSIGenericString; +use ansi_term::Colour::RGB; use std::env::var_os; -//Root user indicator +// User indicator symbol +pub const USER_SYMBOL: &str = "\u{276F}"; // "❯" +pub const ROOT_COL: ansi_term::Colour = RGB(255, 53, 94); // Riot red or something +pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // A kind of green -pub fn user() -> String { +//Root user indicator +pub fn username() -> String { var_os("USER") .expect("UnknownUser") .to_str() @@ -11,10 +16,10 @@ pub fn user() -> String { .to_string() } -pub fn root_indicator() -> ColoredString { - let angle = "❯"; - match user().as_str() { - "root" => angle.truecolor(255, 53, 94), - _ => angle.truecolor(0, 255, 180), +pub fn indicator() -> ANSIGenericString<'static, str> { + if username() == "root" { + ROOT_COL.paint(USER_SYMBOL) + } else { + NORMIE_COL.paint(USER_SYMBOL) } } diff --git a/src/main.bkp.rs b/src/main.bkp.rs new file mode 100644 index 0000000..df3d877 --- /dev/null +++ b/src/main.bkp.rs @@ -0,0 +1,55 @@ +//use colored::{ColoredString, Colorize}; +use colored::Colorize; +use std::env::{args, current_dir, var_os}; + +mod indicators { + pub mod error; + pub mod git; + pub mod path; + pub mod shell; + pub mod ssh; + pub mod user; +} +use crate::indicators::{error::*, git::*, path::*, shell::*, ssh::*, user::*}; + +fn main() -> std::io::Result<()> { + //let angle = "❯"; + + let args: Vec = args().collect(); + let shell: String = shell(args.clone()); + + let root_indicator = root_indicator(); + + let err: String = err(args.clone()); + let err_indicator = err_indicator(err); + + // SSH status + let ssh_char = ssh_char(); + + //Git status + let git_branch = get_git_branch(); + let git_repo_root = get_git_root(); + let git_repo_name = get_git_repo_name(&git_repo_root.clone()).truecolor(122, 68, 24); + let git_char = get_git_char(&git_branch); + + //pwd + let homedir = homedir(); + let pwd = current_dir()?; + let mut cur_dir = pwd.display().to_string(); + cur_dir = cur_dir.replace(&git_repo_root, ""); // Remove git repo root + cur_dir = cur_dir.replace(&homedir, "~"); // Abreviate homedir with "~" + cur_dir = abrev_path(&cur_dir); + + print!( + "{}{}{}{}{}{}{} ", + ssh_char, + get_shell_char(&shell).truecolor(75, 75, 75), + git_repo_name, + git_char, + cur_dir.italic().truecolor(82, 82, 82), + root_indicator, + err_indicator, + ); + + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index df3d877..c425200 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,55 +1,18 @@ -//use colored::{ColoredString, Colorize}; -use colored::Colorize; -use std::env::{args, current_dir, var_os}; - mod indicators { - pub mod error; - pub mod git; - pub mod path; - pub mod shell; - pub mod ssh; pub mod user; } -use crate::indicators::{error::*, git::*, path::*, shell::*, ssh::*, user::*}; +use crate::indicators::user; fn main() -> std::io::Result<()> { - //let angle = "❯"; + //let mut prompt: ANSIGenericString<'static, str> = "".into(); + let mut prompt: String = String::new(); + + let indicate_user:bool = true; - let args: Vec = args().collect(); - let shell: String = shell(args.clone()); - - let root_indicator = root_indicator(); - - let err: String = err(args.clone()); - let err_indicator = err_indicator(err); - - // SSH status - let ssh_char = ssh_char(); - - //Git status - let git_branch = get_git_branch(); - let git_repo_root = get_git_root(); - let git_repo_name = get_git_repo_name(&git_repo_root.clone()).truecolor(122, 68, 24); - let git_char = get_git_char(&git_branch); - - //pwd - let homedir = homedir(); - let pwd = current_dir()?; - let mut cur_dir = pwd.display().to_string(); - cur_dir = cur_dir.replace(&git_repo_root, ""); // Remove git repo root - cur_dir = cur_dir.replace(&homedir, "~"); // Abreviate homedir with "~" - cur_dir = abrev_path(&cur_dir); - - print!( - "{}{}{}{}{}{}{} ", - ssh_char, - get_shell_char(&shell).truecolor(75, 75, 75), - git_repo_name, - git_char, - cur_dir.italic().truecolor(82, 82, 82), - root_indicator, - err_indicator, - ); + if indicate_user { + prompt += &user::indicator().to_string(); + } + print!("{}", prompt); Ok(()) } From 24f3f6772ea8ea14adfa2c4e37ccf975d7c24dc3 Mon Sep 17 00:00:00 2001 From: candifloss Date: Sun, 24 Nov 2024 19:53:15 +0530 Subject: [PATCH 06/23] migrated user, git, & ssh indicators to ansi_term --- src/indicators/git.rs | 86 ++++++++++++++------------------ src/indicators/ssh.rs | 23 ++++++--- src/main.rs | 28 ++++++++--- src/{indicators => old}/error.rs | 0 src/{ => old}/main.bkp.rs | 0 src/{indicators => old}/path.rs | 0 src/{indicators => old}/shell.rs | 0 7 files changed, 76 insertions(+), 61 deletions(-) rename src/{indicators => old}/error.rs (100%) rename src/{ => old}/main.bkp.rs (100%) rename src/{indicators => old}/path.rs (100%) rename src/{indicators => old}/shell.rs (100%) diff --git a/src/indicators/git.rs b/src/indicators/git.rs index 24b006a..f14fd85 100644 --- a/src/indicators/git.rs +++ b/src/indicators/git.rs @@ -1,55 +1,45 @@ -use colored::{ColoredString, Colorize}; +use ansi_term::ANSIGenericString; +use ansi_term::Colour::RGB; use std::process::Command; -pub fn get_git_branch() -> String { - let git_status_cmd = Command::new("git") - .arg("status") - .output() - .expect("git_status_cmd_fail"); - let git_status_output = String::from_utf8_lossy(&git_status_cmd.stdout); - let git_err = String::from_utf8_lossy(&git_status_cmd.stderr); +// SSH indicator symbol +pub const GIT_SYMBOL: &str = "\u{276F}"; // "❯" +pub const MAIN_COL: ansi_term::Colour = RGB(178, 98, 44); // +pub const DEV_COL: ansi_term::Colour = RGB(54, 159, 150); // +pub const OTHER_COL: ansi_term::Colour = RGB(82, 82, 82); // +pub const NORMIE_COL: ansi_term::Colour = RGB(255, 255, 255); // White - if git_err == "" { - git_status_output.split('\n').collect::>()[0] - .split(' ') - .collect::>()[2] - .to_string() - } else { - String::new() - } -} - -pub fn get_git_root() -> String { - let git_repo_root_cmd = Command::new("git") +pub fn info() -> Option<(String, String)> { + let output = Command::new("git") .arg("rev-parse") - .arg("--show-toplevel") - .output() - .expect("git_repo_root_cmd_fail"); - let mut git_repo_path = String::from_utf8_lossy(&git_repo_root_cmd.stdout).to_string(); - let git_repo_err = String::from_utf8_lossy(&git_repo_root_cmd.stderr); + .arg("--show-toplevel") // Repo root + .arg("--abbrev-ref") // Git branch + .arg("HEAD") + .output(); + match output { + Ok(output) if output.status.success() => { + let stdout = String::from_utf8_lossy(&output.stdout); // Get cmd output + let output_string = stdout.trim(); + let parts: Vec<&str> = output_string.split('\n').collect(); - if git_repo_err == "" { - let len = git_repo_path.trim_end_matches(&['\r', '\n'][..]).len(); - git_repo_path.truncate(len); - } else { - git_repo_path = String::new(); - } - git_repo_path -} - -pub fn get_git_repo_name(git_repo_root: &str) -> String { - let repo_path_split: Vec<&str> = git_repo_root.split('/').collect(); - let last_index = repo_path_split.len() - 1; - let git_repo_name = repo_path_split[last_index]; - - git_repo_name.to_string() -} - -pub fn get_git_char(git_branch: &str) -> ColoredString { - match git_branch { - "" => "".clear(), - "main" => " 󰊢 ".truecolor(178, 98, 44), - "master" => " 󰊢 ".truecolor(196, 132, 29), - _ => " 󰊢 ".truecolor(82, 82, 82), + if parts.len() == 2 { + Some((parts[0].to_string(), parts[1].to_string())) + } else { + None + } + } + _ => None, + } +} + +//Git branch indicator +pub fn indicator(branch: Option) -> ANSIGenericString<'static, str> { + match branch { + Some(b) => match b.as_str() { + "main" => MAIN_COL.paint(GIT_SYMBOL), + "dev" => DEV_COL.paint(GIT_SYMBOL), + _ => OTHER_COL.paint(GIT_SYMBOL), + }, + None => NORMIE_COL.paint(GIT_SYMBOL), } } diff --git a/src/indicators/ssh.rs b/src/indicators/ssh.rs index 49f86f9..ef4aae7 100644 --- a/src/indicators/ssh.rs +++ b/src/indicators/ssh.rs @@ -1,10 +1,21 @@ -use colored::{ColoredString, Colorize}; -use std::env::var_os; +use ansi_term::ANSIGenericString; +use ansi_term::Colour::RGB; +use std::env::var; + +// SSH indicator symbol +pub const SSH_SYMBOL: &str = "\u{276F}"; // "❯" +pub const SSH_COL: ansi_term::Colour = RGB(255, 149, 0); // A ind of orange +pub const NORMIE_COL: ansi_term::Colour = RGB(255, 255, 255); // White + +fn is_ssh_session() -> bool { + var("SSH_TTY").is_ok() || var("SSH_CONNECTION").is_ok() +} //SSH shell indicator -pub fn ssh_char() -> ColoredString { - match var_os("SSH_TTY") { - Some(_val) => " ".truecolor(0, 150, 180), - None => "".clear(), +pub fn indicator() -> ANSIGenericString<'static, str> { + if is_ssh_session() { + SSH_COL.paint(SSH_SYMBOL) + } else { + NORMIE_COL.paint(SSH_SYMBOL) } } diff --git a/src/main.rs b/src/main.rs index c425200..c4d3caf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,18 +1,32 @@ mod indicators { + pub mod git; + pub mod ssh; pub mod user; } +use indicators::git; + +use crate::indicators::ssh; use crate::indicators::user; -fn main() -> std::io::Result<()> { - //let mut prompt: ANSIGenericString<'static, str> = "".into(); +fn main() { let mut prompt: String = String::new(); - - let indicate_user:bool = true; + let indicate_user: bool = true; + let indicate_ssh: bool = true; + let indicate_git_branch: bool = true; + + if indicate_git_branch { + let git_info = git::info(); + match git_info { + Some((_repo, branch)) => prompt += &git::indicator(Some(branch)).to_string(), + None => prompt += &git::indicator(None).to_string(), + }; + } + if indicate_ssh { + prompt += &ssh::indicator().to_string(); + } if indicate_user { prompt += &user::indicator().to_string(); } - print!("{}", prompt); - - Ok(()) + print!("{prompt} "); } diff --git a/src/indicators/error.rs b/src/old/error.rs similarity index 100% rename from src/indicators/error.rs rename to src/old/error.rs diff --git a/src/main.bkp.rs b/src/old/main.bkp.rs similarity index 100% rename from src/main.bkp.rs rename to src/old/main.bkp.rs diff --git a/src/indicators/path.rs b/src/old/path.rs similarity index 100% rename from src/indicators/path.rs rename to src/old/path.rs diff --git a/src/indicators/shell.rs b/src/old/shell.rs similarity index 100% rename from src/indicators/shell.rs rename to src/old/shell.rs From 7257faf85d0eee94560fcf9e4eb08494fad85a2f Mon Sep 17 00:00:00 2001 From: candifloss Date: Mon, 25 Nov 2024 13:23:37 +0530 Subject: [PATCH 07/23] error indicator --- src/indicators/error.rs | 17 +++++++++++++++++ src/main.rs | 16 +++++++++++----- 2 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 src/indicators/error.rs diff --git a/src/indicators/error.rs b/src/indicators/error.rs new file mode 100644 index 0000000..56a5a7c --- /dev/null +++ b/src/indicators/error.rs @@ -0,0 +1,17 @@ +use ansi_term::ANSIGenericString; +use ansi_term::Colour::RGB; + +// Error indicator symbol +pub const ERR_SYMBOL: &str = "\u{276F}"; // "❯" +pub const ERR_COL: ansi_term::Colour = RGB(255, 53, 94); // +pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // + +// Error indicator +pub fn indicator(args: Vec) -> ANSIGenericString<'static, str> { + let default_exit_code = "0".to_string(); + let exit_code = args.get(1).unwrap_or(&default_exit_code); // Default to "0" if missing + match exit_code.as_str() { + "0" => NORMIE_COL.paint(ERR_SYMBOL), + _ => ERR_COL.paint(ERR_SYMBOL), + } +} diff --git a/src/main.rs b/src/main.rs index c4d3caf..4039fd9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,20 +1,26 @@ mod indicators { + pub mod error; pub mod git; pub mod ssh; pub mod user; } -use indicators::git; - +use crate::indicators::error; +use crate::indicators::git; use crate::indicators::ssh; use crate::indicators::user; fn main() { + let cmd_args: Vec = std::env::args().collect(); let mut prompt: String = String::new(); let indicate_user: bool = true; let indicate_ssh: bool = true; + let indicate_err: bool = true; let indicate_git_branch: bool = true; + if indicate_ssh { + prompt += &ssh::indicator().to_string(); + } if indicate_git_branch { let git_info = git::info(); match git_info { @@ -22,11 +28,11 @@ fn main() { None => prompt += &git::indicator(None).to_string(), }; } - if indicate_ssh { - prompt += &ssh::indicator().to_string(); - } if indicate_user { prompt += &user::indicator().to_string(); } + if indicate_err { + prompt += &error::indicator(cmd_args).to_string(); + } print!("{prompt} "); } From 5a1fca980de65591baab6b106d3d65d84fed96b7 Mon Sep 17 00:00:00 2001 From: Candifloss Date: Mon, 25 Nov 2024 07:55:17 +0000 Subject: [PATCH 08/23] Delete src/old/error.rs --- src/old/error.rs | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 src/old/error.rs diff --git a/src/old/error.rs b/src/old/error.rs deleted file mode 100644 index 38681df..0000000 --- a/src/old/error.rs +++ /dev/null @@ -1,17 +0,0 @@ -use colored::{ColoredString, Colorize}; - -pub fn err(args: Vec) -> String { - if args.len() > 2 { - args[2].clone() // Error status - } else { - "none".to_string() - } -} - -pub fn err_indicator(err: String) -> ColoredString { - let angle = "❯"; - match err.as_str() { - "0" => angle.truecolor(0, 255, 180), - _ => angle.truecolor(255, 53, 94), - } -} From a9a7dc13b859a38f53a99b83a8989e02e179b276 Mon Sep 17 00:00:00 2001 From: candifloss Date: Tue, 26 Nov 2024 12:34:31 +0530 Subject: [PATCH 09/23] path --- src/indicators/path.rs | 13 +++++++++++++ src/main.rs | 7 +++++++ 2 files changed, 20 insertions(+) create mode 100644 src/indicators/path.rs diff --git a/src/indicators/path.rs b/src/indicators/path.rs new file mode 100644 index 0000000..504b503 --- /dev/null +++ b/src/indicators/path.rs @@ -0,0 +1,13 @@ +use ansi_term::ANSIGenericString; +use ansi_term::Colour::RGB; +use std::env::current_dir; + +pub const PATH_COL: ansi_term::Colour = RGB(82, 82, 82); // + +pub fn pwd() -> ANSIGenericString<'static, str> { + let path = current_dir().map_or_else( + |_| "~~".to_string(), + |path| path.to_string_lossy().to_string(), + ); + PATH_COL.italic().paint(path) +} diff --git a/src/main.rs b/src/main.rs index 4039fd9..9d4094b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,14 @@ mod indicators { pub mod error; pub mod git; + pub mod path; pub mod ssh; pub mod user; } + use crate::indicators::error; use crate::indicators::git; +use crate::indicators::path; use crate::indicators::ssh; use crate::indicators::user; @@ -17,7 +20,11 @@ fn main() { let indicate_ssh: bool = true; let indicate_err: bool = true; let indicate_git_branch: bool = true; + let pwd: bool = true; + if pwd { + prompt += &path::pwd().to_string(); + } if indicate_ssh { prompt += &ssh::indicator().to_string(); } From 18168cf0e11cfdd213c4ad949af0420ff551ae03 Mon Sep 17 00:00:00 2001 From: candifloss Date: Tue, 26 Nov 2024 13:43:39 +0530 Subject: [PATCH 10/23] shorten pwd --- .idea/workspace.xml | 102 ----------------------------------------- src/indicators/path.rs | 13 ------ src/indicators/pwd.rs | 33 +++++++++++++ src/indicators/user.rs | 9 ++-- src/main.rs | 7 +-- 5 files changed, 40 insertions(+), 124 deletions(-) delete mode 100644 .idea/workspace.xml delete mode 100644 src/indicators/path.rs create mode 100644 src/indicators/pwd.rs diff --git a/.idea/workspace.xml b/.idea/workspace.xml deleted file mode 100644 index aaf8a4a..0000000 --- a/.idea/workspace.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - - - - - - - - - - - - - - { - "associatedIndex": 2 -} - - - - - - - - - - - - - - - - - 1723662281778 - - - - - - \ No newline at end of file diff --git a/src/indicators/path.rs b/src/indicators/path.rs deleted file mode 100644 index 504b503..0000000 --- a/src/indicators/path.rs +++ /dev/null @@ -1,13 +0,0 @@ -use ansi_term::ANSIGenericString; -use ansi_term::Colour::RGB; -use std::env::current_dir; - -pub const PATH_COL: ansi_term::Colour = RGB(82, 82, 82); // - -pub fn pwd() -> ANSIGenericString<'static, str> { - let path = current_dir().map_or_else( - |_| "~~".to_string(), - |path| path.to_string_lossy().to_string(), - ); - PATH_COL.italic().paint(path) -} diff --git a/src/indicators/pwd.rs b/src/indicators/pwd.rs new file mode 100644 index 0000000..149f460 --- /dev/null +++ b/src/indicators/pwd.rs @@ -0,0 +1,33 @@ +use ansi_term::ANSIGenericString; +use ansi_term::Colour::RGB; +use std::env::current_dir; + +pub const UNKNOWN_PATH: &str = "\u{2248}"; // "≈" +pub const PATH_COL: ansi_term::Colour = RGB(82, 82, 82); + +fn home_dir() -> String { + std::env::var("HOME").map_or_else( + |_| "".to_string(), + |path| path.to_string(), + ) +} + +fn full_path() -> String { + current_dir().map_or_else( + |_| UNKNOWN_PATH.to_string(), + |path| path.to_string_lossy().to_string(), + ) +} + +fn replace_home(path: String) -> String { + let homedir = home_dir(); + path.replace(&homedir, "~") +} + +pub fn pwd(abbrev_home:bool) -> ANSIGenericString<'static, str> { + let mut path = full_path(); + if abbrev_home { + path = replace_home(path); + } + PATH_COL.italic().paint(path) +} \ No newline at end of file diff --git a/src/indicators/user.rs b/src/indicators/user.rs index a1193cb..8285977 100644 --- a/src/indicators/user.rs +++ b/src/indicators/user.rs @@ -1,6 +1,6 @@ use ansi_term::ANSIGenericString; use ansi_term::Colour::RGB; -use std::env::var_os; +use std::env::var; // User indicator symbol pub const USER_SYMBOL: &str = "\u{276F}"; // "❯" @@ -9,11 +9,8 @@ pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // A kind of green //Root user indicator pub fn username() -> String { - var_os("USER") - .expect("UnknownUser") - .to_str() - .expect("UnknownUser") - .to_string() + var("USER") + .unwrap_or_else(|_| "UnknownUser".to_string()) } pub fn indicator() -> ANSIGenericString<'static, str> { diff --git a/src/main.rs b/src/main.rs index 9d4094b..a5ddcb7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,14 @@ mod indicators { pub mod error; pub mod git; - pub mod path; + pub mod pwd; pub mod ssh; pub mod user; } use crate::indicators::error; use crate::indicators::git; -use crate::indicators::path; +use crate::indicators::pwd; use crate::indicators::ssh; use crate::indicators::user; @@ -21,9 +21,10 @@ fn main() { let indicate_err: bool = true; let indicate_git_branch: bool = true; let pwd: bool = true; + let abbrev_home:bool = true; if pwd { - prompt += &path::pwd().to_string(); + prompt += &pwd::pwd(abbrev_home).to_string(); } if indicate_ssh { prompt += &ssh::indicator().to_string(); From a0c6f3a71ea0c754f450e44e5132003f4b1c564f Mon Sep 17 00:00:00 2001 From: candifloss Date: Wed, 27 Nov 2024 16:41:55 +0530 Subject: [PATCH 11/23] migrated pwd to ansi_term and more modularity --- src/indicators/git.rs | 9 +++++ src/indicators/pwd.rs | 89 +++++++++++++++++++++++++++++++++++------- src/indicators/user.rs | 3 +- src/main.rs | 38 ++++++++++++------ src/old/path.rs | 31 --------------- 5 files changed, 110 insertions(+), 60 deletions(-) delete mode 100644 src/old/path.rs diff --git a/src/indicators/git.rs b/src/indicators/git.rs index f14fd85..bef62fd 100644 --- a/src/indicators/git.rs +++ b/src/indicators/git.rs @@ -1,5 +1,6 @@ use ansi_term::ANSIGenericString; use ansi_term::Colour::RGB; +use std::path::Path; use std::process::Command; // SSH indicator symbol @@ -32,6 +33,14 @@ pub fn info() -> Option<(String, String)> { } } +pub fn repo_name(path: &str) -> String { + Path::new(path) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("") // Default value if None + .to_string() // Convert &str to String +} + //Git branch indicator pub fn indicator(branch: Option) -> ANSIGenericString<'static, str> { match branch { diff --git a/src/indicators/pwd.rs b/src/indicators/pwd.rs index 149f460..d71e76c 100644 --- a/src/indicators/pwd.rs +++ b/src/indicators/pwd.rs @@ -1,33 +1,94 @@ +use crate::indicators::git::{repo_name, MAIN_COL}; use ansi_term::ANSIGenericString; use ansi_term::Colour::RGB; use std::env::current_dir; pub const UNKNOWN_PATH: &str = "\u{2248}"; // "≈" pub const PATH_COL: ansi_term::Colour = RGB(82, 82, 82); +pub const REPO_COL: ansi_term::Colour = RGB(55, 120, 130); fn home_dir() -> String { - std::env::var("HOME").map_or_else( - |_| "".to_string(), - |path| path.to_string(), - ) + std::env::var("HOME").map_or_else(|_| "".to_string(), |path| path.to_string()) } fn full_path() -> String { - current_dir().map_or_else( + current_dir().map_or_else( |_| UNKNOWN_PATH.to_string(), |path| path.to_string_lossy().to_string(), ) } -fn replace_home(path: String) -> String { - let homedir = home_dir(); - path.replace(&homedir, "~") +fn remove_repo(pwd_path: &str, repo_path: &str) -> String { + pwd_path.replacen(repo_path, "", 1) } -pub fn pwd(abbrev_home:bool) -> ANSIGenericString<'static, str> { - let mut path = full_path(); - if abbrev_home { - path = replace_home(path); +fn replace_home(path: &str) -> String { + let homedir = home_dir(); + path.replacen(&homedir, "~", 1) +} + +fn short(path: &str, slash_limit: u8) -> String { + let slashes = path.matches('/').count(); + if slashes <= slash_limit.into() { + path.to_string() // Short path, return without changes + } else { + // Long path, shorten it + let parts: Vec<&str> = path.split('/').collect(); // Split the path into parts + let first = if path.starts_with("~") { "~" } else { "" }; // Determine the first part correctly + let last = parts[parts.len() - 1]; // The last part + + // Abbreviate middle parts (take the first character of each) + let abbreviated_middle: Vec = parts[1..parts.len() - 1] // Skip the first and last part + .iter() + .filter(|&&part| !part.is_empty()) // Avoid empty parts (like after "/") + .map(|&part| part.chars().next().unwrap().to_string()) // Take the first letter + .collect(); + + // Join the parts back together with "/" and return the shortened path + let mut shortened_path = vec![first.to_string()]; + shortened_path.extend(abbreviated_middle); + shortened_path.push(last.to_string()); + + shortened_path.join("/") } - PATH_COL.italic().paint(path) -} \ No newline at end of file +} + +pub fn pwd( + abbrev_home: bool, + shorten_path: bool, + replace_repo: bool, + git_repo: Option, +) -> ANSIGenericString<'static, str> { + let mut path = full_path(); + let slash_limit: u8 = if replace_repo { 2 } else { 3 }; + + if replace_repo && git_repo.is_some() { + if let Some(repo_path) = git_repo { + path = remove_repo(&path, &repo_path); + let repo_name = repo_name(&repo_path); + if shorten_path { + path = short(&path, slash_limit); + } + match path.as_str() { + "" => REPO_COL.paint(repo_name), + _ => format!( + "{}{}{}", + REPO_COL.paint(repo_name), + MAIN_COL.paint(" \u{F02A2} "), + PATH_COL.italic().paint(path) + ) + .into(), + } + } else { + PATH_COL.italic().paint(path) + } + } else if abbrev_home { + path = replace_home(&path); + if shorten_path { + path = short(&path, slash_limit); + } + PATH_COL.italic().paint(path) + } else { + PATH_COL.italic().paint(path) + } +} diff --git a/src/indicators/user.rs b/src/indicators/user.rs index 8285977..45d380a 100644 --- a/src/indicators/user.rs +++ b/src/indicators/user.rs @@ -9,8 +9,7 @@ pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // A kind of green //Root user indicator pub fn username() -> String { - var("USER") - .unwrap_or_else(|_| "UnknownUser".to_string()) + var("USER").unwrap_or_else(|_| "UnknownUser".to_string()) } pub fn indicator() -> ANSIGenericString<'static, str> { diff --git a/src/main.rs b/src/main.rs index a5ddcb7..2a8630d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,33 +14,45 @@ use crate::indicators::user; fn main() { let cmd_args: Vec = std::env::args().collect(); - let mut prompt: String = String::new(); + + let mut components: Vec = Vec::new(); let indicate_user: bool = true; let indicate_ssh: bool = true; let indicate_err: bool = true; let indicate_git_branch: bool = true; - let pwd: bool = true; - let abbrev_home:bool = true; + let show_pwd: bool = true; + let abbrev_home: bool = true; + let shorten_path: bool = true; + let replace_repo: bool = true; + let mut git_info = None; - if pwd { - prompt += &pwd::pwd(abbrev_home).to_string(); - } if indicate_ssh { - prompt += &ssh::indicator().to_string(); + components.push(ssh::indicator().to_string()); } if indicate_git_branch { - let git_info = git::info(); + git_info = git::info(); match git_info { - Some((_repo, branch)) => prompt += &git::indicator(Some(branch)).to_string(), - None => prompt += &git::indicator(None).to_string(), - }; + Some(ref info) => components.push(git::indicator(Some(info.1.clone())).to_string()), + None => components.push(git::indicator(None).to_string()), + } } if indicate_user { - prompt += &user::indicator().to_string(); + components.push(user::indicator().to_string()); } if indicate_err { - prompt += &error::indicator(cmd_args).to_string(); + components.push(error::indicator(cmd_args).to_string()); } + if show_pwd { + let repo_path = match git_info { + Some(info) => Some(info.0), // Clone to avoid ownership issues + None => None, + }; + components.insert( + 0, + pwd::pwd(abbrev_home, shorten_path, replace_repo, repo_path).to_string(), + ); + } + let prompt = components.join(""); print!("{prompt} "); } diff --git a/src/old/path.rs b/src/old/path.rs deleted file mode 100644 index ff76519..0000000 --- a/src/old/path.rs +++ /dev/null @@ -1,31 +0,0 @@ -use std::env::{args, current_dir, var_os}; - -pub fn abrev_path(path: &str) -> String { - let mut short_dir = path.to_string(); - - let slashes = path.matches('/').count(); - - if slashes > 3 { - let parts: Vec<&str> = path.split('/').collect(); - let len = parts.len() - 1; - let mut ch1: String; - - for part in &parts[0..len] { - if part.to_string() != "" { - // to avoid the 1st "/" - ch1 = part.chars().next().expect(part).to_string(); // 1st char of each part - short_dir = short_dir.replace(part, &ch1); - } - } - } - short_dir -} - -//pwd -pub fn homedir() -> String { - var_os("HOME") - .expect("UnknownDir") - .to_str() - .expect("UnknownDir") - .to_string() -} From e836ad40ac560bb9b7e1f286995d8bcd2658be7d Mon Sep 17 00:00:00 2001 From: candifloss Date: Thu, 28 Nov 2024 16:21:38 +0530 Subject: [PATCH 12/23] changed type of strings --- src/main.rs | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2a8630d..61cffe5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,11 +11,12 @@ use crate::indicators::git; use crate::indicators::pwd; use crate::indicators::ssh; use crate::indicators::user; +use ansi_term::{ANSIGenericString, ANSIGenericStrings}; fn main() { - let cmd_args: Vec = std::env::args().collect(); + let cmd_args: Vec = std::env::args().collect(); // Cmd-line args - let mut components: Vec = Vec::new(); + let mut components: Vec> = Vec::new(); // The components will be concated into one string let indicate_user: bool = true; let indicate_ssh: bool = true; @@ -25,23 +26,27 @@ fn main() { let abbrev_home: bool = true; let shorten_path: bool = true; let replace_repo: bool = true; - let mut git_info = None; + + let git_info: Option<(String, String)> = if indicate_git_branch || replace_repo { + git::info() + } else { + None + }; if indicate_ssh { - components.push(ssh::indicator().to_string()); + components.push(ssh::indicator()); } if indicate_git_branch { - git_info = git::info(); match git_info { - Some(ref info) => components.push(git::indicator(Some(info.1.clone())).to_string()), - None => components.push(git::indicator(None).to_string()), + Some(ref info) => components.push(git::indicator(Some(info.1.clone()))), + None => components.push(git::indicator(None)), } } if indicate_user { - components.push(user::indicator().to_string()); + components.push(user::indicator()); } if indicate_err { - components.push(error::indicator(cmd_args).to_string()); + components.push(error::indicator(cmd_args)); } if show_pwd { let repo_path = match git_info { @@ -50,9 +55,9 @@ fn main() { }; components.insert( 0, - pwd::pwd(abbrev_home, shorten_path, replace_repo, repo_path).to_string(), + pwd::pwd(abbrev_home, shorten_path, replace_repo, repo_path), ); } - let prompt = components.join(""); + let prompt: ANSIGenericStrings<'_, str> = ANSIGenericStrings(&components[..]); print!("{prompt} "); } From 0510f9c34da39947434efa392b74a46d563dd794 Mon Sep 17 00:00:00 2001 From: candifloss Date: Thu, 28 Nov 2024 16:43:58 +0530 Subject: [PATCH 13/23] wrong comment --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 61cffe5..5bee6b5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,7 +50,7 @@ fn main() { } if show_pwd { let repo_path = match git_info { - Some(info) => Some(info.0), // Clone to avoid ownership issues + Some(info) => Some(info.0), None => None, }; components.insert( From e8216e7c0806fe5df69dc65f17fd65a128ce8161 Mon Sep 17 00:00:00 2001 From: candifloss Date: Fri, 29 Nov 2024 12:10:02 +0530 Subject: [PATCH 14/23] Iimproved efficiency and best practices --- src/indicators/error.rs | 19 +++++++------- src/indicators/git.rs | 25 +++++++------------ src/indicators/pwd.rs | 10 +++++--- src/main.rs | 3 ++- src/old/main.bkp.rs | 55 ----------------------------------------- src/old/shell.rs | 20 --------------- 6 files changed, 27 insertions(+), 105 deletions(-) delete mode 100644 src/old/main.bkp.rs delete mode 100644 src/old/shell.rs diff --git a/src/indicators/error.rs b/src/indicators/error.rs index 56a5a7c..5ce1992 100644 --- a/src/indicators/error.rs +++ b/src/indicators/error.rs @@ -1,17 +1,16 @@ use ansi_term::ANSIGenericString; use ansi_term::Colour::RGB; -// Error indicator symbol -pub const ERR_SYMBOL: &str = "\u{276F}"; // "❯" -pub const ERR_COL: ansi_term::Colour = RGB(255, 53, 94); // -pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // +pub const ERR_SYMBOL: &str = "\u{276F}"; // Error indicator symbol: "❯" +pub const ERR_COL: ansi_term::Colour = RGB(255, 53, 94); // Error +pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // Success // Error indicator -pub fn indicator(args: Vec) -> ANSIGenericString<'static, str> { - let default_exit_code = "0".to_string(); - let exit_code = args.get(1).unwrap_or(&default_exit_code); // Default to "0" if missing - match exit_code.as_str() { - "0" => NORMIE_COL.paint(ERR_SYMBOL), - _ => ERR_COL.paint(ERR_SYMBOL), +pub fn indicator(args: &[String]) -> ANSIGenericString<'static, str> { + let exit_code = args.get(1).map_or("0", String::as_str); // Default to "0" (success, no error) if arg missing + if exit_code == "0" { + NORMIE_COL.paint(ERR_SYMBOL) // Success + } else { + ERR_COL.paint(ERR_SYMBOL) // Error } } diff --git a/src/indicators/git.rs b/src/indicators/git.rs index bef62fd..2425808 100644 --- a/src/indicators/git.rs +++ b/src/indicators/git.rs @@ -12,25 +12,18 @@ pub const NORMIE_COL: ansi_term::Colour = RGB(255, 255, 255); // White pub fn info() -> Option<(String, String)> { let output = Command::new("git") - .arg("rev-parse") - .arg("--show-toplevel") // Repo root - .arg("--abbrev-ref") // Git branch - .arg("HEAD") - .output(); - match output { - Ok(output) if output.status.success() => { - let stdout = String::from_utf8_lossy(&output.stdout); // Get cmd output - let output_string = stdout.trim(); - let parts: Vec<&str> = output_string.split('\n').collect(); + .args(["rev-parse", "--show-toplevel", "--abbrev-ref", "HEAD"]) + .output() + .ok()?; - if parts.len() == 2 { - Some((parts[0].to_string(), parts[1].to_string())) - } else { - None - } + if output.status.success() { + let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string(); + let parts: Vec<&str> = output_str.split('\n').collect(); + if parts.len() == 2 { + return Some((parts[0].to_string(), parts[1].to_string())); } - _ => None, } + None } pub fn repo_name(path: &str) -> String { diff --git a/src/indicators/pwd.rs b/src/indicators/pwd.rs index d71e76c..11a5c45 100644 --- a/src/indicators/pwd.rs +++ b/src/indicators/pwd.rs @@ -7,10 +7,12 @@ pub const UNKNOWN_PATH: &str = "\u{2248}"; // "≈" pub const PATH_COL: ansi_term::Colour = RGB(82, 82, 82); pub const REPO_COL: ansi_term::Colour = RGB(55, 120, 130); +/// Find the current user's home directory. fn home_dir() -> String { - std::env::var("HOME").map_or_else(|_| "".to_string(), |path| path.to_string()) + std::env::var("HOME").map_or_else(|_| String::new(), |path| path.to_string()) } +/// Returns the full path of the current directory as a string. fn full_path() -> String { current_dir().map_or_else( |_| UNKNOWN_PATH.to_string(), @@ -18,10 +20,12 @@ fn full_path() -> String { ) } +/// Remove the path of the repo's root from the path, to replace it with the repo's name. fn remove_repo(pwd_path: &str, repo_path: &str) -> String { pwd_path.replacen(repo_path, "", 1) } +/// Replace the 'home directory' part of the path with a the '~' symbol fn replace_home(path: &str) -> String { let homedir = home_dir(); path.replacen(&homedir, "~", 1) @@ -34,13 +38,13 @@ fn short(path: &str, slash_limit: u8) -> String { } else { // Long path, shorten it let parts: Vec<&str> = path.split('/').collect(); // Split the path into parts - let first = if path.starts_with("~") { "~" } else { "" }; // Determine the first part correctly + let first = if path.starts_with('~') { "~" } else { "" }; // Determine the first part correctly let last = parts[parts.len() - 1]; // The last part // Abbreviate middle parts (take the first character of each) let abbreviated_middle: Vec = parts[1..parts.len() - 1] // Skip the first and last part .iter() - .filter(|&&part| !part.is_empty()) // Avoid empty parts (like after "/") + .filter(|&&part| !part.is_empty()) // Avoid empty parts (like "//") .map(|&part| part.chars().next().unwrap().to_string()) // Take the first letter .collect(); diff --git a/src/main.rs b/src/main.rs index 5bee6b5..041833c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,7 +46,8 @@ fn main() { components.push(user::indicator()); } if indicate_err { - components.push(error::indicator(cmd_args)); + //components.push(error::indicator(cmd_args)); + components.push(error::indicator(&cmd_args)); } if show_pwd { let repo_path = match git_info { diff --git a/src/old/main.bkp.rs b/src/old/main.bkp.rs deleted file mode 100644 index df3d877..0000000 --- a/src/old/main.bkp.rs +++ /dev/null @@ -1,55 +0,0 @@ -//use colored::{ColoredString, Colorize}; -use colored::Colorize; -use std::env::{args, current_dir, var_os}; - -mod indicators { - pub mod error; - pub mod git; - pub mod path; - pub mod shell; - pub mod ssh; - pub mod user; -} -use crate::indicators::{error::*, git::*, path::*, shell::*, ssh::*, user::*}; - -fn main() -> std::io::Result<()> { - //let angle = "❯"; - - let args: Vec = args().collect(); - let shell: String = shell(args.clone()); - - let root_indicator = root_indicator(); - - let err: String = err(args.clone()); - let err_indicator = err_indicator(err); - - // SSH status - let ssh_char = ssh_char(); - - //Git status - let git_branch = get_git_branch(); - let git_repo_root = get_git_root(); - let git_repo_name = get_git_repo_name(&git_repo_root.clone()).truecolor(122, 68, 24); - let git_char = get_git_char(&git_branch); - - //pwd - let homedir = homedir(); - let pwd = current_dir()?; - let mut cur_dir = pwd.display().to_string(); - cur_dir = cur_dir.replace(&git_repo_root, ""); // Remove git repo root - cur_dir = cur_dir.replace(&homedir, "~"); // Abreviate homedir with "~" - cur_dir = abrev_path(&cur_dir); - - print!( - "{}{}{}{}{}{}{} ", - ssh_char, - get_shell_char(&shell).truecolor(75, 75, 75), - git_repo_name, - git_char, - cur_dir.italic().truecolor(82, 82, 82), - root_indicator, - err_indicator, - ); - - Ok(()) -} diff --git a/src/old/shell.rs b/src/old/shell.rs deleted file mode 100644 index 513ea28..0000000 --- a/src/old/shell.rs +++ /dev/null @@ -1,20 +0,0 @@ -pub fn get_shell_char(shell: &str) -> String { - let shell_char = match shell { - "bash" | "/bin/bash" | "/usr/bin/bash" | "-bash" => " ", - "zsh" | "/bin/zsh" | "/usr/bin/zsh" | "-zsh" => "󰰶 ", - "fish" => "󰈺 ", - "nushell" => " ", - "ion" => " ", - "oursh" => "󱢇 ", - _ => "󱆃 ", - }; - shell_char.to_string() -} - -pub fn shell(args: Vec) -> String { - if args.len() > 1 { - args[1].clone() // Shell symbol - } else { - "none".to_string() - } -} From 309021fb68ff4dc57f641fb2d60050eae1f3f064 Mon Sep 17 00:00:00 2001 From: candifloss Date: Fri, 29 Nov 2024 16:38:19 +0530 Subject: [PATCH 15/23] comments --- src/indicators/git.rs | 8 ++++---- src/main.rs | 1 - 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/indicators/git.rs b/src/indicators/git.rs index 2425808..b70b094 100644 --- a/src/indicators/git.rs +++ b/src/indicators/git.rs @@ -28,10 +28,10 @@ pub fn info() -> Option<(String, String)> { pub fn repo_name(path: &str) -> String { Path::new(path) - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or("") // Default value if None - .to_string() // Convert &str to String + .file_name() // Extracts the last component of the path. + .and_then(|name| name.to_str()) // Converts the `OsStr` to `&str`. + .unwrap_or("") // Default value(empty string) if None(no valid name) + .to_string() // Converts &str to String } //Git branch indicator diff --git a/src/main.rs b/src/main.rs index 041833c..87be1d1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,7 +46,6 @@ fn main() { components.push(user::indicator()); } if indicate_err { - //components.push(error::indicator(cmd_args)); components.push(error::indicator(&cmd_args)); } if show_pwd { From 82528f13be752eb115f37ab1f56d3994e757a937 Mon Sep 17 00:00:00 2001 From: candifloss Date: Sat, 30 Nov 2024 11:31:50 +0530 Subject: [PATCH 16/23] Improved efficiency & best practices, & comments --- src/indicators/git.rs | 6 +-- src/indicators/pwd.rs | 86 +++++++++++++++++++++--------------------- src/indicators/ssh.rs | 19 ++++++---- src/indicators/user.rs | 13 ++++--- src/main.rs | 2 + 5 files changed, 65 insertions(+), 61 deletions(-) diff --git a/src/indicators/git.rs b/src/indicators/git.rs index b70b094..bc5cf99 100644 --- a/src/indicators/git.rs +++ b/src/indicators/git.rs @@ -11,8 +11,8 @@ pub const OTHER_COL: ansi_term::Colour = RGB(82, 82, 82); // pub const NORMIE_COL: ansi_term::Colour = RGB(255, 255, 255); // White pub fn info() -> Option<(String, String)> { - let output = Command::new("git") - .args(["rev-parse", "--show-toplevel", "--abbrev-ref", "HEAD"]) + let output = Command::new("git") // Program/Command to execute + .args(["rev-parse", "--show-toplevel", "--abbrev-ref", "HEAD"]) // Arguments .output() .ok()?; @@ -28,7 +28,7 @@ pub fn info() -> Option<(String, String)> { pub fn repo_name(path: &str) -> String { Path::new(path) - .file_name() // Extracts the last component of the path. + .file_name() // Extracts the last component of the path. .and_then(|name| name.to_str()) // Converts the `OsStr` to `&str`. .unwrap_or("") // Default value(empty string) if None(no valid name) .to_string() // Converts &str to String diff --git a/src/indicators/pwd.rs b/src/indicators/pwd.rs index 11a5c45..691681a 100644 --- a/src/indicators/pwd.rs +++ b/src/indicators/pwd.rs @@ -16,7 +16,7 @@ fn home_dir() -> String { fn full_path() -> String { current_dir().map_or_else( |_| UNKNOWN_PATH.to_string(), - |path| path.to_string_lossy().to_string(), + |path| path.display().to_string(), ) } @@ -27,34 +27,29 @@ fn remove_repo(pwd_path: &str, repo_path: &str) -> String { /// Replace the 'home directory' part of the path with a the '~' symbol fn replace_home(path: &str) -> String { - let homedir = home_dir(); - path.replacen(&homedir, "~", 1) + path.replacen(&home_dir(), "~", 1) } fn short(path: &str, slash_limit: u8) -> String { - let slashes = path.matches('/').count(); + let slashes = path.matches('/').count(); // Get the number of slashes if slashes <= slash_limit.into() { - path.to_string() // Short path, return without changes - } else { - // Long path, shorten it - let parts: Vec<&str> = path.split('/').collect(); // Split the path into parts - let first = if path.starts_with('~') { "~" } else { "" }; // Determine the first part correctly - let last = parts[parts.len() - 1]; // The last part - - // Abbreviate middle parts (take the first character of each) - let abbreviated_middle: Vec = parts[1..parts.len() - 1] // Skip the first and last part - .iter() - .filter(|&&part| !part.is_empty()) // Avoid empty parts (like "//") - .map(|&part| part.chars().next().unwrap().to_string()) // Take the first letter - .collect(); - - // Join the parts back together with "/" and return the shortened path - let mut shortened_path = vec![first.to_string()]; - shortened_path.extend(abbreviated_middle); - shortened_path.push(last.to_string()); - - shortened_path.join("/") + return path.to_string(); // Short path, return without changes } + + // Else: Long path, shorten it + let parts: Vec<&str> = path.split('/').collect(); // Split the path into parts + let first = if path.starts_with('~') { "~" } else { "" }; // Determine the first part correctly + let last = parts[parts.len() - 1]; // The last part + + // Abbreviate middle parts (take the first character of each) + let abbreviated_middle = parts[1..parts.len() - 1] // Skip the first and last part + .iter() + .filter(|&&part| !part.is_empty()) // Avoid empty parts (like "//") + .map(|&part| part.chars().next().unwrap().to_string()) // Take the first letter + .collect::>() // Collect the parts as a Vec + .join("/"); // Join them with a "/" separator + + format!("{first}/{abbreviated_middle}/{last}") // Final } pub fn pwd( @@ -63,9 +58,10 @@ pub fn pwd( replace_repo: bool, git_repo: Option, ) -> ANSIGenericString<'static, str> { - let mut path = full_path(); - let slash_limit: u8 = if replace_repo { 2 } else { 3 }; + let slash_limit: u8 = if replace_repo { 2 } else { 3 }; // Max number of slashes + let mut path = full_path(); // Get the full path of he current directory + // Replace a git repo root path with the repo's name if replace_repo && git_repo.is_some() { if let Some(repo_path) = git_repo { path = remove_repo(&path, &repo_path); @@ -73,26 +69,28 @@ pub fn pwd( if shorten_path { path = short(&path, slash_limit); } - match path.as_str() { - "" => REPO_COL.paint(repo_name), - _ => format!( + return if path.is_empty() { + REPO_COL.paint(repo_name) // In the root dir of the repo + } else { + // In a subdir inside the repo + format!( "{}{}{}", - REPO_COL.paint(repo_name), - MAIN_COL.paint(" \u{F02A2} "), - PATH_COL.italic().paint(path) + REPO_COL.paint(repo_name), // Repo name + MAIN_COL.paint(" \u{F02A2} "), // Seperator + PATH_COL.italic().paint(path) // Sub-directory ) - .into(), - } - } else { - PATH_COL.italic().paint(path) + .into() + }; } - } else if abbrev_home { - path = replace_home(&path); - if shorten_path { - path = short(&path, slash_limit); - } - PATH_COL.italic().paint(path) - } else { - PATH_COL.italic().paint(path) } + + // Replace the home directory path with the 'home symbol': ~ + if abbrev_home { + path = replace_home(&path); + } + if shorten_path { + path = short(&path, slash_limit); + } + + PATH_COL.italic().paint(path) } diff --git a/src/indicators/ssh.rs b/src/indicators/ssh.rs index ef4aae7..0e9bc88 100644 --- a/src/indicators/ssh.rs +++ b/src/indicators/ssh.rs @@ -1,19 +1,22 @@ use ansi_term::ANSIGenericString; use ansi_term::Colour::RGB; -use std::env::var; +use std::env::var; // For environment variables -// SSH indicator symbol -pub const SSH_SYMBOL: &str = "\u{276F}"; // "❯" -pub const SSH_COL: ansi_term::Colour = RGB(255, 149, 0); // A ind of orange -pub const NORMIE_COL: ansi_term::Colour = RGB(255, 255, 255); // White +/// Constants +pub const SSH_SYMBOL: &str = "\u{276F}"; // SSH indicator symbol: "❯" +pub const SSH_COL: ansi_term::Colour = RGB(255, 149, 0); // In SSH session +pub const NORMIE_COL: ansi_term::Colour = RGB(255, 255, 255); // Non-SSH session +const SSH_ENV_VARS: [&str; 2] = ["SSH_TTY", "SSH_CONNECTION"]; // Environment variables normally present in SSH sessions +/// Checks if current session is an SSH session fn is_ssh_session() -> bool { - var("SSH_TTY").is_ok() || var("SSH_CONNECTION").is_ok() + SSH_ENV_VARS.iter().any(|&var_name| var(var_name).is_ok()) // any() iterates through the iter and stops at first `true`. Equal to `||`(`or` condition) } -//SSH shell indicator +/// SSH shell indicator pub fn indicator() -> ANSIGenericString<'static, str> { - if is_ssh_session() { + let is_ssh: bool = is_ssh_session(); + if is_ssh { SSH_COL.paint(SSH_SYMBOL) } else { NORMIE_COL.paint(SSH_SYMBOL) diff --git a/src/indicators/user.rs b/src/indicators/user.rs index 45d380a..3521a58 100644 --- a/src/indicators/user.rs +++ b/src/indicators/user.rs @@ -1,11 +1,11 @@ use ansi_term::ANSIGenericString; use ansi_term::Colour::RGB; -use std::env::var; +use std::env::var; // For environment variables -// User indicator symbol -pub const USER_SYMBOL: &str = "\u{276F}"; // "❯" -pub const ROOT_COL: ansi_term::Colour = RGB(255, 53, 94); // Riot red or something -pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // A kind of green +pub const USER_SYMBOL: &str = "\u{276F}"; // User indicator symbol: "❯" +pub const ROOT_COL: ansi_term::Colour = RGB(255, 53, 94); // If the user is root +pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // Regular user +const ROOT_USER: &str = "root"; // Root username constant //Root user indicator pub fn username() -> String { @@ -13,7 +13,8 @@ pub fn username() -> String { } pub fn indicator() -> ANSIGenericString<'static, str> { - if username() == "root" { + let user = username(); + if user == ROOT_USER { ROOT_COL.paint(USER_SYMBOL) } else { NORMIE_COL.paint(USER_SYMBOL) diff --git a/src/main.rs b/src/main.rs index 87be1d1..3f1bcc7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ fn main() { let mut components: Vec> = Vec::new(); // The components will be concated into one string + // Hard-coded configuration. This will be replaced by a configuration file in a future version let indicate_user: bool = true; let indicate_ssh: bool = true; let indicate_err: bool = true; @@ -33,6 +34,7 @@ fn main() { None }; + // Conditionally add the parts of the prompt if indicate_ssh { components.push(ssh::indicator()); } From 735158a1235e4df9ccc1f7a4e52f185f03313367 Mon Sep 17 00:00:00 2001 From: candifloss Date: Sat, 30 Nov 2024 12:18:47 +0530 Subject: [PATCH 17/23] improved code readability & comments --- src/indicators/pwd.rs | 4 ++- src/main.rs | 59 +++++++++++++++++++++++-------------------- 2 files changed, 34 insertions(+), 29 deletions(-) diff --git a/src/indicators/pwd.rs b/src/indicators/pwd.rs index 691681a..328acf1 100644 --- a/src/indicators/pwd.rs +++ b/src/indicators/pwd.rs @@ -58,7 +58,8 @@ pub fn pwd( replace_repo: bool, git_repo: Option, ) -> ANSIGenericString<'static, str> { - let slash_limit: u8 = if replace_repo { 2 } else { 3 }; // Max number of slashes + //let slash_limit: u8 = if replace_repo { 2 } else { 3 }; // Max number of slashes + let slash_limit: u8 = 3; // Max number of slashes let mut path = full_path(); // Get the full path of he current directory // Replace a git repo root path with the repo's name @@ -67,6 +68,7 @@ pub fn pwd( path = remove_repo(&path, &repo_path); let repo_name = repo_name(&repo_path); if shorten_path { + let slash_limit: u8 = 2; // Max number of slashes path = short(&path, slash_limit); } return if path.is_empty() { diff --git a/src/main.rs b/src/main.rs index 3f1bcc7..c90dcca 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,17 +6,25 @@ mod indicators { pub mod user; } -use crate::indicators::error; -use crate::indicators::git; -use crate::indicators::pwd; -use crate::indicators::ssh; -use crate::indicators::user; +use crate::indicators::{error, git, pwd, ssh, user}; use ansi_term::{ANSIGenericString, ANSIGenericStrings}; -fn main() { - let cmd_args: Vec = std::env::args().collect(); // Cmd-line args +// Add a component to the prompt if the condition is true. +fn add_component( + components: &mut Vec>, // Vector to hold components of the prompt. + condition: bool, // Condition to add the component + component_fn: impl FnOnce() -> ANSIGenericString<'static, str>, // Function to create the component(takes no arguments, returns `ANSIGenericString`) is passed here. +) { + if condition { + components.push(component_fn()); // Push the generated component to the vector. + } +} - let mut components: Vec> = Vec::new(); // The components will be concated into one string +fn main() { + let cmd_args: Vec = std::env::args().collect(); // Command-line args + + // Vector to hold the different parts of the prompt. + let mut components: Vec> = Vec::new(); // The components will be concatenated into a single string in the end. // Hard-coded configuration. This will be replaced by a configuration file in a future version let indicate_user: bool = true; @@ -28,6 +36,7 @@ fn main() { let shorten_path: bool = true; let replace_repo: bool = true; + // Conditionally fetch Git-related info if required, or set to None let git_info: Option<(String, String)> = if indicate_git_branch || replace_repo { git::info() } else { @@ -35,31 +44,25 @@ fn main() { }; // Conditionally add the parts of the prompt - if indicate_ssh { - components.push(ssh::indicator()); - } - if indicate_git_branch { - match git_info { - Some(ref info) => components.push(git::indicator(Some(info.1.clone()))), - None => components.push(git::indicator(None)), - } - } - if indicate_user { - components.push(user::indicator()); - } - if indicate_err { - components.push(error::indicator(&cmd_args)); - } + add_component(&mut components, indicate_ssh, ssh::indicator); + add_component(&mut components, indicate_git_branch, || { + git::indicator(git_info.as_ref().map(|info| info.1.clone())) + }); + add_component(&mut components, indicate_user, user::indicator); + add_component(&mut components, indicate_err, || { + error::indicator(&cmd_args) + }); + + // Insert `pwd` at the beginning of the prompt if show_pwd { - let repo_path = match git_info { - Some(info) => Some(info.0), - None => None, - }; + let repo_path = git_info.map(|info| info.0); components.insert( 0, pwd::pwd(abbrev_home, shorten_path, replace_repo, repo_path), ); } + + // Finally, combine the parts into a single prompts string let prompt: ANSIGenericStrings<'_, str> = ANSIGenericStrings(&components[..]); - print!("{prompt} "); + print!("{prompt} "); // A trailing space for aesthetic formatting. `print!()` prevents an extra newline, unlike `println!()` } From 3ca299e14f6731f5d0fac9affef974be655bcb2d Mon Sep 17 00:00:00 2001 From: candifloss Date: Sat, 30 Nov 2024 12:22:49 +0530 Subject: [PATCH 18/23] Minor change in logic --- src/indicators/pwd.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/indicators/pwd.rs b/src/indicators/pwd.rs index 328acf1..21fb3a3 100644 --- a/src/indicators/pwd.rs +++ b/src/indicators/pwd.rs @@ -58,8 +58,7 @@ pub fn pwd( replace_repo: bool, git_repo: Option, ) -> ANSIGenericString<'static, str> { - //let slash_limit: u8 = if replace_repo { 2 } else { 3 }; // Max number of slashes - let slash_limit: u8 = 3; // Max number of slashes + let mut slash_limit: u8 = 3; // Max number of slashes let mut path = full_path(); // Get the full path of he current directory // Replace a git repo root path with the repo's name @@ -68,7 +67,7 @@ pub fn pwd( path = remove_repo(&path, &repo_path); let repo_name = repo_name(&repo_path); if shorten_path { - let slash_limit: u8 = 2; // Max number of slashes + slash_limit = 2; // Max number of slashes path = short(&path, slash_limit); } return if path.is_empty() { From 264719da5e11047973cf105430852dea81d8c961 Mon Sep 17 00:00:00 2001 From: candifloss Date: Sat, 30 Nov 2024 14:16:14 +0530 Subject: [PATCH 19/23] Updated README --- Cargo.lock | 4 +-- Cargo.toml | 2 +- README.md | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++-- src/main.rs | 3 +- 4 files changed, 82 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5e5dcd2..39cac17 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "ansi_term" @@ -13,7 +13,7 @@ dependencies = [ [[package]] name = "prettyprompt" -version = "0.1.0" +version = "0.2.0" dependencies = [ "ansi_term", ] diff --git a/Cargo.toml b/Cargo.toml index 886dff1..56acdc0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "prettyprompt" -version = "0.1.0" +version = "0.2.0" edition = "2021" [dependencies] diff --git a/README.md b/README.md index f974528..62c62d2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,82 @@ -# PrettyPrompt +# PrettyPrompt -A pretty shell prompt, written in rust +A pretty shell prompt, written in rust + +## Current Features + +- **User indicator** - Symbol with different colors for root user and normal users +- **Error indicator** - Symbol with different colors to indicate if the last comment was successful +- **Git repo indicator** + - Indicates if the current directory is a repo or a regular directory + - Branches indicated by different colors +- **SSH indicator** - Symbol to indicate if the current shell is in an SSH session +- **Current directory** + - Abbreviated if the path is too long + - Replaces the user's home directory with a `~` symbol + - Show the repo's name if currently in a git repo ## Screenshot ![screenshot](https://git.candifloss.cc/candifloss/PrettyPrompt/raw/branch/main/screenshot/BashPromptExampleScreenshoot.png "Screenshot") -Ignore the zsh prompt in the screenshot. + +## Planned Features + +- Right-hand side prompt +- Configuration file + - Choose only the components you need + - Change appearance + - symbols and texts + - colors + - order and position + - Etc. + - User-defined components + - Static sybols or strings + - Shell symbol + - Host name + - Etc. + - Dynamic components by running custom commands + - Time & date + - More `git` information + - System stats + - Basically, anything you like + +## Current Limitations + +- Not user-configurable, yet - any changes in the current stage require hard-coding. +- Exit code of the last command requires to be passed as a command-line argument. + +## Usage + +The binary needs to be in your `$PATH`. Place it somewhere like `/usr/bin/`, or add the appropriate path to the `$PATH` variable +The configuration depends on the shell and the configuration file location can vary according to your distro. + +### `bash` + +System-wide: `/etc/bash.bashrc` or User-specific: `$HOME/.bashrc`: +```bash +PS1="" // PS1 is a fixed prompt variable. +PROMPT_COMMAND="prettyprompt $?" // This updates the prompt every time. +``` + +### `ion` + +User-specific: `$HOME/.config/ion/initrc`: + +```ion +# This is currently the only way to customize the prompt according to the docs +fn PROMPT + prettyprompt $? +end +``` + +## Changes since the last version + - **Updated Output String Type:** Improved compatibility with other shells. + - **Revamped Indicator Symbols:** Enhanced the visual aspect of the prompt. + - **Removed Shell Symbol:** Determining the shell is practically not possible. + - **Conditional Component Inclusion:** A first step towards user-configuration expected in future versions. + - **Code Improvements:** readability and performance + - **Refactoring:** Modular structure for better readability and maintenance. + - **Modularization:** Separate modules for cleaner organization. + - **Error Handling:** Improved logic to exclude error messages from the prompt. + - **Enhanced Documentation:** Comments for better comprehension. + diff --git a/src/main.rs b/src/main.rs index c90dcca..3d6ed5c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -64,5 +64,6 @@ fn main() { // Finally, combine the parts into a single prompts string let prompt: ANSIGenericStrings<'_, str> = ANSIGenericStrings(&components[..]); - print!("{prompt} "); // A trailing space for aesthetic formatting. `print!()` prevents an extra newline, unlike `println!()` + // `print!()` prevents an extra newline, unlike `println!()` + print!("{prompt} "); // A trailing space for aesthetic formatting. } From 676671112236062ba0ac850eab50646daaf4456e Mon Sep 17 00:00:00 2001 From: candifloss Date: Sat, 30 Nov 2024 16:47:36 +0530 Subject: [PATCH 20/23] Modified README --- README.md | 57 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 47 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 62c62d2..00164cf 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ A pretty shell prompt, written in rust ## Planned Features -- Right-hand side prompt +- Right-hand side prompt: Implementing this is a challenge on non-`zsh` shells - Configuration file - Choose only the components you need - Change appearance @@ -30,7 +30,7 @@ A pretty shell prompt, written in rust - order and position - Etc. - User-defined components - - Static sybols or strings + - Static symbols or strings - Shell symbol - Host name - Etc. @@ -45,30 +45,64 @@ A pretty shell prompt, written in rust - Not user-configurable, yet - any changes in the current stage require hard-coding. - Exit code of the last command requires to be passed as a command-line argument. +## Tested on + +Ubuntu 24.04 + - `bash` 5.2 + - `zsh` 5.9 + - `ion` 1.0.0-alpha + +## Installation + +1. Download the pre-built binary from [releases](https://git.candifloss.cc/candifloss/PrettyPrompt/releases), or build from source: + +```bash +git clone https://git.candifloss.cc/candifloss/PrettyPrompt.git +cd PrettyPrompt/ +cargo build --release #Now find the `prettyprompt` binary in `target/release/` +``` +2. Move the binary to a path in your `$PATH`. Eg: +```bash +sudo mv /path/to/prettyprompt /usr/bin/ +``` +Or add it to your `$PATH` variable by adding this to your `bashrc`, `zshrc`, or `ion/initrc` +```bash +export PATH="$PATH:/your/path" +``` + ## Usage -The binary needs to be in your `$PATH`. Place it somewhere like `/usr/bin/`, or add the appropriate path to the `$PATH` variable -The configuration depends on the shell and the configuration file location can vary according to your distro. +The binary needs to be in your `$PATH`. Place it somewhere like `/usr/bin/`, or add the appropriate path to the `$PATH` variable. +The configuration depends on the shell, and the file location can vary according to your distro. Please consult the documentations or forums of your shell for more accurate information. ### `bash` -System-wide: `/etc/bash.bashrc` or User-specific: `$HOME/.bashrc`: + - The `PS1` variable sets a fixed prompt string. + - This `PROMPT_COMMAND` variable updates the prompt every time. + +System-wide: `/etc/bash.bashrc`, or User-specific: `$HOME/.bashrc`: ```bash -PS1="" // PS1 is a fixed prompt variable. -PROMPT_COMMAND="prettyprompt $?" // This updates the prompt every time. +PS1="" # Set it to an empty string +PROMPT_COMMAND='prettyprompt $?' # Single quotes, not double quotes ``` ### `ion` -User-specific: `$HOME/.config/ion/initrc`: - +The `PROMPT` function is currently the only way to customize the prompt according to the ion shell docs. +User-specific config file: `$HOME/.config/ion/initrc`: ```ion -# This is currently the only way to customize the prompt according to the docs fn PROMPT prettyprompt $? end ``` +### `zsh` +Export the `PS1` variable with the output of `prettyprompt $?` as its value. +User-specific: `$HOME/.zshrc`, System-wide: `/etc/zsh/zshrc`: +```zsh +export PS1='$(prettyprompt $?)' +``` + ## Changes since the last version - **Updated Output String Type:** Improved compatibility with other shells. - **Revamped Indicator Symbols:** Enhanced the visual aspect of the prompt. @@ -80,3 +114,6 @@ end - **Error Handling:** Improved logic to exclude error messages from the prompt. - **Enhanced Documentation:** Comments for better comprehension. +## Acknowledgement + +The current default(and only) theme is inspired by [s1ck94](https://github.com/zimfw/s1ck94) theme from [zimfw](https://zimfw.sh/). From d9fdd8fa9e84c7ee5947c6edae9fc79be06e4e2d Mon Sep 17 00:00:00 2001 From: candifloss Date: Sun, 1 Dec 2024 18:31:07 +0530 Subject: [PATCH 21/23] updated README --- README.md | 87 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 49 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 00164cf..8f00cc8 100644 --- a/README.md +++ b/README.md @@ -21,29 +21,21 @@ A pretty shell prompt, written in rust ## Planned Features -- Right-hand side prompt: Implementing this is a challenge on non-`zsh` shells -- Configuration file +- **Right-hand side prompt**: Challenging to implement on non-zsh shells. +- **Configuration file** - Choose only the components you need - Change appearance - - symbols and texts - - colors - - order and position - - Etc. - - User-defined components - - Static symbols or strings - - Shell symbol - - Host name - - Etc. - - Dynamic components by running custom commands - - Time & date - - More `git` information - - System stats - - Basically, anything you like + - Symbols and text + - Colors + - Order and position + - Custom components + - Static: Shell icon, Host name, etc. + - Dynamic: Time &date, system stats, or any custom commands ## Current Limitations -- Not user-configurable, yet - any changes in the current stage require hard-coding. -- Exit code of the last command requires to be passed as a command-line argument. +- **Hard-Coded Configuration**: User customization is not available yet. +- **Exit Code Requirement**: Must pass the last command’s exit code as a command-line argument. ## Tested on @@ -54,33 +46,41 @@ Ubuntu 24.04 ## Installation -1. Download the pre-built binary from [releases](https://git.candifloss.cc/candifloss/PrettyPrompt/releases), or build from source: +**Step 1. Get the binary** + - Option 1. Download the pre-built binary from the [releases page](https://git.candifloss.cc/candifloss/PrettyPrompt/releases). + - Option 2. Build from source(if you have [rust](https://www.rust-lang.org/tools/install) installed): -```bash -git clone https://git.candifloss.cc/candifloss/PrettyPrompt.git -cd PrettyPrompt/ -cargo build --release #Now find the `prettyprompt` binary in `target/release/` +```bash +git clone https://git.candifloss.cc/candifloss/PrettyPrompt.git +cd PrettyPrompt/ +cargo build --release +# Binary location: `target/release/prettyprompt` ``` -2. Move the binary to a path in your `$PATH`. Eg: -```bash + +**Step 2. Add to `$PATH`** + - Option 1. Move the binary to a directory in your `$PATH`. Eg: +```bash sudo mv /path/to/prettyprompt /usr/bin/ ``` -Or add it to your `$PATH` variable by adding this to your `bashrc`, `zshrc`, or `ion/initrc` -```bash -export PATH="$PATH:/your/path" -``` + - Option 2. Add the directory containing the binary to `$PATH` + System-wide: `/etc/profile` + User-specific: `~/.profile` + Shell-specific: `bashrc`, `zshrc`, etc. +```bash +export PATH="$PATH:/path/where/the/binary/is/" +``` ## Usage -The binary needs to be in your `$PATH`. Place it somewhere like `/usr/bin/`, or add the appropriate path to the `$PATH` variable. -The configuration depends on the shell, and the file location can vary according to your distro. Please consult the documentations or forums of your shell for more accurate information. +Configuration varies by shell, and the file location varies by distro. Consult your shell's docs or community resources for details. Note that the exit code of the last command(usually `$?` variable) must be passed as a command-line argument. ### `bash` - The `PS1` variable sets a fixed prompt string. - This `PROMPT_COMMAND` variable updates the prompt every time. -System-wide: `/etc/bash.bashrc`, or User-specific: `$HOME/.bashrc`: +System-wide: `/etc/bash.bashrc` +User-specific: `~/.bashrc`: ```bash PS1="" # Set it to an empty string PROMPT_COMMAND='prettyprompt $?' # Single quotes, not double quotes @@ -88,8 +88,8 @@ PROMPT_COMMAND='prettyprompt $?' # Single quotes, not double quotes ### `ion` -The `PROMPT` function is currently the only way to customize the prompt according to the ion shell docs. -User-specific config file: `$HOME/.config/ion/initrc`: +The `PROMPT` function is currently the only way to customize the prompt according to the `ion` shell docs. +User-specific config: `~/.config/ion/initrc`: ```ion fn PROMPT prettyprompt $? @@ -98,15 +98,20 @@ end ### `zsh` Export the `PS1` variable with the output of `prettyprompt $?` as its value. -User-specific: `$HOME/.zshrc`, System-wide: `/etc/zsh/zshrc`: -```zsh +User-specific: `~/.zshrc` +System-wide: `/etc/zsh/zshrc` +```sh export PS1='$(prettyprompt $?)' ``` +### Other shells + +For other shells, refer their docs to set a dynamic prompt. Ensure the last command's exit code (`$?` or equivalent) is passed to `prettyprompt`. + ## Changes since the last version - **Updated Output String Type:** Improved compatibility with other shells. - **Revamped Indicator Symbols:** Enhanced the visual aspect of the prompt. - - **Removed Shell Symbol:** Determining the shell is practically not possible. + - **Removed Shell Icon:** Determining the shell is practically not possible. - **Conditional Component Inclusion:** A first step towards user-configuration expected in future versions. - **Code Improvements:** readability and performance - **Refactoring:** Modular structure for better readability and maintenance. @@ -116,4 +121,10 @@ export PS1='$(prettyprompt $?)' ## Acknowledgement -The current default(and only) theme is inspired by [s1ck94](https://github.com/zimfw/s1ck94) theme from [zimfw](https://zimfw.sh/). +The current default (and only) theme draws inspiration from [s1ck94](https://github.com/zimfw/s1ck94) theme of [zimfw](https://zimfw.sh/). + +## Why this project? + +- **Efficiency**: Avoids repeated invocation of multiple binaries like `tr`, `grep`, `echo`, `git`, `sed`, etc., which would otherwise be used dozens of times in shell scripts just to generate a colored string. +- **Universality**: Eliminates the need to write separate scripts in different shell languages for various shells. +- **Learning Rust**: Serves as a fun and practical project to learn and apply Rust programming skills. \ No newline at end of file From dbd272eb480ac06d50112637a9661d211e260a01 Mon Sep 17 00:00:00 2001 From: candifloss Date: Sun, 1 Dec 2024 21:15:46 +0530 Subject: [PATCH 22/23] updated comments --- README.md | 4 ++-- src/indicators/git.rs | 21 +++++++++++---------- src/indicators/ssh.rs | 3 +-- src/indicators/user.rs | 3 ++- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 8f00cc8..8100371 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # PrettyPrompt -A pretty shell prompt, written in rust +A pretty shell prompt, written in rust. ## Current Features @@ -126,5 +126,5 @@ The current default (and only) theme draws inspiration from [s1ck94](https://git ## Why this project? - **Efficiency**: Avoids repeated invocation of multiple binaries like `tr`, `grep`, `echo`, `git`, `sed`, etc., which would otherwise be used dozens of times in shell scripts just to generate a colored string. -- **Universality**: Eliminates the need to write separate scripts in different shell languages for various shells. +- **Portability**: Eliminates the need to write separate scripts in different shell languages for various shells. - **Learning Rust**: Serves as a fun and practical project to learn and apply Rust programming skills. \ No newline at end of file diff --git a/src/indicators/git.rs b/src/indicators/git.rs index bc5cf99..e459fe9 100644 --- a/src/indicators/git.rs +++ b/src/indicators/git.rs @@ -3,13 +3,13 @@ use ansi_term::Colour::RGB; use std::path::Path; use std::process::Command; -// SSH indicator symbol -pub const GIT_SYMBOL: &str = "\u{276F}"; // "❯" -pub const MAIN_COL: ansi_term::Colour = RGB(178, 98, 44); // -pub const DEV_COL: ansi_term::Colour = RGB(54, 159, 150); // -pub const OTHER_COL: ansi_term::Colour = RGB(82, 82, 82); // -pub const NORMIE_COL: ansi_term::Colour = RGB(255, 255, 255); // White +pub const GIT_SYMBOL: &str = "\u{276F}"; // Git indicator symbol: "❯" +pub const MAIN_COL: ansi_term::Colour = RGB(178, 98, 44); +pub const DEV_COL: ansi_term::Colour = RGB(54, 159, 150); +pub const DEFAULT_BRANCH_COL: ansi_term::Colour = RGB(255, 255, 255); +pub const NORMIE_COL: ansi_term::Colour = RGB(82, 82, 82); +/// Returns the repo's root and branch, if present pub fn info() -> Option<(String, String)> { let output = Command::new("git") // Program/Command to execute .args(["rev-parse", "--show-toplevel", "--abbrev-ref", "HEAD"]) // Arguments @@ -20,12 +20,13 @@ pub fn info() -> Option<(String, String)> { let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string(); let parts: Vec<&str> = output_str.split('\n').collect(); if parts.len() == 2 { - return Some((parts[0].to_string(), parts[1].to_string())); + return Some((parts[0].to_string(), parts[1].to_string())); // If the `git`` command returns a repo and branch } } - None + None // If the current directory is not in a git repo } +/// The name of the repo pub fn repo_name(path: &str) -> String { Path::new(path) .file_name() // Extracts the last component of the path. @@ -34,13 +35,13 @@ pub fn repo_name(path: &str) -> String { .to_string() // Converts &str to String } -//Git branch indicator +/// Git branch indicator pub fn indicator(branch: Option) -> ANSIGenericString<'static, str> { match branch { Some(b) => match b.as_str() { "main" => MAIN_COL.paint(GIT_SYMBOL), "dev" => DEV_COL.paint(GIT_SYMBOL), - _ => OTHER_COL.paint(GIT_SYMBOL), + _ => DEFAULT_BRANCH_COL.paint(GIT_SYMBOL), }, None => NORMIE_COL.paint(GIT_SYMBOL), } diff --git a/src/indicators/ssh.rs b/src/indicators/ssh.rs index 0e9bc88..500b5eb 100644 --- a/src/indicators/ssh.rs +++ b/src/indicators/ssh.rs @@ -2,10 +2,9 @@ use ansi_term::ANSIGenericString; use ansi_term::Colour::RGB; use std::env::var; // For environment variables -/// Constants pub const SSH_SYMBOL: &str = "\u{276F}"; // SSH indicator symbol: "❯" pub const SSH_COL: ansi_term::Colour = RGB(255, 149, 0); // In SSH session -pub const NORMIE_COL: ansi_term::Colour = RGB(255, 255, 255); // Non-SSH session +pub const NORMIE_COL: ansi_term::Colour = RGB(82, 82, 82); // Non-SSH session const SSH_ENV_VARS: [&str; 2] = ["SSH_TTY", "SSH_CONNECTION"]; // Environment variables normally present in SSH sessions /// Checks if current session is an SSH session diff --git a/src/indicators/user.rs b/src/indicators/user.rs index 3521a58..451303f 100644 --- a/src/indicators/user.rs +++ b/src/indicators/user.rs @@ -7,11 +7,12 @@ pub const ROOT_COL: ansi_term::Colour = RGB(255, 53, 94); // If the user is root pub const NORMIE_COL: ansi_term::Colour = RGB(0, 255, 180); // Regular user const ROOT_USER: &str = "root"; // Root username constant -//Root user indicator +/// Username of current user pub fn username() -> String { var("USER").unwrap_or_else(|_| "UnknownUser".to_string()) } +/// Root user indicator pub fn indicator() -> ANSIGenericString<'static, str> { let user = username(); if user == ROOT_USER { From 859f16cd08d996bd52c2ec47b381107816b217de Mon Sep 17 00:00:00 2001 From: candifloss Date: Mon, 2 Dec 2024 09:49:45 +0530 Subject: [PATCH 23/23] updated README --- README.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 8100371..4f5c7d0 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ A pretty shell prompt, written in rust. - Order and position - Custom components - Static: Shell icon, Host name, etc. - - Dynamic: Time &date, system stats, or any custom commands + - Dynamic: Time & date, system stats, or any custom commands ## Current Limitations @@ -46,9 +46,8 @@ Ubuntu 24.04 ## Installation -**Step 1. Get the binary** - - Option 1. Download the pre-built binary from the [releases page](https://git.candifloss.cc/candifloss/PrettyPrompt/releases). - - Option 2. Build from source(if you have [rust](https://www.rust-lang.org/tools/install) installed): +**Step 1. Build binary from source** +This requires [rust](https://www.rust-lang.org/tools/install) installed on your system. ```bash git clone https://git.candifloss.cc/candifloss/PrettyPrompt.git @@ -60,7 +59,7 @@ cargo build --release **Step 2. Add to `$PATH`** - Option 1. Move the binary to a directory in your `$PATH`. Eg: ```bash -sudo mv /path/to/prettyprompt /usr/bin/ +sudo mv target/release/prettyprompt /usr/bin/ ``` - Option 2. Add the directory containing the binary to `$PATH` System-wide: `/etc/profile` @@ -72,12 +71,12 @@ export PATH="$PATH:/path/where/the/binary/is/" ## Usage -Configuration varies by shell, and the file location varies by distro. Consult your shell's docs or community resources for details. Note that the exit code of the last command(usually `$?` variable) must be passed as a command-line argument. +Configuration varies by shell, and the file location varies by distro. Refer your shell's docs or community resources for details. Note that the exit code of the last command(usually `$?` variable) must be passed as a command-line argument. ### `bash` - The `PS1` variable sets a fixed prompt string. - - This `PROMPT_COMMAND` variable updates the prompt every time. + - This `PROMPT_COMMAND` variable sets a dynamic prompt. System-wide: `/etc/bash.bashrc` User-specific: `~/.bashrc`: @@ -101,7 +100,7 @@ Export the `PS1` variable with the output of `prettyprompt $?` as its value. User-specific: `~/.zshrc` System-wide: `/etc/zsh/zshrc` ```sh -export PS1='$(prettyprompt $?)' +export PS1='$(prettyprompt $?)' # Notice the single quotes ``` ### Other shells @@ -109,7 +108,7 @@ export PS1='$(prettyprompt $?)' For other shells, refer their docs to set a dynamic prompt. Ensure the last command's exit code (`$?` or equivalent) is passed to `prettyprompt`. ## Changes since the last version - - **Updated Output String Type:** Improved compatibility with other shells. + - **Updated Output String Type:** Ansi strings improved compatibility with other shells. - **Revamped Indicator Symbols:** Enhanced the visual aspect of the prompt. - **Removed Shell Icon:** Determining the shell is practically not possible. - **Conditional Component Inclusion:** A first step towards user-configuration expected in future versions.