aboutsummaryrefslogtreecommitdiff
path: root/src/process.rs
blob: eb48bc8bb7853257e2eb6247c7299bd4ebc3b5c7 (plain)
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
// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::fmt;
use std::io::{self, Write};
use std::process::{Command, Output};

use anyhow::{Context, Result, bail};

pub(crate) fn capture(command: &mut Command) -> Result<Output> {
    let output = command.output().with_context(|| {
        format!(
            "Could not start {}",
            command.get_program().to_string_lossy()
        )
    })?;
    if !output.status.success() {
        bail!(
            "{} failed ({}): {}",
            command.get_program().to_string_lossy(),
            output.status,
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(output)
}

pub(crate) fn text(command: &mut Command) -> Result<String> {
    String::from_utf8(capture(command)?.stdout).context("Command returned non-UTF-8 output")
}

pub(crate) fn run(command: &mut Command) -> Result<()> {
    let status = command.status().with_context(|| {
        format!(
            "Could not start {}",
            command.get_program().to_string_lossy()
        )
    })?;
    if !status.success() {
        bail!(
            "{} failed ({status})",
            command.get_program().to_string_lossy()
        );
    }
    Ok(())
}

pub(crate) fn available(command: &mut Command) -> bool {
    command.output().is_ok_and(|output| output.status.success())
}

pub(crate) fn line(message: fmt::Arguments<'_>) -> Result<()> {
    writeln!(io::stdout().lock(), "{message}").context("Could not write command output")
}

pub(crate) fn error(message: fmt::Arguments<'_>) -> io::Result<()> {
    writeln!(io::stderr().lock(), "{message}")
}