From 55f75215607962def4cf83d2c27b2899dce24881 Mon Sep 17 00:00:00 2001 From: Aqua-sama Date: Tue, 13 Oct 2020 22:59:23 +0300 Subject: Use crates.io/rustyline as readline --- src/prompt/user.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/prompt/user.rs (limited to 'src/prompt/user.rs') diff --git a/src/prompt/user.rs b/src/prompt/user.rs new file mode 100644 index 0000000..9744928 --- /dev/null +++ b/src/prompt/user.rs @@ -0,0 +1,48 @@ +use std::io::BufRead; + +pub fn hostname() -> std::result::Result { + let h = std::fs::read_to_string("/proc/sys/kernel/hostname")?; + Ok(h.trim().to_string()) +} + +#[test] +fn test_hostname() { + 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), + }; + + assert_eq!(hostname__, hostname().unwrap()); +} + +pub fn username() -> std::result::Result { + let uid = unsafe { libc::getuid().to_string() }; + + let file = std::fs::File::open("/etc/passwd")?; + let reader = std::io::BufReader::new(file); + + for line in reader.lines() { + let l = line?; + let parts: Vec<&str> = l.split(':').collect(); + if uid == parts[2] { + return Ok(parts[0].to_string()); + } + } + + Ok(uid) +} + +#[test] +fn test_username() { + 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), + }; + assert_eq!(username__, username().unwrap()); +} -- cgit v1.2.1