user_startup/utils/
linux.rs

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
//! use systemd to manage startup.

use std::{path::PathBuf, sync::LazyLock as Lazy};

pub static CONFIG_PATH: Lazy<PathBuf> = Lazy::new(|| {
    dirs::home_dir()
        .expect("Could not find home directory")
        .join(".config")
        .join("systemd")
        .join("user")
});

pub const COMMENT_PREFIX: &str = "# ";

pub fn comment(s: &str) -> String {
    format!("{}{}", COMMENT_PREFIX, s)
}

pub const OPEN_COMMAND: &str = "xdg-open";

pub const FILE_EXT: &str = ".service";

pub fn format(cmd: &str, name: Option<&str>, stdout: Option<&str>, stderr: Option<&str>) -> String {
    let name = name.unwrap_or_else(|| cmd.split_whitespace().next().unwrap());
    format!(
        r#"{prefixed_cmd}
[Unit]
Description={name}
After=network.target

[Service]
ExecStart={cmd}
Restart=on-failure
RestartSec=5
LimitNOFILE=4096
StandardOutput={stdout}
StandardError={stderr}
SyslogIdentifier={name}
LogLevelMax=info
TimeoutStartSec=60
TimeoutStopSec=30
WorkingDirectory=/tmp

[Install]
WantedBy=default.target
"#,
        prefixed_cmd = comment(cmd),
        name = name,
        cmd = cmd,
        stdout = stdout.unwrap_or("journal"),
        stderr = stderr.unwrap_or("journal"),
    )
}