git clone https://garage44.eu/jeroen/midas.git.. /src/util.rs
//! Small things several modules need the same way: running a command, git,
//! cutting text short for a line, and reading a duration people typed.
use std::io::Write;
use std::path::Path;
use std::process::{Command, Output, Stdio};
use anyhow::{bail, Context, Result};
/// Run a command and return its stdout; an error with its stderr if it fails.
pub fn run(cmd: &mut Command) -> Result<String> {
let out = cmd.output().with_context(|| format!("running {cmd:?}"))?;
if !out.status.success() {
bail!("{cmd:?} failed: {}", String::from_utf8_lossy(&out.stderr).trim());
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
/// Run `f` on a thread of its own and do not wait for it. `std::thread::spawn` panics when
/// the process is at its task limit, and the release build aborts on a panic, so a hub at its
/// limit lost everything to one background job (2026-10-27): this logs that `what` did not run.
pub fn spawn_detached(what: &str, f: impl FnOnce() + Send + 'static) {
if let Err(e) = std::thread::Builder::new().spawn(f) {
crate::events::emit("error", serde_json::json!({"what": format!("no thread for {what}: {e}")}));
}
}
/// A commit's short form: its first eight characters, or all of a shorter one. By characters,
/// not bytes: a sha in a posted event is anything the poster wrote, and `&s[..8]` through an
/// `é` panicked (the hub with it).
pub fn sha8(s: &str) -> &str {
s.char_indices().nth(8).map_or(s, |(i, _)| &s[..i])
}
/// `git -C <dir> <args>`, its output trimmed. A bare repository (the hub's
/// mirrors) is a `dir` too.
pub fn git(dir: &Path, args: &[&str]) -> Result<String> {
let out = Command::new("git").arg("-C").arg(dir).args(args).output()
.with_context(|| format!("running git {}", args.join(" ")))?;
if !out.status.success() {
bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
/// Free (to an unprivileged user) and total bytes on the filesystem `path` is on.
pub fn disk_space(path: &std::path::Path) -> Option<(u64, u64)> {
use std::os::unix::ffi::OsStrExt;
let path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
// SAFETY: statvfs fills a struct we own, from a valid C string.
let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
(unsafe { libc::statvfs(path.as_ptr(), &mut st) } == 0)
.then(|| (st.f_bavail as u64 * st.f_frsize as u64, st.f_blocks as u64 * st.f_frsize as u64))
}
/// A value for a curl config file (`-K`), quoted, line breaks and all. curl
/// reads its config line by line, so a raw line break in a value — a body a
/// caller sent through the hub's Forgejo proxy, say — would end the value and
/// start an option of the caller's choosing (`upload-file`, `output`).
pub fn curl_quote(s: &str) -> String {
format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"").replace('\r', "\\r").replace('\n', "\\n"))
}
/// curl with `headers` given in a config on its stdin (`-K -`), never on its
/// command line, where any user of the machine reads them in `ps`: they carry
/// tokens. `args` are the rest, as usual.
pub fn curl(headers: &[String], args: &[&str]) -> Result<Output> {
let config: String = headers.iter().map(|h| format!("header = {}\n", curl_quote(h))).collect();
let mut child = Command::new("curl").args(["-K", "-"]).args(args)
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
.spawn().context("starting curl")?;
child.stdin.take().expect("piped").write_all(config.as_bytes())?;
Ok(child.wait_with_output()?)
}
/// One line to stderr, the UTC time before it: what a long-running process's
/// log needs to be read against the event log. A stderr gone costs the line, not
/// the process, which `eprintln!` would end with a panic.
pub fn log_line(s: &str) {
use std::io::Write;
let _ = writeln!(std::io::stderr(), "{} {s}", chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"));
}
/// At most `n` characters, the last of them `…` when it was cut.
pub fn short(s: &str, n: usize) -> String {
if s.chars().count() <= n {
s.to_string()
} else {
s.chars().take(n.saturating_sub(1)).collect::<String>() + "…"
}
}
/// At most `n` characters, cut after a whole word with `…` when it was cut
/// (mid-word only when one word is longer than the line): for a command or a
/// sentence shown on one line, which reads wrong cut mid-quote.
pub fn clip_words(s: &str, n: usize) -> String {
let s = s.trim();
if s.chars().count() <= n {
return s.to_string();
}
let head: String = s.chars().take(n.saturating_sub(1)).collect();
let cut = match head.rfind(char::is_whitespace) {
Some(i) if i > head.len() / 2 => head[..i].trim_end(),
_ => head.as_str(),
};
format!("{cut}…")
}
/// A duration as people type it — `90`, `90s`, `30m`, `2h`, `3d` — in seconds.
pub fn seconds(s: &str) -> Option<u64> {
let s = s.trim();
let (num, mult) = match s.chars().last()? {
's' => (&s[..s.len() - 1], 1),
'm' => (&s[..s.len() - 1], 60),
'h' => (&s[..s.len() - 1], 3600),
'd' => (&s[..s.len() - 1], 86400),
_ => (s, 1),
};
if num.is_empty() || !num.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
num.parse::<u64>().ok()?.checked_mul(mult)
}
/// This binary's path, for running it again. After a deploy has put a new
/// midas in its place, Linux names the running one "<path> (deleted)", which
/// nothing can run; the new one is at the path itself. A runner that started
/// a session's agent that way lost it (s3, 2026-10-21).
pub fn exe() -> std::io::Result<std::path::PathBuf> {
let p = std::env::current_exe()?;
Ok(match p.to_str().and_then(|s| s.strip_suffix(" (deleted)")) {
Some(live) if !p.exists() => std::path::PathBuf::from(live),
_ => p,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_short_sha_is_cut_by_characters() {
assert_eq!(sha8("02f4dcdb7e1a"), "02f4dcdb");
assert_eq!(sha8("abc"), "abc");
assert_eq!(sha8("1234567é9"), "1234567é", "byte 8 inside a character");
}
#[test]
fn text_is_cut_with_an_ellipsis_and_at_a_word_where_it_can_be() {
assert_eq!(short("abcdef", 6), "abcdef");
assert_eq!(short("abcdefg", 6), "abcde…");
assert_eq!(short("ééééé", 3), "éé…", "characters, not bytes");
assert_eq!(clip_words("cargo test --workspace", 40), "cargo test --workspace");
assert_eq!(clip_words("ssh vps-1 'cargo test --workspace --exclude cartopolis_android'", 40),
"ssh vps-1 'cargo test --workspace…");
assert_eq!(clip_words(&"x".repeat(50), 10), format!("{}…", "x".repeat(9)), "one long word is cut where it must");
}
#[test]
fn curl_takes_its_headers_from_stdin_quoted() {
assert_eq!(curl_quote(r#"Authorization: token a"b\c"#), r#""Authorization: token a\"b\\c""#);
}
#[test]
fn a_value_with_line_breaks_stays_one_curl_config_line() {
let q = curl_quote("{}\nupload-file = \"/srv/midas/callers.json\"\r\nurl = \"http://x/\"");
assert!(!q.contains('\n') && !q.contains('\r'));
assert_eq!(curl_quote("a\r\n"), r#""a\r\n""#);
}
#[test]
fn durations_read_as_people_type_them() {
for (s, want) in [("90", Some(90)), ("90s", Some(90)), ("30m", Some(1800)), ("2h", Some(7200)), ("3d", Some(259200)),
("0", Some(0)), ("", None), ("h", None), ("soon", None), ("-5m", None), ("2.5h", None)] {
assert_eq!(seconds(s), want, "{s:?}");
}
}
}