chore: remove unused name from Segment and remove some of the misleading underscores (#1584)

* chore: Remove unused name from Segment and remove some of the misleading underscores

* chore: Access members of `Segment` directly
This commit is contained in:
Tilmann Meyer 2020-08-16 19:16:05 -07:00 committed by GitHub
parent 2e14d1af5a
commit bcdf522af5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 57 additions and 113 deletions

View File

@ -7,50 +7,50 @@ use super::model::*;
#[grammar = "formatter/spec.pest"] #[grammar = "formatter/spec.pest"]
struct IdentParser; struct IdentParser;
fn _parse_value(value: Pair<Rule>) -> FormatElement { fn parse_value(value: Pair<Rule>) -> FormatElement {
match value.as_rule() { match value.as_rule() {
Rule::text => FormatElement::Text(_parse_text(value).into()), Rule::text => FormatElement::Text(parse_text(value).into()),
Rule::variable => FormatElement::Variable(_parse_variable(value).into()), Rule::variable => FormatElement::Variable(parse_variable(value).into()),
Rule::textgroup => FormatElement::TextGroup(_parse_textgroup(value)), Rule::textgroup => FormatElement::TextGroup(parse_textgroup(value)),
Rule::conditional => { Rule::conditional => {
FormatElement::Conditional(_parse_format(value.into_inner().next().unwrap())) FormatElement::Conditional(parse_format(value.into_inner().next().unwrap()))
} }
_ => unreachable!(), _ => unreachable!(),
} }
} }
fn _parse_textgroup(textgroup: Pair<Rule>) -> TextGroup { fn parse_textgroup(textgroup: Pair<Rule>) -> TextGroup {
let mut inner_rules = textgroup.into_inner(); let mut inner_rules = textgroup.into_inner();
let format = inner_rules.next().unwrap(); let format = inner_rules.next().unwrap();
let style = inner_rules.next().unwrap(); let style = inner_rules.next().unwrap();
TextGroup { TextGroup {
format: _parse_format(format), format: parse_format(format),
style: _parse_style(style), style: parse_style(style),
} }
} }
fn _parse_variable(variable: Pair<Rule>) -> &str { fn parse_variable(variable: Pair<Rule>) -> &str {
variable.into_inner().next().unwrap().as_str() variable.into_inner().next().unwrap().as_str()
} }
fn _parse_text(text: Pair<Rule>) -> String { fn parse_text(text: Pair<Rule>) -> String {
text.into_inner() text.into_inner()
.map(|pair| pair.as_str().chars()) .map(|pair| pair.as_str().chars())
.flatten() .flatten()
.collect() .collect()
} }
fn _parse_format(format: Pair<Rule>) -> Vec<FormatElement> { fn parse_format(format: Pair<Rule>) -> Vec<FormatElement> {
format.into_inner().map(_parse_value).collect() format.into_inner().map(parse_value).collect()
} }
fn _parse_style(style: Pair<Rule>) -> Vec<StyleElement> { fn parse_style(style: Pair<Rule>) -> Vec<StyleElement> {
style style
.into_inner() .into_inner()
.map(|pair| match pair.as_rule() { .map(|pair| match pair.as_rule() {
Rule::string => StyleElement::Text(pair.as_str().into()), Rule::string => StyleElement::Text(pair.as_str().into()),
Rule::variable => StyleElement::Variable(_parse_variable(pair).into()), Rule::variable => StyleElement::Variable(parse_variable(pair).into()),
_ => unreachable!(), _ => unreachable!(),
}) })
.collect() .collect()
@ -60,7 +60,7 @@ pub fn parse(format: &str) -> Result<Vec<FormatElement>, Error<Rule>> {
IdentParser::parse(Rule::expression, format).map(|pairs| { IdentParser::parse(Rule::expression, format).map(|pairs| {
pairs pairs
.take_while(|pair| pair.as_rule() != Rule::EOI) .take_while(|pair| pair.as_rule() != Rule::EOI)
.map(_parse_value) .map(parse_value)
.collect() .collect()
}) })
} }

View File

@ -204,13 +204,13 @@ impl<'a> StringFormatter<'a> {
/// - Format string in meta variables fails to parse /// - Format string in meta variables fails to parse
/// - Variable mapper returns an error. /// - Variable mapper returns an error.
pub fn parse(self, default_style: Option<Style>) -> Result<Vec<Segment>, StringFormatterError> { pub fn parse(self, default_style: Option<Style>) -> Result<Vec<Segment>, StringFormatterError> {
fn _parse_textgroup<'a>( fn parse_textgroup<'a>(
textgroup: TextGroup<'a>, textgroup: TextGroup<'a>,
variables: &'a VariableMapType<'a>, variables: &'a VariableMapType<'a>,
style_variables: &'a StyleVariableMapType<'a>, style_variables: &'a StyleVariableMapType<'a>,
) -> Result<Vec<Segment>, StringFormatterError> { ) -> Result<Vec<Segment>, StringFormatterError> {
let style = _parse_style(textgroup.style, style_variables); let style = parse_style(textgroup.style, style_variables);
_parse_format( parse_format(
textgroup.format, textgroup.format,
style.transpose()?, style.transpose()?,
&variables, &variables,
@ -218,7 +218,7 @@ impl<'a> StringFormatter<'a> {
) )
} }
fn _parse_style<'a>( fn parse_style<'a>(
style: Vec<StyleElement>, style: Vec<StyleElement>,
variables: &'a StyleVariableMapType<'a>, variables: &'a StyleVariableMapType<'a>,
) -> Option<Result<Style, StringFormatterError>> { ) -> Option<Result<Style, StringFormatterError>> {
@ -244,7 +244,7 @@ impl<'a> StringFormatter<'a> {
.transpose() .transpose()
} }
fn _parse_format<'a>( fn parse_format<'a>(
format: Vec<FormatElement<'a>>, format: Vec<FormatElement<'a>>,
style: Option<Style>, style: Option<Style>,
variables: &'a VariableMapType<'a>, variables: &'a VariableMapType<'a>,
@ -254,13 +254,13 @@ impl<'a> StringFormatter<'a> {
.into_iter() .into_iter()
.map(|el| { .map(|el| {
match el { match el {
FormatElement::Text(text) => Ok(vec![_new_segment("_text", text, style)]), FormatElement::Text(text) => Ok(vec![Segment::new(style, text)]),
FormatElement::TextGroup(textgroup) => { FormatElement::TextGroup(textgroup) => {
let textgroup = TextGroup { let textgroup = TextGroup {
format: textgroup.format, format: textgroup.format,
style: textgroup.style, style: textgroup.style,
}; };
_parse_textgroup(textgroup, &variables, &style_variables) parse_textgroup(textgroup, &variables, &style_variables)
} }
FormatElement::Variable(name) => variables FormatElement::Variable(name) => variables
.get(name.as_ref()) .get(name.as_ref())
@ -271,21 +271,17 @@ impl<'a> StringFormatter<'a> {
.into_iter() .into_iter()
.map(|mut segment| { .map(|mut segment| {
// Derive upper style if the style of segments are none. // Derive upper style if the style of segments are none.
if !segment.has_style() { if segment.style.is_none() {
if let Some(style) = style { segment.style = style;
segment.set_style(style); };
}
}
segment segment
}) })
.collect()), .collect()),
VariableValue::Plain(text) => { VariableValue::Plain(text) => Ok(vec![Segment::new(style, text)]),
Ok(vec![_new_segment(name, text, style)])
}
VariableValue::Meta(format) => { VariableValue::Meta(format) => {
let formatter = StringFormatter { let formatter = StringFormatter {
format, format,
variables: _clone_without_meta(variables), variables: clone_without_meta(variables),
style_variables: style_variables.clone(), style_variables: style_variables.clone(),
}; };
formatter.parse(style) formatter.parse(style)
@ -295,7 +291,7 @@ impl<'a> StringFormatter<'a> {
FormatElement::Conditional(format) => { FormatElement::Conditional(format) => {
// Show the conditional format string if all the variables inside are not // Show the conditional format string if all the variables inside are not
// none. // none.
fn _should_show_elements<'a>( fn should_show_elements<'a>(
format_elements: &[FormatElement], format_elements: &[FormatElement],
variables: &'a VariableMapType<'a>, variables: &'a VariableMapType<'a>,
) -> bool { ) -> bool {
@ -311,8 +307,8 @@ impl<'a> StringFormatter<'a> {
// check the format string inside it. // check the format string inside it.
VariableValue::Meta(meta_elements) => { VariableValue::Meta(meta_elements) => {
let meta_variables = let meta_variables =
_clone_without_meta(variables); clone_without_meta(variables);
_should_show_elements( should_show_elements(
&meta_elements, &meta_elements,
&meta_variables, &meta_variables,
) )
@ -328,10 +324,10 @@ impl<'a> StringFormatter<'a> {
}) })
} }
let should_show: bool = _should_show_elements(&format, variables); let should_show: bool = should_show_elements(&format, variables);
if should_show { if should_show {
_parse_format(format, style, variables, style_variables) parse_format(format, style, variables, style_variables)
} else { } else {
Ok(Vec::new()) Ok(Vec::new())
} }
@ -342,7 +338,7 @@ impl<'a> StringFormatter<'a> {
Ok(results?.into_iter().flatten().collect()) Ok(results?.into_iter().flatten().collect())
} }
_parse_format( parse_format(
self.format, self.format,
default_style, default_style,
&self.variables, &self.variables,
@ -363,20 +359,7 @@ impl<'a> StyleVariableHolder<String> for StringFormatter<'a> {
} }
} }
/// Helper function to create a new segment fn clone_without_meta<'a>(variables: &VariableMapType<'a>) -> VariableMapType<'a> {
fn _new_segment(
name: impl Into<String>,
value: impl Into<String>,
style: Option<Style>,
) -> Segment {
Segment {
_name: name.into(),
value: value.into(),
style,
}
}
fn _clone_without_meta<'a>(variables: &VariableMapType<'a>) -> VariableMapType<'a> {
VariableMapType::from_iter(variables.iter().map(|(key, value)| { VariableMapType::from_iter(variables.iter().map(|(key, value)| {
let value = match value { let value = match value {
Some(Ok(value)) => match value { Some(Ok(value)) => match value {
@ -523,13 +506,9 @@ mod tests {
.unwrap() .unwrap()
.map_variables_to_segments(|variable| match variable { .map_variables_to_segments(|variable| match variable {
"var" => Some(Ok(vec![ "var" => Some(Ok(vec![
_new_segment("_1".to_owned(), "styless".to_owned(), None), Segment::new(None, "styless"),
_new_segment("_2".to_owned(), "styled".to_owned(), styled_style), Segment::new(styled_style, "styled"),
_new_segment( Segment::new(styled_no_modifier_style, "styled_no_modifier"),
"_3".to_owned(),
"styled_no_modifier".to_owned(),
styled_no_modifier_style,
),
])), ])),
_ => None, _ => None,
}); });

View File

@ -66,7 +66,7 @@ pub struct Module<'a> {
pub config: Option<&'a toml::Value>, pub config: Option<&'a toml::Value>,
/// The module's name, to be used in configuration and logging. /// The module's name, to be used in configuration and logging.
_name: String, name: String,
/// The module's description /// The module's description
description: String, description: String,
@ -80,7 +80,7 @@ impl<'a> Module<'a> {
pub fn new(name: &str, desc: &str, config: Option<&'a toml::Value>) -> Module<'a> { pub fn new(name: &str, desc: &str, config: Option<&'a toml::Value>) -> Module<'a> {
Module { Module {
config, config,
_name: name.to_string(), name: name.to_string(),
description: desc.to_string(), description: desc.to_string(),
segments: Vec::new(), segments: Vec::new(),
} }
@ -93,7 +93,7 @@ impl<'a> Module<'a> {
/// Get module's name /// Get module's name
pub fn get_name(&self) -> &String { pub fn get_name(&self) -> &String {
&self._name &self.name
} }
/// Get module's description /// Get module's description
@ -103,12 +103,17 @@ impl<'a> Module<'a> {
/// Whether a module has non-empty segments /// Whether a module has non-empty segments
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.segments.iter().all(|segment| segment.is_empty()) self.segments
.iter()
.all(|segment| segment.value.trim().is_empty())
} }
/// Get values of the module's segments /// Get values of the module's segments
pub fn get_segments(&self) -> Vec<&str> { pub fn get_segments(&self) -> Vec<&str> {
self.segments.iter().map(Segment::get_value).collect() self.segments
.iter()
.map(|segment| segment.value.as_str())
.collect()
} }
/// Returns a vector of colored ANSIString elements to be later used with /// Returns a vector of colored ANSIString elements to be later used with
@ -159,7 +164,7 @@ mod tests {
let desc = "This is a unit test"; let desc = "This is a unit test";
let module = Module { let module = Module {
config: None, config: None,
_name: name.to_string(), name: name.to_string(),
description: desc.to_string(), description: desc.to_string(),
segments: Vec::new(), segments: Vec::new(),
}; };
@ -173,9 +178,9 @@ mod tests {
let desc = "This is a unit test"; let desc = "This is a unit test";
let module = Module { let module = Module {
config: None, config: None,
_name: name.to_string(), name: name.to_string(),
description: desc.to_string(), description: desc.to_string(),
segments: vec![Segment::new("test_segment")], segments: vec![Segment::new(None, "")],
}; };
assert!(module.is_empty()); assert!(module.is_empty());

View File

@ -7,11 +7,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("line_break"); let mut module = context.new_module("line_break");
module.set_segments(vec![Segment { module.set_segments(vec![Segment::new(None, LINE_ENDING)]);
_name: "line_break".to_string(),
style: None,
value: LINE_ENDING.to_string(),
}]);
Some(module) Some(module)
} }

View File

@ -6,9 +6,6 @@ use std::fmt;
/// (e.g. The version that software is running). /// (e.g. The version that software is running).
#[derive(Clone)] #[derive(Clone)]
pub struct Segment { pub struct Segment {
/// The segment's name, to be used in configuration and logging.
pub _name: String,
/// The segment's style. If None, will inherit the style of the module containing it. /// The segment's style. If None, will inherit the style of the module containing it.
pub style: Option<Style>, pub style: Option<Style>,
@ -17,43 +14,15 @@ pub struct Segment {
} }
impl Segment { impl Segment {
/// Creates a new segment with default fields. /// Creates a new segment.
pub fn new(name: &str) -> Self { pub fn new<T>(style: Option<Style>, value: T) -> Self
Self {
_name: name.to_string(),
style: None,
value: "".to_string(),
}
}
/// Sets the style of the segment.
///
/// Accepts either `Color` or `Style`.
pub fn set_style<T>(&mut self, style: T) -> &mut Self
where
T: Into<Style>,
{
self.style = Some(style.into());
self
}
/// Check if the segment has a style
pub fn has_style(&self) -> bool {
self.style.is_some()
}
/// Sets the value of the segment.
pub fn set_value<T>(&mut self, value: T) -> &mut Self
where where
T: Into<String>, T: Into<String>,
{ {
self.value = value.into(); Self {
self style,
value: value.into(),
} }
/// Gets the value of the segment.
pub fn get_value(&self) -> &str {
&self.value
} }
// Returns the ANSIString of the segment value, not including its prefix and suffix // Returns the ANSIString of the segment value, not including its prefix and suffix
@ -63,11 +32,6 @@ impl Segment {
None => ANSIString::from(&self.value), None => ANSIString::from(&self.value),
} }
} }
/// Determines if the segment contains a value.
pub fn is_empty(&self) -> bool {
self.value.trim().is_empty()
}
} }
impl fmt::Display for Segment { impl fmt::Display for Segment {