Skip to content

Commit

Permalink
feat: add template formatting for hook (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
InioX committed Jun 29, 2024
1 parent d9dfc56 commit e1117d6
Show file tree
Hide file tree
Showing 7 changed files with 175 additions and 88 deletions.
53 changes: 53 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,4 @@ serde_json = "1.0.107"
toml = "0.8.8"
material-colors = { version = "0.3.2", features = ["image"] }
regex = "1.10.5"
execute = "0.2.13"
3 changes: 1 addition & 2 deletions example/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ swww_options = [
"--transition-type",
"center",
]
default_value = "-"

[config.custom_keywords]
test = "aaaa"
Expand All @@ -31,7 +30,7 @@ colors_to_compare = [
{ name = "purple", color = "#800080" },
]
compare_to = "#aefbd5"
hook = "source color {source_color}, source image {source_image}, compared color {compared_color}"
hook = 'echo "source color {{colors.source_color.default.hex}}, source image {{image}}, compared color {{compared_color}}"'

[config.custom_colors]
green = "#00FF00"
Expand Down
1 change: 0 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,6 @@ fn main() -> Result<(), Report> {
&default_scheme,
&config.config.custom_keywords,
&args.prefix,
&config.config.default_value,
)?;

if config.config.reload_apps == Some(true) {
Expand Down
1 change: 0 additions & 1 deletion src/util/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ pub struct Config {
pub prefix: Option<String>,
pub custom_keywords: Option<HashMap<String, String>>,
pub custom_colors: Option<HashMap<String, CustomColor>>,
pub default_value: Option<String>
}

#[derive(Deserialize, Serialize, Debug)]
Expand Down
57 changes: 37 additions & 20 deletions src/util/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@ use upon::Value;
use crate::util::color;
use crate::util::color::color_to_string;
use crate::util::filters::set_lightness;
use crate::util::variables::replace_hook_keywords;
use crate::util::variables::format_hook_text;

use std::str;

use std::process::{Command, Stdio};

use execute::{Execute, shell};

use std::collections::HashMap;
use std::fs::create_dir_all;
use std::fs::read_to_string;
Expand Down Expand Up @@ -110,7 +114,6 @@ impl Template {
default_scheme: &SchemesEnum,
custom_keywords: &Option<HashMap<String, String>>,
path_prefix: &Option<PathBuf>,
default_fill_value: &Option<String>,
) -> Result<(), Report> {
let default_prefix = "@".to_string();

Expand Down Expand Up @@ -147,13 +150,12 @@ impl Template {
}
}

let render_data = upon::value! {
let mut render_data = upon::value! {
colors: &colors, image: image, custom: &custom,
};

let fill = String::from("-");
let default_fill_value = default_fill_value.as_ref().unwrap_or(&fill);


// let default_fill_value = String::from("-");
// debug!("render_data: {:#?}", &render_data);

for (i, (name, template)) in templates.iter().enumerate() {
Expand All @@ -171,21 +173,36 @@ impl Template {
None
};

let parsed = replace_hook_keywords(
&template.hook.as_ref().unwrap(),
&default_fill_value,
image,
compared_color.as_ref(),
source_color,
);
println!("{}", parsed);
}
// let parsed = replace_hook_keywords(
// &template.hook.as_ref().unwrap(),
// &default_fill_value,
// image,
// compared_color.as_ref(),
// source_color,
// );

if template.colors_to_compare.is_some() && template.compare_to.is_some() {
color::color_to_string(
&template.colors_to_compare.as_ref().unwrap(),
&template.compare_to.as_ref().unwrap(),
);
let t = engine.compile(template.hook.as_ref().unwrap())?;
let res = format_hook_text(&mut render_data, compared_color.as_ref(), t);
let mut command = shell(&res);

if template.colors_to_compare.is_some() && template.compare_to.is_some() {
color::color_to_string(
&template.colors_to_compare.as_ref().unwrap(),
&template.compare_to.as_ref().unwrap(),
);
command.stdout(Stdio::inherit());

let output = command.execute_output()?;


if let Some(exit_code) = output.status.code() {
if exit_code != 0 {
error!("Failed executing command: {:?}", &res)
}
} else {
eprintln!("Interrupted!");
}
}
}

if !input_path_absolute.exists() {
Expand Down
147 changes: 83 additions & 64 deletions src/util/variables.rs
Original file line number Diff line number Diff line change
@@ -1,76 +1,95 @@
use material_colors::color::Argb;
use regex::{Captures, Regex};
use upon::Engine;
use upon::{Engine, Syntax, Template, Value};

use super::color::{format_hex, rgb_from_argb};
// use regex::{Captures, Regex};
// use material_colors::color::Argb;
// use super::color::{format_hex, rgb_from_argb};

pub enum Variables {
Invalid,
ComparedColor,
SourceImage,
SourceColor,
}
// pub enum Variables {
// Invalid,
// ComparedColor,
// SourceImage,
// SourceColor,
// }

impl Variables {
fn from(mut input: &str) -> Self {
if input.starts_with("{") && input.ends_with("}") {
input = input.remove_first_char().remove_last_char();
}
// impl Variables {
// fn from(mut input: &str) -> Self {
// if input.starts_with("{") && input.ends_with("}") {
// input = input.remove_first_char().remove_last_char();
// }

match input {
"compared_color" => Variables::ComparedColor,
"source_image" => Variables::SourceImage,
"source_color" => Variables::SourceColor,
_ => {
error!("Invalid variable: {{{}}}", input);
Variables::Invalid
}
}
}
}
// match input {
// "compared_color" => Variables::ComparedColor,
// "source_image" => Variables::SourceImage,
// "source_color" => Variables::SourceColor,
// _ => {
// error!("Invalid variable: {{{}}}", input);
// Variables::Invalid
// }
// }
// }
// }

trait StrExt {
fn remove_last_char(&self) -> &str;
fn remove_first_char(&self) -> &str;
}
// trait StrExt {
// fn remove_last_char(&self) -> &str;
// fn remove_first_char(&self) -> &str;
// }

impl StrExt for str {
fn remove_last_char(&self) -> &str {
match self.char_indices().next_back() {
Some((i, _)) => &self[..i],
None => self,
}
}
fn remove_first_char(&self) -> &str {
self.chars()
.next()
.map(|c| &self[c.len_utf8()..])
.unwrap_or("")
}
}
// impl StrExt for str {
// fn remove_last_char(&self) -> &str {
// match self.char_indices().next_back() {
// Some((i, _)) => &self[..i],
// None => self,
// }
// }
// fn remove_first_char(&self) -> &str {
// self.chars()
// .next()
// .map(|c| &self[c.len_utf8()..])
// .unwrap_or("")
// }
// }

// pub fn replace_hook_keywords(
// input: &str,
// default_value: &String,
// src_img: Option<&String>,
// compared_color: Option<&String>,
// source_color: &Argb,
// ) -> String {
// let re = Regex::new(r"\{.*?\}").unwrap();

// let source_formatted = format_hex(&rgb_from_argb(*source_color));

pub fn replace_hook_keywords(
input: &str,
default_value: &String,
src_img: Option<&String>,
compared_color: Option<&String>,
source_color: &Argb,
) -> String {
let re = Regex::new(r"\{.*?\}").unwrap();
// let result = re.replace_all(input, |cap: &Captures| {
// match Variables::from(&cap[0]) {
// Variables::Invalid => &cap[0],
// Variables::ComparedColor => compared_color.unwrap_or(default_value),
// Variables::SourceImage => src_img.unwrap_or(default_value),
// Variables::SourceColor => &source_formatted,
// }
// .to_string()
// });

let source_formatted = format_hex(&rgb_from_argb(*source_color));
// return result.to_string();
// }

let result = re.replace_all(input, |cap: &Captures| {
match Variables::from(&cap[0]) {
Variables::Invalid => &cap[0],
Variables::ComparedColor => compared_color.unwrap_or(default_value),
Variables::SourceImage => src_img.unwrap_or(default_value),
Variables::SourceColor => &source_formatted,
pub fn format_hook_text(render_data: &mut Value, compared_color: Option<&String>, template: Template<'_>) -> String {
let syntax = Syntax::builder().expr("{{", "}}").block("<*", "*>").build();
let mut engine = Engine::with_syntax(syntax);
match render_data {
Value::Map(ref mut map) => {
if compared_color.is_some() {
map.insert("compared_color".to_string(), Value::from(compared_color.unwrap().as_str()));
}
},
_ => {
println!("not")
}
.to_string()
});
}

return result.to_string();
}
let data = template
.render(&engine,&render_data)
.to_string().unwrap();

pub fn format_hook_text(mut engine: Engine) {}
return data
}

0 comments on commit e1117d6

Please sign in to comment.