#[cfg(feature = "clap")]
use clap::ValueEnum;
#[derive(Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "clap", derive(ValueEnum))]
pub enum TreeStyle {
#[default]
Unicode,
Ascii,
Box,
#[cfg_attr(feature = "clap", value(skip))]
Custom {
branch: String,
last: String,
vertical: String,
empty: String,
},
}
impl TreeStyle {
#[inline]
pub fn unicode() -> StyleConfig {
StyleConfig {
branch: " ├─".to_string(),
last: " └─".to_string(),
vertical: " │ ".to_string(),
empty: " ".to_string(),
}
}
#[inline]
pub fn ascii() -> StyleConfig {
StyleConfig {
branch: " +-".to_string(),
last: " `-".to_string(),
vertical: " | ".to_string(),
empty: " ".to_string(),
}
}
#[inline]
pub fn box_drawing() -> StyleConfig {
StyleConfig {
branch: " ├─".to_string(),
last: " └─".to_string(),
vertical: " │ ".to_string(),
empty: " ".to_string(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StyleConfig {
pub branch: String,
pub last: String,
pub vertical: String,
pub empty: String,
}
impl Default for StyleConfig {
fn default() -> Self {
TreeStyle::unicode()
}
}
impl From<TreeStyle> for StyleConfig {
fn from(style: TreeStyle) -> Self {
match style {
TreeStyle::Unicode => TreeStyle::unicode(),
TreeStyle::Ascii => TreeStyle::ascii(),
TreeStyle::Box => TreeStyle::box_drawing(),
TreeStyle::Custom {
branch,
last,
vertical,
empty,
} => StyleConfig {
branch,
last,
vertical,
empty,
},
}
}
}
impl StyleConfig {
pub fn custom(
branch: impl Into<String>,
last: impl Into<String>,
vertical: impl Into<String>,
empty: impl Into<String>,
) -> Self {
StyleConfig {
branch: branch.into(),
last: last.into(),
vertical: vertical.into(),
empty: empty.into(),
}
}
#[inline]
pub fn get_branch(&self, is_last: bool) -> &str {
if is_last { &self.last } else { &self.branch }
}
#[inline]
pub fn get_vertical(&self) -> &str {
&self.vertical
}
#[inline]
pub fn get_empty(&self) -> &str {
&self.empty
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_style() {
let config = StyleConfig::default();
assert_eq!(config.branch, " ├─");
assert_eq!(config.last, " └─");
}
#[test]
fn test_unicode_style() {
let config = TreeStyle::unicode();
assert_eq!(config.branch, " ├─");
assert_eq!(config.last, " └─");
}
#[test]
fn test_ascii_style() {
let config = TreeStyle::ascii();
assert_eq!(config.branch, " +-");
assert_eq!(config.last, " `-");
}
#[test]
fn test_custom_style() {
let config = StyleConfig::custom(">", "<", "|", " ");
assert_eq!(config.branch, ">");
assert_eq!(config.last, "<");
}
#[test]
fn test_get_branch() {
let config = StyleConfig::default();
assert_eq!(config.get_branch(false), " ├─");
assert_eq!(config.get_branch(true), " └─");
}
}