Add implementation of TemplateProcessor for Track struct to process template placeholders

This commit is contained in:
Anas Elgarhy 2023-02-20 23:53:41 +02:00
parent 2d8fc85ba5
commit cb164f962a
No known key found for this signature in database
GPG Key ID: 0501802A1D496528
2 changed files with 46 additions and 33 deletions

View File

@ -12,6 +12,10 @@ use std::str::FromStr;
use thiserror::Error;
use typed_builder::TypedBuilder;
pub trait TemplateProcessor {
fn process(&self, template: &String) -> String;
}
#[derive(Debug, PartialEq, Default, Clone)]
pub struct TrackMetadata {
tags: HashMap<String, String>,
@ -58,6 +62,44 @@ pub enum CmusError {
NoEvents,
}
impl TemplateProcessor for Track {
fn process(&self, template: &String) -> String {
#[cfg(feature = "debug")]
{
info!("Processing the template placeholders.");
debug!("Template: {template}");
debug!("Track: {self:?}");
}
let mut processed = template.clone();
let mut key = String::new(); // Just a buffer to store the key.
for c in template.chars() {
if c == '{' {
key = String::new();
} else if c == '}' {
#[cfg(feature = "debug")]
debug!("Replacing the placeholder {{{key}}} with its matching value.");
// Replace the key with their matching value if exists, if not replace with the empty string.
processed = processed.replace(
&format!("{{{}}}", key),
match key.as_str() {
"title" => self.get_name(),
_ => self.metadata.get(&key).unwrap_or(""),
},
);
} else {
key.push(c);
}
}
#[cfg(feature = "debug")]
debug!("Processed template: {processed}");
processed
}
}
impl FromStr for TrackStatus {
type Err = CmusError;

View File

@ -3,6 +3,7 @@
#[cfg(feature = "debug")]
use log::{debug, info};
use std::path::Path;
use crate::cmus::TemplateProcessor;
pub mod cmus;
pub mod notification;
@ -209,44 +210,14 @@ fn search(search_directory: &str, matcher: &regex::Regex) -> std::io::Result<Opt
}
/// Replace all the placeholders in the template with their matching value.
#[inline(always)]
pub fn process_template_placeholders(
template: &String,
track: &cmus::Track,
player_settings: &cmus::player_settings::PlayerSettings,
) -> String {
#[cfg(feature = "debug")]
{
info!("Processing the template placeholders.");
debug!("Template: {template}");
debug!("Track: {track:?}");
}
let mut processed = template.clone();
let mut key = String::new(); // Just a buffer to store the key.
for c in template.chars() {
if c == '{' {
key = String::new();
} else if c == '}' {
#[cfg(feature = "debug")]
debug!("Replacing the placeholder {{{key}}} with its matching value.");
// Replace the key with their matching value if exists, if not replace with the empty string.
processed = processed.replace(
&format!("{{{}}}", key),
match key.as_str() {
"title" => track.get_name(),
_ => track.metadata.get(&key).unwrap_or(""),
},
);
} else {
key.push(c);
}
}
#[cfg(feature = "debug")]
debug!("Processed template: {processed}");
processed
let res = track.process(template);
player_settings.process(&res)
}
#[cfg(test)]