sysd-manager 2.20.0

Application to empower user to manage their <b>systemd units</b> via Graphical User Interface. Not only are you able to make changes to the enablement and running status of each of the units, but you will also be able to view and modify their unit files and check the journal logs.
use freedesktop_entry_parser::{ParseError, low_level};
use indexmap::{Equivalent, IndexMap};
use std::cmp::Ordering::{Equal, Greater, Less};
use std::fmt::Write;
use tracing::warn;

use crate::widget::creator::timer_creator_page::MonotonicTimer;

#[derive(Debug, Eq, PartialEq, Hash)]
pub struct FileEntry {
    pub section: String,
    pub attribute: String,
}

impl FileEntry {
    fn new(section: &str, attribute: &str) -> FileEntry {
        FileEntry {
            section: section.to_string(),
            attribute: attribute.to_string(),
        }
    }
    fn new2(section: &str, attribute: String) -> FileEntry {
        FileEntry {
            section: section.to_string(),
            attribute,
        }
    }
}

#[derive(Debug, Eq, PartialEq, Hash)]
struct FileEntryRef<'a> {
    pub section: &'a str,
    pub attribute: &'a str,
}

impl<'a> FileEntryRef<'a> {
    fn new(section: &'a str, attribute: &'a str) -> FileEntryRef<'a> {
        Self { section, attribute }
    }
}

impl Equivalent<FileEntry> for FileEntryRef<'_> {
    fn equivalent(&self, key: &FileEntry) -> bool {
        self.section == key.section && self.attribute == key.attribute
    }
}

const VERSION: &str = env!("CARGO_PKG_VERSION");
const UNIT: &str = "Unit";
pub const TIMER: &str = "Timer";
const SERVICE: &str = "Service";
const INSTALL: &str = "Install";
pub const ON_CALENDAR: &str = "OnCalendar";

#[derive(Debug, Default)]
pub struct UnitFileData(IndexMap<FileEntry, Vec<String>>);

impl UnitFileData {
    pub fn new() -> Self {
        UnitFileData(IndexMap::new())
    }

    pub fn to_file(&self) -> String {
        let mut out = format!("# Generated by SysD Manager {VERSION}\n");

        let mut section = None;
        for (entry, values) in self.0.iter() {
            if Some(&entry.section) != section.as_ref() {
                write_section_header(&mut out, &entry.section);
                section = Some(entry.section.clone())
            }

            for value in values {
                out.push_str(&entry.attribute);
                out.push('=');
                out.push_str(value.as_ref());
                out.push('\n');
            }
        }
        out
    }

    pub fn from_content(data: &str) -> Option<UnitFileData> {
        Self::parse(data)
            .inspect_err(|err| warn!("Parse Error {err:?}"))
            .ok()
    }

    fn parse(input: impl AsRef<[u8]>) -> Result<UnitFileData, ParseError> {
        let mut map = UnitFileData::new();
        for section in low_level::parse_entry_str(input.as_ref()) {
            let section = section?;
            let section_name = section.title;
            for attr in section.attrs {
                let key = match attr.param {
                    Some(param) => param.attr_name,
                    None => attr.name,
                };
                let value = attr.value;
                if !value.trim_ascii().is_empty() {
                    match map.0.entry(FileEntry::new(section_name, key)) {
                        indexmap::map::Entry::Occupied(mut occupied_entry) => {
                            occupied_entry.get_mut().push(value.into());
                        }
                        indexmap::map::Entry::Vacant(vacant_entry) => {
                            vacant_entry.insert_entry(vec![value.into()]);
                        }
                    };
                }
            }
        }
        Ok(map)
    }

    fn insert_str(&mut self, section: &str, key: &str, value: Option<&str>) -> Option<Vec<String>> {
        self.insert_string(section, key, value.map(|s| s.to_owned()))
    }

    fn insert_string(
        &mut self,
        section: &str,
        attribute: &str,
        value: Option<String>,
    ) -> Option<Vec<String>> {
        if let Some(value) = value
            && !value.trim().is_empty()
        {
            self.0
                .insert(FileEntry::new(section, attribute), vec![value])
        } else {
            self.remove(section, attribute)
        }
    }

    fn insert_bool(&mut self, section: &str, attribute: &str, value: bool) -> Option<Vec<String>> {
        if value {
            self.insert_string(section, attribute, Some(value.to_string()))
        } else {
            self.remove(section, attribute)
        }
    }

    pub fn remove(&mut self, section: &str, attribute: &str) -> Option<Vec<String>> {
        self.0.shift_remove(&FileEntryRef::new(section, attribute))
    }

    fn get(&self, section: &str, attribute: &str) -> Option<&Vec<String>> {
        self.0.get(&FileEntryRef::new(section, attribute))
    }

    pub fn set_description(&mut self, description: impl AsRef<str>) {
        self.insert_str(UNIT, "Description", Some(description.as_ref()));
    }

    pub(crate) fn description(&self) -> &str {
        self.get_str(UNIT, "Description")
    }

    fn get_str(&self, section: &str, attribute: &str) -> &str {
        if let Some(vector) = self.get(section, attribute)
            && !vector.is_empty()
        {
            vector[0].as_ref()
        } else {
            ""
        }
    }

    fn get_bool(&self, section: &str, attribute: &str) -> bool {
        match self.get_str(section, attribute) {
            "true" => true,
            "" | "false" => false,
            other => other.eq_ignore_ascii_case("true"),
        }
    }

    pub fn set_persistent(&mut self, persistent: bool) {
        self.insert_bool(TIMER, "Persistent", persistent);
    }

    pub fn persistent(&self) -> bool {
        self.get_bool(TIMER, "Persistent")
    }

    pub fn working_directory(&self) -> &str {
        self.get_str(SERVICE, "WorkingDirectory")
    }

    pub fn set_working_directory(&mut self, value: impl AsRef<str>) {
        self.insert_str(SERVICE, "WorkingDirectory", Some(value.as_ref()));
    }

    pub fn exec_start(&self) -> &str {
        self.get_str(SERVICE, "ExecStart")
    }

    pub fn set_exec_start(&mut self, value: impl AsRef<str>) {
        self.insert_str(SERVICE, "ExecStart", Some(value.as_ref()));
    }

    pub fn sort(&mut self) {
        self.0.sort_by(
            |a, _, b, _| match (a.section.as_str(), b.section.as_str()) {
                (UNIT, UNIT) => Equal,
                (UNIT, _) => Less,
                (_, UNIT) => Greater,
                (INSTALL, INSTALL) => Equal,
                (INSTALL, _) => Greater,
                (_, INSTALL) => Less,
                (a, b) => a.cmp(b),
            },
        );
    }

    pub(crate) fn trigger_unit(&self) -> &str {
        self.get_str(TIMER, "Unit")
    }

    pub fn set_trigger_unit(&mut self, value: Option<impl AsRef<str>>) {
        self.insert_string(TIMER, "Unit", value.map(|s| s.as_ref().to_string()));
    }

    pub fn remove_trigger_unit(&mut self) {
        self.remove(TIMER, "Unit");
    }

    pub fn add_timers(&mut self, timers: IndexMap<String, Vec<String>>) {
        for (timer, value) in timers {
            self.0.insert(FileEntry::new2(TIMER, timer), value);
        }
    }

    pub fn timers(&self) -> impl Iterator<Item = (&FileEntry, &Vec<String>)> {
        self.0.iter().filter(|(file_entry, _)| {
            file_entry.section == TIMER
                && (file_entry.attribute.as_str() == ON_CALENDAR
                    || MonotonicTimer::get(&file_entry.attribute).is_some())
        })
    }

    pub fn set_restart(&mut self, value: impl AsRef<str>) {
        self.insert_str(SERVICE, "Restart", Some(value.as_ref()));
    }

    pub(crate) fn restart(&self) -> &str {
        self.get_str(SERVICE, "Restart")
    }
}

fn write_section_header(out: &mut String, section: &str) {
    let _ = writeln!(out, "\n[{}]", section);
}

#[cfg(test)]
mod tests {

    use test_base::init_logs;

    // #[test]
    // fn out() {
    //     init_logs();
    //     let uf = UnitFileData::default();
    //     uf.set_description("asdf");
    //     uf.set_working_directory("/tmp/test/");

    //     info!("--Out put--\n{}", uf.to_file_data());
    // }

    // #[test]
    // fn load() {
    //     init_logs();
    //     let uf = UnitFileData::default();
    //     uf.set_description(" this is a description ");
    //     uf.set_working_directory("/tmp/test/");
    //     uf.set_environment(vec!["KEY=VALUE".to_string(), "/path/to".to_string()]);

    //     let data = uf.to_file_data();
    //     info!("--Out put--\n{}", data);

    //     let uf2 = UnitFileData::from_file_data(&data);

    //     let data2 = uf2.to_file_data();
    //     info!("--Out put--\n{}", data2);
    // }

    // #[test]
    // fn convert_case() {
    //     assert_eq!(ccase!(pascal, "working_directory"), "WorkingDirectory");
    // }

    #[test]
    fn test_machin() {
        init_logs();
        // let mut map: IndexMap<FileEntry, Vec<_>> = IndexMap::new();

        // map.insert(FileEntry::new(UNIT, "Description"), vec![Cow::from("test")]);
        // map.insert(
        //     FileEntry::new(SERVICE, "ExecStart"),
        //     vec![Cow::Borrowed("/bin/run"), Cow::Borrowed("vroum")],
        // );

        // let file_content = UnitFileData::<Cow<'_, str>>::to_file(&map);

        // info!("--Out--\n{}", file_content);
    }
}