aboutsummaryrefslogtreecommitdiff
path: root/src/prompt.rs
diff options
context:
space:
mode:
authorAqua-sama <aqua@iserlohn-fortress.net>2020-10-11 18:37:39 +0300
committerAqua-sama <aqua@iserlohn-fortress.net>2020-10-11 18:37:39 +0300
commitb1e25166433ce93403324a96f129712e4fac944d (patch)
tree3c168076c6699009ebc85fe1ebd3a65970853481 /src/prompt.rs
parentMake Prompt more const (diff)
downloadrshell-b1e25166433ce93403324a96f129712e4fac944d.tar.xz
Properly read username and hostname
username is read by using libc::getuid, and checking /etc/passwd for the uid and getting the username from there hostname is read from /proc/sys/kernel/hostname
Diffstat (limited to 'src/prompt.rs')
-rw-r--r--src/prompt.rs49
1 files changed, 20 insertions, 29 deletions
diff --git a/src/prompt.rs b/src/prompt.rs
index e6600b7..40c96cc 100644
--- a/src/prompt.rs
+++ b/src/prompt.rs
@@ -1,42 +1,33 @@
use std::io::Write;
+#[path = "user.rs"]
+mod user;
+
pub struct Prompt {
ps1: std::string::String,
pub home: std::path::PathBuf,
}
impl Prompt {
- pub fn new() -> Prompt {
- let username = match std::process::Command::new("whoami").output() {
- Ok(s) => {
- let output = std::string::String::from_utf8(s.stdout).unwrap();
- output.trim().to_string()
- }
- Err(e) => panic!(e),
- };
- let hostname = match std::process::Command::new("hostname").output() {
- Ok(s) => {
- let output = std::string::String::from_utf8(s.stdout).unwrap();
- output.trim().to_string()
- }
- Err(e) => panic!(e),
- };
- let ready = if username == "root" {
- "#"
- } else {
- "$"
- }.to_owned();
-
- let ps1 = String::from(" {USER}@{HOST} [{PWD}]\n\\$ ")
- .replace("{USER}", &username)
- .replace("{HOST}", &hostname)
- .replace("\\$", &ready);
- let home = match std::env::home_dir() {
- Some(p) => p,
- None => std::path::Path::new("/").to_path_buf(),
+ pub fn new() -> Result<Prompt, std::io::Error> {
+ let username = user::username()?;
+ let hostname = user::hostname()?;
+ let ready = if username == "root" { "#" } else { "$" }.to_owned();
+
+ let ps1 = match std::env::var("PS1") {
+ Ok(val) => val,
+ Err(_) => String::from(" {USER}@{HOST} [{PWD}]\n{$} "),
+ }
+ .replace("{USER}", &username)
+ .replace("{HOST}", &hostname)
+ .replace("{$}", &ready);
+
+ let home = match std::env::var("HOME") {
+ Ok(val) => std::path::Path::new(&val).to_path_buf(),
+ Err(_) => std::path::Path::new("/").to_path_buf(),
};
- Prompt { ps1, home }
+ Ok(Prompt { ps1, home })
}
pub fn print(&self, pwd: &std::path::PathBuf) {