use std::process::{Command, Stdio};
use crate::utils::{system::extract_stdout, Pair};
fn clean_text(string: &String) -> String {
let mut result = string.clone();
while result.find("\n\n").is_some() {
result = result.replace("\n\n", "\n");
}
result
}
fn format_keyword_definition(keyword: &Pair<String, String>) -> String {
format!("keyword {} {}", keyword.first(), keyword.second())
}
pub fn apply_keywords_to_config(
keywords: Vec<Pair<String, String>>,
) -> Result<(), String> {
let mut hyprctl = Command::new("hyprctl");
let batch = keywords
.iter()
.map(format_keyword_definition)
.collect::<Vec<String>>()
.join(" ; ");
let capture_mode = Stdio::piped;
let result = hyprctl
.arg("--batch")
.arg(batch)
.stdout(capture_mode())
.stderr(capture_mode())
.output();
match result {
Ok(output) => {
let stdout = extract_stdout(&output)?;
let cleaned_stdout = clean_text(&stdout);
let good_line = "ok";
let erronous_lines: Vec<&str> = cleaned_stdout
.split("\n")
.into_iter()
.filter(|line| !line.is_empty() && line != &good_line)
.collect();
match erronous_lines.len() {
0 => Ok(()),
_ => Err(erronous_lines.join("\n")),
}
}
Err(error) => Err(error.to_string()),
}
}