local-ci 0.6.2

Run the GitHub Actions jobs a branch would trigger, locally, in an isolated worktree, and print a short report
//! Ports from [portool](https://github.com/t09tanaka/portool)'s ledger, so a
//! job whose scripts fall back to a fixed port (`TEST_PORT ?? 4000`) gets one
//! no other worktree uses.

use anyhow::{bail, Context, Result};
use std::path::Path;
use std::process::{Command, Stdio};

/// Allocate (or keep) the port block of the worktree at `ws` and return what
/// `.env.portool` says (`APP_PORT=…`, `TEST_PORT=…`).
pub fn sync(bin: &Path, ws: &Path) -> Result<Vec<(String, String)>> {
    // a copy carries the `.env.portool` of the worktree it was made from
    let file = ws.join(".env.portool");
    let _ = std::fs::remove_file(&file);
    let out = Command::new(bin)
        .args(["sync", "--quiet"])
        .current_dir(ws)
        .stdin(Stdio::null())
        .output()
        .context("cannot run portool")?;
    if !out.status.success() {
        bail!(
            "portool sync: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let text = std::fs::read_to_string(&file).context("portool wrote no .env.portool")?;
    Ok(parse(&text))
}

pub fn parse(text: &str) -> Vec<(String, String)> {
    text.lines()
        .map(str::trim)
        .filter(|l| !l.is_empty() && !l.starts_with('#'))
        .filter_map(|l| l.split_once('='))
        .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
        .collect()
}

/// Give the block back. Run it while the worktree still exists.
pub fn release(bin: &Path, ws: &Path) {
    let _ = Command::new(bin)
        .arg("release")
        .current_dir(ws)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn env_file() {
        let v = parse("# generated by portool\n# block: 1-5\nAPP_PORT=4100\n\nTEST_PORT = 4101\n");
        assert_eq!(
            v,
            vec![
                ("APP_PORT".into(), "4100".into()),
                ("TEST_PORT".into(), "4101".into())
            ]
        );
    }
}