feat: Implement the prompt module for username (#56)

This commit is contained in:
Youssef Habri
2019-05-20 02:26:12 +00:00
committed by Matan Kushner
parent a213114e9a
commit 08b238114e
6 changed files with 66 additions and 9 deletions
+2
View File
@@ -40,6 +40,8 @@ pub fn segment(context: &Context) -> Option<Module> {
let truncated_dir_string = truncate(dir_string, DIR_TRUNCATION_LENGTH);
module.new_segment("path", truncated_dir_string);
module.get_prefix().set_value("in ");
Some(module)
}
+2
View File
@@ -8,6 +8,7 @@ mod nodejs;
mod package;
mod python;
mod rust;
mod username;
use crate::context::Context;
use crate::module::Module;
@@ -24,6 +25,7 @@ pub fn handle(module: &str, context: &Context) -> Option<Module> {
"package" => package::segment(context),
"git_branch" => git_branch::segment(context),
"git_status" => git_status::segment(context),
"username" => username::segment(context),
_ => panic!("Unknown module: {}", module),
}
+49
View File
@@ -0,0 +1,49 @@
use ansi_term::{Color, Style};
use std::env;
use std::process::Command;
use super::{Context, Module};
/// Creates a segment with the current user's username
///
/// Will display the usename if any of the following criteria are met:
/// - The current user isn't the same as the one that is logged in ($LOGNAME != $USER)
/// - The current user is root (UID = 0)
/// - The user is currently connected as an SSH session ($SSH_CONNECTION)
pub fn segment(_context: &Context) -> Option<Module> {
let user = env::var("USER").ok();
let logname = env::var("LOGNAME").ok();
let ssh_connection = env::var("SSH_CONNECTION").ok();
let mut module_color = Color::Yellow.bold();
if user != logname || ssh_connection.is_some() || is_root(&mut module_color) {
let mut module = Module::new("username");
module.set_style(module_color);
module.new_segment("username", user?);
return Some(module);
}
None
}
fn get_uid() -> Option<u32> {
match Command::new("id").arg("-u").output() {
Ok(output) => String::from_utf8(output.stdout)
.map(|uid| uid.trim().parse::<u32>().ok())
.ok()?,
Err(_) => None,
}
}
fn is_root(style: &mut Style) -> bool {
match get_uid() {
Some(uid) if uid == 0 => {
style.clone_from(&Color::Red.bold());
true
}
_ => false,
}
}
+1
View File
@@ -8,6 +8,7 @@ use crate::modules;
pub fn prompt(args: ArgMatches) {
let prompt_order = vec![
"username",
"directory",
"git_branch",
"git_status",