starship/src/segment.rs

102 lines
2.4 KiB
Rust
Raw Normal View History

2019-04-12 21:49:20 +00:00
use ansi_term::Style;
2019-04-12 23:11:40 +00:00
#[derive(Clone)]
2019-04-12 21:49:20 +00:00
pub struct Segment {
name: Option<String>,
style: Style,
value: String,
prefix: OptionalSegment,
suffix: OptionalSegment,
}
impl Segment {
2019-04-12 22:12:29 +00:00
pub fn new<T>(name: T) -> Segment
where
T: Into<String>,
2019-04-12 23:11:40 +00:00
T: Copy,
2019-04-12 22:12:29 +00:00
{
2019-04-12 21:49:20 +00:00
let default_prefix = Some(Box::new(Segment {
name: Some(format!("{} {}", name.into(), "prefix")),
style: Style::default(),
value: String::from("via "),
prefix: None,
suffix: None,
}));
let default_suffix = Some(Box::new(Segment {
name: Some(format!("{} {}", name.into(), "suffix")),
style: Style::default(),
value: String::from(" "),
prefix: None,
suffix: None,
}));
Segment {
name: Some(name.into()),
style: Style::default(),
value: String::from(""),
prefix: default_prefix,
suffix: default_suffix,
}
}
2019-04-12 23:18:47 +00:00
pub fn set_style<T>(&mut self, style: T) -> &mut Segment
2019-04-12 22:12:29 +00:00
where
T: Into<Style>,
{
self.style = style.into();
2019-04-12 21:49:20 +00:00
self
}
2019-04-12 23:18:47 +00:00
pub fn set_value<T>(&mut self, value: T) -> &mut Segment
2019-04-12 23:11:40 +00:00
where
T: Into<String>,
{
self.value = value.into();
2019-04-12 21:49:20 +00:00
self
}
2019-04-13 03:06:48 +00:00
pub fn set_prefix(&mut self, prefix: OptionalSegment) -> &mut Segment {
self.prefix = prefix;
2019-04-12 21:49:20 +00:00
self
}
2019-04-13 03:06:48 +00:00
pub fn set_suffix(&mut self, suffix: OptionalSegment) -> &mut Segment {
self.suffix = suffix;
2019-04-12 21:49:20 +00:00
self
}
2019-04-12 23:11:40 +00:00
/// Create a string with the formatted contents of a segment
///
/// Will recursively also format the prefix and suffix of the segment being
/// stringified.
2019-04-13 03:06:48 +00:00
pub fn output(&self, index: usize) -> String {
2019-04-12 21:49:20 +00:00
let Segment {
name: _name,
prefix,
value,
style,
suffix,
} = self;
let mut segment_string = String::new();
2019-04-13 03:06:48 +00:00
// Skip the prefix for the first segment
if index != 0 {
if let Some(prefix) = prefix {
segment_string += &prefix.output(index)
}
2019-04-12 21:49:20 +00:00
}
segment_string += &style.paint(value).to_string();
if let Some(suffix) = suffix {
2019-04-13 03:06:48 +00:00
segment_string += &suffix.output(index);
2019-04-12 21:49:20 +00:00
}
segment_string
}
}
type OptionalSegment = Option<Box<Segment>>;