This commit is contained in:
Kelorastus
2026-09-30 10:53:46 +02:00
parent 58ebd1dded
commit ffbb8fc9a5
12 changed files with 619 additions and 25 deletions
+259
View File
@@ -0,0 +1,259 @@
//! Cutting a release from the hub, in dev mode.
//!
//! Three artifacts ship from these repos and each has its own pipeline: the ODIAN pack
//! (client + API + tile server), this launcher, and the Engine API container on the
//! cluster. The scripts that do the work already exist and are the ones a person runs by
//! hand; nothing here reimplements them. This decides WHAT is behind and runs them.
//!
//! "Behind" is answered by the commit each published artifact records it was built from.
//! Comparing versions would not do: a version says what was cut, not from what.
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::process::Command;
/// What a release could do right now, and what stops it.
#[derive(Clone, Debug, Serialize)]
pub struct ReleasePlan {
/// Docker Desktop answers. Only the Engine API container needs it.
pub docker: bool,
/// The DHP answered its health check: nothing can be published without it.
pub online: bool,
/// The scripts that do the work are where they should be.
pub scripts: bool,
pub items: Vec<ReleaseItem>,
/// Why the whole thing cannot run, in one line; None when it can.
pub blocked: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct ReleaseItem {
/// `pack`, `launcher` or `api`.
pub key: &'static str,
pub title: &'static str,
/// The version that is live, when it could be read.
pub live: Option<String>,
/// The repo's HEAD, short.
pub commit: Option<String>,
/// True when the repo has moved past what is published. None when nothing published
/// says which commit it came from - the honest answer until a release records one.
pub behind: Option<bool>,
/// Uncommitted changes in its repo: a release from those could not be rebuilt.
pub dirty: bool,
/// What the row says out loud.
pub note: String,
}
/// Is a Docker daemon answering? The Engine API image is built in one.
pub fn docker_running() -> bool {
run_ok(Command::new("docker").args(["info", "--format", "{{.ServerVersion}}"]))
}
fn run_ok(cmd: &mut Command) -> bool {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
cmd.output().map(|o| o.status.success()).unwrap_or(false)
}
fn git(repo: &Path, args: &[&str]) -> Option<String> {
let mut cmd = Command::new("git");
cmd.arg("-C").arg(repo).args(args);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
let out = cmd.output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
}
fn head(repo: &Path) -> Option<String> {
git(repo, &["rev-parse", "HEAD"])
}
fn dirty(repo: &Path) -> bool {
git(repo, &["status", "--porcelain"]).is_some_and(|s| !s.trim().is_empty())
}
/// One artifact's row: is this repo past what is published?
fn item(
key: &'static str,
title: &'static str,
repo: PathBuf,
live: Option<String>,
published_commit: Option<String>,
) -> ReleaseItem {
let exists = repo.is_dir();
let commit = exists.then(|| head(&repo)).flatten();
let dirty = exists && dirty(&repo);
let behind = match (&commit, &published_commit) {
(Some(now), Some(was)) => Some(now != was),
_ => None,
};
let note = match (exists, &commit, behind, dirty) {
(false, ..) => format!("{} is not in the checkout folder", repo.display()),
(_, None, ..) => "not a git checkout".to_string(),
(_, _, _, true) => "uncommitted changes: commit them before releasing".to_string(),
(_, _, Some(true), _) => "behind: the repo has moved past what is published".to_string(),
(_, _, Some(false), _) => "up to date".to_string(),
(_, _, None, _) => "what is published does not say which commit it came from".to_string(),
};
ReleaseItem { key, title, live, commit: commit.map(|c| c[..c.len().min(7)].to_string()), behind, dirty, note }
}
/// Everything the Release panel shows.
pub fn plan(
dev_root: &Path,
mcp_repo: &Path,
online: bool,
pack_live: Option<String>,
pack_commit: Option<String>,
launcher_live: Option<String>,
launcher_commit: Option<String>,
api_live: Option<String>,
) -> ReleasePlan {
let docker = docker_running();
let scripts = mcp_repo.join("scripts").join("release_pack.ps1").is_file()
&& mcp_repo.join("scripts").join("package_launcher.ps1").is_file();
let items = vec![
item("pack", "ODIAN", dev_root.join("ODIAN_Engine"), pack_live, pack_commit),
item("launcher", "Launcher", dev_root.join("ODIAN_Launcher"), launcher_live, launcher_commit),
// The container is built from the same Engine checkout as the pack; only its pipeline
// differs, and only it needs Docker.
item("api", "Engine API", dev_root.join("ODIAN_Engine"), api_live, None),
];
let blocked = if !online {
Some("The DHP is not answering: nothing can be published.".to_string())
} else if !scripts {
Some(format!("The release scripts are not in {}.", mcp_repo.display()))
} else if items.iter().any(|i| i.dirty) {
Some("Commit what is open first: a release built from uncommitted work cannot be rebuilt.".to_string())
} else {
None
};
ReleasePlan { docker, online, scripts, items, blocked }
}
/// Cut and publish, in its own console.
///
/// The three scripts are run as a person runs them, in order, and each decides for itself
/// whether it has anything to do: `release_pack.ps1` stops with "nothing changed" when the
/// repo matches the live manifest, and `deploy-api.ps1` skips the roll when the compiled
/// binary is identical. So "release whatever is behind" needs no prediction here - only
/// that they are run in the right order and that the first real failure stops the rest.
///
/// The node's sudo password goes in the ENVIRONMENT, not the command line: arguments are
/// readable by anyone who can list processes.
pub fn run_release(
mcp_repo: &Path,
work_dir: &Path,
pack_version: &str,
launcher_version: Option<&str>,
with_api: bool,
sudo: &str,
) -> Result<PathBuf, String> {
let scripts = mcp_repo.join("scripts");
let mut ps = String::new();
ps.push_str("$ErrorActionPreference = 'Stop'
");
ps.push_str("$pw = $env:ODIAN_NODE_SUDO
");
ps.push_str("$env:ODIAN_NODE_SUDO = $null
"); // out of the environment the scripts inherit
ps.push_str(&format!(
"Write-Host '=== ODIAN pack {pack_version} ===' -ForegroundColor Cyan
& '{}' -Version '{pack_version}' -NodeSudoPw $pw
if ($LASTEXITCODE -notin 0,2) {{ Write-Host 'the pack step failed' -ForegroundColor Red; pause; exit 1 }}
if ($LASTEXITCODE -eq 2) {{ Write-Host 'pack: nothing to release' -ForegroundColor Yellow }}
",
scripts.join("release_pack.ps1").display()
));
if let Some(v) = launcher_version {
ps.push_str(&format!(
"Write-Host '=== Launcher {v} ===' -ForegroundColor Cyan
& '{}' -Version '{v}' -SiteUrl 'https://engine.odian.fr/dhp' -McpUrl 'https://engine.odian.fr' -AiUrl 'https://engine.odian.fr' -SiteName 'ODIAN test DHP' -Publish
if ($LASTEXITCODE -ne 0) {{ Write-Host 'the launcher step failed' -ForegroundColor Red; pause; exit 1 }}
",
scripts.join("package_launcher.ps1").display()
));
}
if with_api {
ps.push_str(&format!(
"Write-Host '=== Engine API ===' -ForegroundColor Cyan
& '{}' -NodeSudoPw $pw
if ($LASTEXITCODE -notin 0,3) {{ Write-Host 'the API step failed' -ForegroundColor Red; pause; exit 1 }}
",
// The api script lives with the release skill, beside the others when it is there.
scripts.join("deploy-api.ps1").display()
));
}
ps.push_str("Write-Host ''
Write-Host 'Release finished.' -ForegroundColor Green
pause
");
std::fs::create_dir_all(work_dir).map_err(|e| format!("cannot use {}: {e}", work_dir.display()))?;
let file = work_dir.join("release.ps1");
std::fs::write(&file, ps).map_err(|e| format!("cannot write {}: {e}", file.display()))?;
let mut cmd = Command::new("powershell");
cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]).arg(&file);
cmd.env("ODIAN_NODE_SUDO", sudo);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0000_0010); // CREATE_NEW_CONSOLE: the developer watches it run
}
cmd.spawn().map_err(|e| format!("cannot start the release: {e}"))?;
Ok(file)
}
/// `0.71.0` -> `0.72.0`. A pack release is a minor; the patch place is not used.
pub fn next_pack(live: &str) -> Option<String> {
let p: Vec<u64> = live.split('.').map_while(|x| x.parse().ok()).collect();
(p.len() >= 2).then(|| format!("{}.{}.0", p[0], p[1] + 1))
}
/// `0.1.38` -> `0.1.39`.
pub fn next_launcher(live: &str) -> Option<String> {
let p: Vec<u64> = live.split('.').map_while(|x| x.parse().ok()).collect();
(p.len() >= 3).then(|| format!("{}.{}.{}", p[0], p[1], p[2] + 1))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_next_version_moves_the_right_place() {
// A pack is a minor (0.71.0 -> 0.72.0); the launcher is a patch (0.1.38 -> 0.1.39).
assert_eq!(next_pack("0.71.0").as_deref(), Some("0.72.0"));
assert_eq!(next_pack("0.9.0").as_deref(), Some("0.10.0"), "ten follows nine");
assert_eq!(next_launcher("0.1.38").as_deref(), Some("0.1.39"));
assert_eq!(next_launcher("0.1.9").as_deref(), Some("0.1.10"));
// Nonsense from a feed must not become a version number.
assert_eq!(next_pack("").as_deref(), None);
assert_eq!(next_launcher("latest").as_deref(), None);
assert_eq!(next_launcher("0.1").as_deref(), None);
}
#[test]
fn a_repo_that_matches_what_is_published_is_not_behind() {
// The comparison is COMMIT against COMMIT. Versions cannot answer it: a version says
// what was cut, not from what - which is how a release gets cut twice from one tree.
let same = item("pack", "ODIAN", PathBuf::from("."), Some("0.71.0".into()), head(Path::new(".")));
if same.commit.is_some() {
assert_eq!(same.behind, Some(false), "same commit: nothing to release");
}
// Nothing published says where it came from: say so rather than guess.
let unknown = item("pack", "ODIAN", PathBuf::from("."), Some("0.71.0".into()), None);
assert_eq!(unknown.behind, None);
assert!(unknown.note.contains("does not say") || unknown.dirty || unknown.commit.is_none());
// A folder that is not there is named, not silently "up to date".
let missing = item("pack", "ODIAN", PathBuf::from(r"Z:\nothing\here"), None, None);
assert_eq!(missing.behind, None);
assert!(missing.note.contains("not in the checkout folder"));
}
}