use freedesktop_entry_parser::{ParseError, low_level};
use indexmap::map::Entry;
use indexmap::{Equivalent, IndexMap};
use std::cmp::Ordering::{Equal, Greater, Less};
use std::fmt::Write;
use tracing::warn;
use crate::widget::creator::creator_page_service::ENVIRONMENT;
use crate::widget::creator::creator_page_timer::MonotonicTimer;
pub const STANDARD_OUTPUT: &str = "StandardOutput";
pub const STANDARD_ERROR: &str = "StandardError";
#[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";
const MOUNT: &str = "Mount";
pub const ON_CALENDAR: &str = "OnCalendar";
macro_rules! get_set_str {
($section:ident, $key:ident $($suffix:ident), *) => {
paste::paste! {
pub fn [<$key:snake $($suffix),*>](&self) -> &str {
self.get_str($section, stringify!($key))
}
}
paste::paste! {
pub fn [<set_ $key:snake $($suffix),*>](&mut self, value: impl AsRef<str>) {
self.set_str($section, stringify!($key), Some(value.as_ref()));
}
}
};
}
macro_rules! get_set_bool {
($section:ident, $key:ident) => {
paste::paste! {
pub fn [< $key:snake >](&self) -> bool {
self.get_bool($section, stringify!($key))
}
}
paste::paste! {
pub fn [<set_ $key:snake>](&mut self, value: bool) {
self.set_bool($section, stringify!($key), value);
}
}
};
}
#[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 set_str(&mut self, section: &str, key: &str, value: Option<&str>) -> Option<Vec<String>> {
self.set_string(section, key, value.map(|s| s.to_owned()))
}
fn set_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_str(&mut self, section: &str, key: &str, value: &str) {
self.insert_string(section, key, value.to_owned())
}
fn insert_string(&mut self, section: &str, attribute: &str, value: String) {
if !value.trim().is_empty() {
match self.0.entry(FileEntry::new(section, attribute)) {
Entry::Occupied(mut occupied_entry) => {
occupied_entry.get_mut().push(value);
}
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(vec![value]);
}
}
}
}
fn set_bool(&mut self, section: &str, attribute: &str, value: bool) -> Option<Vec<String>> {
if value {
self.set_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))
}
get_set_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"),
}
}
get_set_bool!(TIMER, Persistent);
get_set_str!(SERVICE, WorkingDirectory);
get_set_str!(INSTALL, WantedBy);
pub fn after(&self) -> &str {
self.get_str(UNIT, "After")
}
pub fn set_after(&mut self, value: Option<glib::GString>) {
self.set_str(UNIT, "After", value.as_deref());
}
pub fn wants(&self) -> &str {
self.get_str(UNIT, "Wants")
}
pub fn set_wants(&mut self, value: Option<glib::GString>) {
self.set_str(UNIT, "Wants", value.as_deref());
}
pub fn exec_start(&self) -> &str {
self.get_str(SERVICE, "ExecStart")
}
pub fn set_exec_start(&mut self, value: impl AsRef<str>) {
self.set_str(SERVICE, "ExecStart", Some(value.as_ref()));
}
pub fn user(&self) -> &str {
self.get_str(SERVICE, "User")
}
pub fn set_user(&mut self, value: Option<impl AsRef<str>>) {
if let Some(v) = value {
self.set_str(SERVICE, "User", Some(v.as_ref()));
} else {
self.set_str(SERVICE, "User", None);
}
}
pub fn group(&self) -> &str {
self.get_str(SERVICE, "Group")
}
pub fn set_group(&mut self, value: Option<impl AsRef<str>>) {
if let Some(v) = value {
self.set_str(SERVICE, "Group", Some(v.as_ref()));
} else {
self.set_str(SERVICE, "Group", None);
}
}
pub fn cpu_quota(&self) -> &str {
self.get_str(SERVICE, "CPUQuota")
}
pub fn set_cpu_quota(&mut self, value: impl AsRef<str>) {
self.set_str(SERVICE, "CPUQuota", Some(value.as_ref()));
}
pub fn memory_high(&self) -> &str {
self.get_str(SERVICE, "MemoryHigh")
}
pub fn set_memory_high(&mut self, value: impl AsRef<str>) {
self.set_str(SERVICE, "MemoryHigh", Some(value.as_ref()));
}
fn clear(&mut self, section: &str, attribute: &str) {
if let Some(v) = self.0.get_mut(&FileEntryRef::new(section, attribute)) {
v.clear();
}
}
pub fn set_environment(&mut self, value: Option<&[impl AsRef<str>]>) {
if let Some(value) = value {
self.clear(SERVICE, ENVIRONMENT);
for v in value {
self.insert_str(SERVICE, ENVIRONMENT, v.as_ref());
}
} else {
self.remove(SERVICE, ENVIRONMENT);
}
}
pub fn environment(&self) -> Option<&Vec<String>> {
self.0.get(&FileEntryRef::new(SERVICE, ENVIRONMENT))
}
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.set_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.set_str(SERVICE, "Restart", Some(value.as_ref()));
}
pub(crate) fn restart(&self) -> &str {
self.get_str(SERVICE, "Restart")
}
pub(crate) fn standard_output(&self) -> &str {
self.get_str(SERVICE, STANDARD_OUTPUT)
}
pub fn set_standard_output(&mut self, value: glib::GString) {
self.set_str(SERVICE, STANDARD_OUTPUT, Some(value.as_str()));
}
pub(crate) fn standard_error(&self) -> &str {
self.get_str(SERVICE, STANDARD_ERROR)
}
pub fn set_standard_error(&mut self, value: glib::GString) {
self.set_str(SERVICE, STANDARD_ERROR, Some(value.as_str()));
}
get_set_str!(MOUNT, What);
get_set_str!(MOUNT, Where x);
get_set_str!(MOUNT, Options);
get_set_str!(MOUNT, Type x);
get_set_str!(MOUNT, DirectoryMode);
get_set_str!(MOUNT, TimeoutSec);
get_set_bool!(MOUNT, LazyUnmount);
get_set_bool!(MOUNT, SloppyOptions);
get_set_bool!(MOUNT, ReadWriteOnly);
get_set_bool!(MOUNT, ForceUnmount);
}
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 test_machin() {
init_logs();
}
}