use anyhow::Result;
use super::core::GuardyConfig;
#[derive(Debug, Clone)]
pub enum ConfigFormat {
Json,
Toml,
Yaml,
}
impl GuardyConfig {
pub fn export_config(&self, format: ConfigFormat) -> Result<String> {
let output = match format {
ConfigFormat::Json => serde_json::to_string_pretty(self)?,
ConfigFormat::Toml => toml::to_string_pretty(self)?,
ConfigFormat::Yaml => serde_yaml_ng::to_string(self)?,
};
Ok(output)
}
pub fn export_config_highlighted(&self, format: ConfigFormat) -> Result<String> {
use syntect::{
easy::HighlightLines,
highlighting::Style,
util::{LinesWithEndings, as_24_bit_terminal_escaped},
};
use two_face::{syntax, theme};
let output = self.export_config(format.clone())?;
if !is_terminal::IsTerminal::is_terminal(&std::io::stdout()) {
return Ok(output);
}
let ps = syntax::extra_newlines();
let ts = theme::extra();
let syntax = match format {
ConfigFormat::Json => ps
.find_syntax_by_extension("json")
.unwrap_or_else(|| ps.find_syntax_plain_text()),
ConfigFormat::Toml => ps
.find_syntax_by_extension("toml")
.unwrap_or_else(|| ps.find_syntax_plain_text()),
ConfigFormat::Yaml => ps
.find_syntax_by_extension("yaml")
.unwrap_or_else(|| ps.find_syntax_plain_text()),
};
use two_face::theme::EmbeddedThemeName;
let theme = ts.get(EmbeddedThemeName::Base16OceanDark);
let mut h = HighlightLines::new(syntax, theme);
let mut highlighted = String::new();
for line in LinesWithEndings::from(&output) {
let ranges: Vec<(Style, &str)> = h.highlight_line(line, &ps)?;
let escaped = as_24_bit_terminal_escaped(&ranges[..], false);
highlighted.push_str(&escaped);
}
Ok(highlighted)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::CONFIG;
#[test]
fn test_config_export_formats() {
let json_output = CONFIG.export_config(ConfigFormat::Json);
assert!(json_output.is_ok());
assert!(json_output.unwrap().contains("{"));
let toml_output = CONFIG.export_config(ConfigFormat::Toml);
assert!(toml_output.is_ok());
let yaml_output = CONFIG.export_config(ConfigFormat::Yaml);
assert!(yaml_output.is_ok());
}
#[test]
fn test_syntax_highlighting() {
let highlighted = CONFIG.export_config_highlighted(ConfigFormat::Json);
assert!(highlighted.is_ok());
}
}