sysd-manager 2.20.10

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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::service_creator_page::ENVIRONMENT;
use crate::widget::creator::timer_creator_page::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";
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 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))
    }

    pub fn set_description(&mut self, description: impl AsRef<str>) {
        self.set_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.set_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.set_str(SERVICE, "WorkingDirectory", Some(value.as_ref()));
    }

    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()));
    }
}

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);
    }
}