about summary refs log tree commit diff stats
path: root/pkgs/by-name/no/notify-run/src/main.rs
blob: a6a0165a2ee27bc69aae6caa1a3c584d10b929da (plain) (blame)
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
// nixos-config - My current NixOS configuration
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of my nixos-config.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::{env::args, path::PathBuf, process::Command};

use anyhow::{Context, Result};

fn main() -> Result<()> {
    let args = args().skip(1).collect::<Vec<_>>();

    let mut cmd = Command::new(&args[0]);
    if let Some(arguments) = args.get(1) {
        cmd.args(arguments.split(" ").collect::<Vec<_>>().as_slice());
    }

    eprintln!("Spawning {:?}", cmd);

    let output = cmd
        .output()
        .with_context(|| format!("Failed to spawn and await output of {:?}", cmd))?;

    if !output.status.success() {
        let mut notify_send = Command::new("notify-send");
        notify_send.args([
            format!("Command {:?} failed", cmd).as_str(),
            &String::from_utf8_lossy(output.stderr.as_slice()),
        ]);

        notify_send.status().with_context(|| {
            format!(
                "Failed to run `notify-send` to tell about failed command ({:?}).",
                cmd
            )
        })?;
    } else {
        let name = PathBuf::from(&args[0])
            .file_name()
            .expect("this to be a command, and thus have a file_name")
            .to_string_lossy()
            .to_string();

        print!("{}", append_name(&name, &output.stdout));
        eprint!("{}", append_name(&name, &output.stderr));
    }

    Ok(())
}

fn append_name(name: &str, base: &[u8]) -> String {
    let base = String::from_utf8_lossy(base).to_string();

    let mut output = String::new();
    for line in base.lines() {
        output.push_str(format!("{name}> {line}\n").as_str());
    }

    output
}