Add dir section with home truncation

This commit is contained in:
Matan Kushner
2019-04-04 14:18:15 -04:00
parent a81eabd690
commit 7683f33bc8
6 changed files with 304 additions and 3 deletions

View File

@@ -2,7 +2,7 @@ use super::Segment;
use ansi_term::{Color, Style};
use clap::ArgMatches;
/// Prints the prompt character
/// Creates a segment for the prompt character
///
/// The char segment prints an arrow character in a color dependant on the exit-
/// code of the last executed command:

50
src/modules/dir.rs Normal file
View File

@@ -0,0 +1,50 @@
use super::Segment;
use dirs;
use std::env;
use ansi_term::{Color, Style};
use clap::ArgMatches;
/// Creates a segment with the current directory
pub fn segment(args: &ArgMatches) -> Segment {
const COLOR_DIR: Color = Color::Cyan;
const HOME_SYMBOL: char = '~';
let current_dir = env::current_dir().unwrap();
let mut dir_string = String::from(current_dir.to_str().unwrap());
if let Some(home_dir) = dirs::home_dir() {
if current_dir.starts_with(&home_dir) {
let current_dir = current_dir.to_str().unwrap();
let home_dir = home_dir.to_str().unwrap();
dir_string = current_dir.replace(home_dir, &HOME_SYMBOL.to_string());
}
}
Segment {
value: dir_string,
style: Style::from(COLOR_DIR).bold(),
..Default::default()
}
}
// fn truncate_dir(directory: PathBuf, truncate_to: u8) {
// }
#[cfg(test)]
mod tests {
use super::*;
use clap::{App, Arg};
#[test]
fn truncate_home_dir() {
let args = App::new("starship")
.arg(Arg::with_name("status_code"))
.get_matches_from(vec!["starship", "0"]);
env::set_current_dir("~/dev/");
let segment = segment(&args);
assert_eq!(segment.style, Style::from(Color::Green));
}
}

View File

@@ -1,4 +1,5 @@
mod char;
mod dir;
use clap::ArgMatches;
use ansi_term::Style;
@@ -12,11 +13,18 @@ pub struct Segment {
impl Default for Segment {
fn default() -> Segment {
let default_suffix = Some(Box::new(Segment {
style: Style::default(),
value: String::from(" "),
prefix: None,
suffix: None
}));
Segment {
style: Style::default(),
value: String::from(""),
prefix: None,
suffix: None
suffix: default_suffix
}
}
}
@@ -24,6 +32,7 @@ impl Default for Segment {
pub fn handle(module: &str, args: &ArgMatches) -> Segment {
match module {
"char" => char::segment(&args),
"dir" => dir::segment(&args),
_ => panic!("Unknown module: {}", module),
}

View File

@@ -3,7 +3,7 @@ use crate::modules::Segment;
use clap::ArgMatches;
pub fn prompt(args: ArgMatches) {
let default_prompt = vec!["char"];
let default_prompt = vec!["dir", "char"];
for module in default_prompt {
let segment = modules::handle(module, &args);