| @@ -0,0 +1,1152 @@ |
| 1 | +//! `louise self update`: replace the running compiler, and the runtime |
| 2 | +//! archives next to it, with a release's prebuilt ones (issue #284). |
| 3 | +//! |
| 4 | +//! Until the forge has real releases (toboggan#94), a "release" is the |
| 5 | +//! artifact of the latest successful `release` workflow run on a tag |
| 6 | +//! (`.toboggan/workflows/release.yml`): an artifact `louise-<tag>-<platform>` |
| 7 | +//! holding `louise-<tag>-<platform>.tar.xz` (the compiler, the three |
| 8 | +//! runtime archives and the lto archive's LLVM version) and the tarball's |
| 9 | +//! sha256. [`discover`] is the one function that knows this shape; real |
| 10 | +//! releases swap in by replacing it, the rest stands. |
| 11 | +//! |
| 12 | +//! The forge's API is MessagePack over HTTPS with a bearer token |
| 13 | +//! (toboggan's docs/api.md); `tob`'s `src/api.rs` is the reference client |
| 14 | +//! this one follows. The token, first match wins: |
| 15 | +//! |
| 16 | +//! 1. `LOUISE_TOKEN`; |
| 17 | +//! 2. `TOBOGGAN_TOKEN`; |
| 18 | +//! 3. the host's token in tob's `~/.config/tob/hosts.toml` (sign in with |
| 19 | +//! `tob auth login --hostname toboggan.cloud`); |
| 20 | +//! 4. none, which answers 401 while the repository is `internal`. |
| 21 | +//! |
| 22 | +//! `LOUISE_UPDATE_HOST`, `LOUISE_UPDATE_REPO` and `LOUISE_UPDATE_WORKFLOW` |
| 23 | +//! override where releases are looked for; they are for tests and forks, |
| 24 | +//! not for users. |
| 25 | + |
| 26 | +use std::collections::BTreeMap; |
| 27 | +use std::fmt; |
| 28 | +use std::fs; |
| 29 | +use std::io::{Read as _, Write as _}; |
| 30 | +use std::path::{Path, PathBuf}; |
| 31 | +use std::process::ExitCode; |
| 32 | +use std::time::Duration; |
| 33 | + |
| 34 | +use serde::Deserialize; |
| 35 | +use sha2::{Digest as _, Sha256}; |
| 36 | + |
| 37 | +/// Where releases live, unless the `LOUISE_UPDATE_*` variables say else. |
| 38 | +const HOST: &str = "toboggan.cloud"; |
| 39 | +const REPO: &str = "gabla108/louise"; |
| 40 | +const WORKFLOW: &str = "release.yml"; |
| 41 | + |
| 42 | +/// An API answer is a run list or one run; anything bigger is not one. |
| 43 | +const MAX_ANSWER_BYTES: u64 = 64 * 1024 * 1024; |
| 44 | +/// A tarball entry read into memory is refused past this (the tarball is |
| 45 | +/// tens of megabytes). |
| 46 | +const MAX_MEMBER_BYTES: u64 = 512 * 1024 * 1024; |
| 47 | + |
| 48 | +/// The files an install replaces, in order: the runtime archives first, |
| 49 | +/// the compiler last, so a crash mid-install never leaves the directory |
| 50 | +/// without archives and keeps the old compiler running until the new one |
| 51 | +/// is wholly there (every rename is atomic; a crash leaves a consistent |
| 52 | +/// mix the next `louise self update` finishes). |
| 53 | +const ARCHIVES: &[&str] = &[ |
| 54 | + "liblouise_rt.a", |
| 55 | + "liblouise_rt-fast.a", |
| 56 | + "liblouise_rt-lto.a", |
| 57 | +]; |
| 58 | +/// Present when the release build had clang and lld (it does); linked |
| 59 | +/// from the archive's directory when there. |
| 60 | +const OPTIONAL: &[&str] = &["liblouise_rt-lto.llvm"]; |
| 61 | +const BINARY: &str = "louise"; |
| 62 | + |
| 63 | +/// `louise self update [--check] [--version V] [--dry-run] [--force]`. |
| 64 | +pub(crate) fn update(check: bool, version: Option<&str>, dry_run: bool, force: bool) -> ExitCode { |
| 65 | + match go(check, version, dry_run, force) { |
| 66 | + Ok(()) => ExitCode::SUCCESS, |
| 67 | + Err(message) => { |
| 68 | + eprintln!("error: {message}"); |
| 69 | + ExitCode::FAILURE |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +fn go(check: bool, version: Option<&str>, dry_run: bool, force: bool) -> Result<(), String> { |
| 75 | + let platform = platform()?; |
| 76 | + let current = Version::current(); |
| 77 | + let targets = Targets::from_env(); |
| 78 | + let client = Client::new(&targets.host, token(&targets.host))?; |
| 79 | + let release = discover(&client, &targets, version, platform)?; |
| 80 | + let wanted = Version::parse(&release.tag) |
| 81 | + .ok_or_else(|| format!("the release's tag {} is not a version", release.tag))?; |
| 82 | + |
| 83 | + if check { |
| 84 | + println!("installed: louise {current}"); |
| 85 | + println!("latest: {} (run {})", release.tag, release.run); |
| 86 | + match wanted.cmp(¤t) { |
| 87 | + std::cmp::Ordering::Greater => { |
| 88 | + println!("an update is available: {current} → {wanted}; run `louise self update`") |
| 89 | + } |
| 90 | + std::cmp::Ordering::Equal => println!("louise {current} is up to date"), |
| 91 | + std::cmp::Ordering::Less => { |
| 92 | + println!("the latest release, {wanted}, is older than this louise {current}") |
| 93 | + } |
| 94 | + } |
| 95 | + return Ok(()); |
| 96 | + } |
| 97 | + match wanted.cmp(¤t) { |
| 98 | + std::cmp::Ordering::Equal if !force => { |
| 99 | + println!("louise {current} is already {wanted} (--force reinstalls)"); |
| 100 | + return Ok(()); |
| 101 | + } |
| 102 | + std::cmp::Ordering::Less if !force => { |
| 103 | + return Err(format!( |
| 104 | + "{} would downgrade louise {current} to {wanted}; pass --force to allow it", |
| 105 | + release.tag |
| 106 | + )); |
| 107 | + } |
| 108 | + _ => {} |
| 109 | + } |
| 110 | + |
| 111 | + let exe = |
| 112 | + std::env::current_exe().map_err(|e| format!("cannot find the running executable: {e}"))?; |
| 113 | + let dir = exe |
| 114 | + .parent() |
| 115 | + .ok_or_else(|| format!("{} has no directory", exe.display()))?; |
| 116 | + let staging = Staging::new(dir)?; |
| 117 | + |
| 118 | + // Download, verify and extract before anything is replaced. |
| 119 | + let zip = staging.path().join("artifact.zip"); |
| 120 | + eprintln!( |
| 121 | + "downloading {} (run {}, {} bytes)…", |
| 122 | + release.artifact.name, release.run, release.artifact.size |
| 123 | + ); |
| 124 | + client.download(&release.download_path(&targets), &zip)?; |
| 125 | + if let Some(expected) = &release.artifact.sha256 { |
| 126 | + let got = sha256_file(&zip)?; |
| 127 | + if !got.eq_ignore_ascii_case(expected) { |
| 128 | + return Err(format!( |
| 129 | + "the artifact's sha256 differs from the server's ({got} ≠ {expected}); not installing it" |
| 130 | + )); |
| 131 | + } |
| 132 | + } |
| 133 | + let tarball = format!("{}.tar.xz", release.artifact.name); |
| 134 | + let members = unzip(&zip, &tarball)?; |
| 135 | + verify_sha256(&members.tarball, &members.sha256)?; |
| 136 | + let unpacked = staging.path().join("unpacked"); |
| 137 | + untar(&members.tarball, &unpacked)?; |
| 138 | + let staged = find_staged(&unpacked, &release.artifact.name)?; |
| 139 | + sanity_check(&staged, &wanted)?; |
| 140 | + |
| 141 | + if dry_run { |
| 142 | + println!( |
| 143 | + "would replace in {}: {}", |
| 144 | + dir.display(), |
| 145 | + present_members(&staged).join(", ") |
| 146 | + ); |
| 147 | + println!("dry run: nothing replaced"); |
| 148 | + return Ok(()); |
| 149 | + } |
| 150 | + |
| 151 | + install(&staged, dir)?; |
| 152 | + println!("louise {wanted} installed to {}", dir.display()); |
| 153 | + Ok(()) |
| 154 | +} |
| 155 | + |
| 156 | +/// The platform string release artifacts are named with; the only one |
| 157 | +/// built so far. |
| 158 | +fn platform() -> Result<&'static str, String> { |
| 159 | + match (std::env::consts::ARCH, std::env::consts::OS) { |
| 160 | + ("x86_64", "linux") => Ok("x86_64-linux"), |
| 161 | + (arch, os) => Err(format!( |
| 162 | + "no prebuilt binaries for {arch}-{os} yet (x86_64-linux only); build from source (README, \"Getting started\")" |
| 163 | + )), |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +/// Where releases are looked for: the constants, or the |
| 168 | +/// `LOUISE_UPDATE_*` overrides (tests and forks). |
| 169 | +struct Targets { |
| 170 | + host: String, |
| 171 | + repo: String, |
| 172 | + workflow: String, |
| 173 | +} |
| 174 | + |
| 175 | +impl Targets { |
| 176 | + fn from_env() -> Targets { |
| 177 | + let env = |name: &str, default: &str| { |
| 178 | + std::env::var(name) |
| 179 | + .ok() |
| 180 | + .filter(|v| !v.is_empty()) |
| 181 | + .unwrap_or_else(|| default.into()) |
| 182 | + }; |
| 183 | + Targets { |
| 184 | + // A URL's `https://` is tolerated; `http://` is not (the forge |
| 185 | + // is spoken to over TLS, always). |
| 186 | + host: env("LOUISE_UPDATE_HOST", HOST) |
| 187 | + .trim_start_matches("https://") |
| 188 | + .trim_end_matches('/') |
| 189 | + .into(), |
| 190 | + repo: env("LOUISE_UPDATE_REPO", REPO), |
| 191 | + workflow: env("LOUISE_UPDATE_WORKFLOW", WORKFLOW), |
| 192 | + } |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +/// The token the API calls carry (see the module docs for the order). |
| 197 | +fn token(host: &str) -> Option<String> { |
| 198 | + for var in ["LOUISE_TOKEN", "TOBOGGAN_TOKEN"] { |
| 199 | + if let Some(token) = std::env::var(var).ok().filter(|t| !t.is_empty()) { |
| 200 | + return Some(token); |
| 201 | + } |
| 202 | + } |
| 203 | + tob_token(host) |
| 204 | +} |
| 205 | + |
| 206 | +/// The host's token in tob's `~/.config/tob/hosts.toml` |
| 207 | +/// (`$XDG_CONFIG_HOME/tob/hosts.toml`), if tob is signed in there. |
| 208 | +fn tob_token(host: &str) -> Option<String> { |
| 209 | + let dir = std::env::var_os("XDG_CONFIG_HOME") |
| 210 | + .filter(|d| !d.is_empty()) |
| 211 | + .map(PathBuf::from) |
| 212 | + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?; |
| 213 | + let text = fs::read_to_string(dir.join("tob").join("hosts.toml")).ok()?; |
| 214 | + token_in_hosts_toml(&text, host) |
| 215 | +} |
| 216 | + |
| 217 | +#[derive(Deserialize)] |
| 218 | +struct TobConfig { |
| 219 | + #[serde(default)] |
| 220 | + hosts: BTreeMap<String, TobHost>, |
| 221 | +} |
| 222 | + |
| 223 | +#[derive(Deserialize)] |
| 224 | +struct TobHost { |
| 225 | + token: String, |
| 226 | +} |
| 227 | + |
| 228 | +fn token_in_hosts_toml(text: &str, host: &str) -> Option<String> { |
| 229 | + let config: TobConfig = toml::from_str(text).ok()?; |
| 230 | + let token = config.hosts.get(host)?.token.trim(); |
| 231 | + (!token.is_empty()).then(|| token.to_string()) |
| 232 | +} |
| 233 | + |
| 234 | +// ------------------------------------------------------------------ versions |
| 235 | + |
| 236 | +/// A release's version: `MAJOR.MINOR.PATCH`, the tag's leading `v` |
| 237 | +/// stripped. Pre-release suffixes are rejected: `update` installs stable |
| 238 | +/// releases only. |
| 239 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 240 | +struct Version { |
| 241 | + major: u64, |
| 242 | + minor: u64, |
| 243 | + patch: u64, |
| 244 | +} |
| 245 | + |
| 246 | +impl Version { |
| 247 | + /// This compiler's, from its manifest (clap's `--version` prints it). |
| 248 | + fn current() -> Version { |
| 249 | + Version::parse(env!("CARGO_PKG_VERSION")).expect("CARGO_PKG_VERSION is a version") |
| 250 | + } |
| 251 | + |
| 252 | + fn parse(text: &str) -> Option<Version> { |
| 253 | + let text = text.strip_prefix('v').unwrap_or(text); |
| 254 | + let mut parts = text.split('.'); |
| 255 | + let number = |part: Option<&str>| part?.parse().ok(); |
| 256 | + let version = Version { |
| 257 | + major: number(parts.next())?, |
| 258 | + minor: number(parts.next())?, |
| 259 | + patch: number(parts.next())?, |
| 260 | + }; |
| 261 | + parts.next().is_none().then_some(version) |
| 262 | + } |
| 263 | +} |
| 264 | + |
| 265 | +impl fmt::Display for Version { |
| 266 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 267 | + write!(f, "{}.{}.{}", self.major, self.minor, self.patch) |
| 268 | + } |
| 269 | +} |
| 270 | + |
| 271 | +// ------------------------------------------------------------------ the wire |
| 272 | + |
| 273 | +/// A page of runs (`GET /api/{o}/{r}/actions?workflow=`). |
| 274 | +#[derive(Debug, Deserialize)] |
| 275 | +struct Runs { |
| 276 | + runs: Vec<Run>, |
| 277 | + more: bool, |
| 278 | +} |
| 279 | + |
| 280 | +#[derive(Debug, Deserialize)] |
| 281 | +struct Run { |
| 282 | + number: u64, |
| 283 | + /// `push`, `pull_request` or `workflow_dispatch`. |
| 284 | + event: String, |
| 285 | + #[serde(rename = "ref")] |
| 286 | + git_ref: String, |
| 287 | + /// `queued`, `running`, `success`, `failure`, `cancelled`, `skipped`. |
| 288 | + state: String, |
| 289 | + /// ISO 8601 UTC: newest compares first as text. |
| 290 | + created_at: String, |
| 291 | + /// Only in a run's own answer. |
| 292 | + #[serde(default)] |
| 293 | + artifacts: Vec<Artifact>, |
| 294 | +} |
| 295 | + |
| 296 | +#[derive(Debug, Clone, Deserialize)] |
| 297 | +struct Artifact { |
| 298 | + id: u64, |
| 299 | + name: String, |
| 300 | + size: u64, |
| 301 | + /// Hex, as the server checked it on upload; absent on an older server. |
| 302 | + #[serde(default)] |
| 303 | + sha256: Option<String>, |
| 304 | +} |
| 305 | + |
| 306 | +/// A 4xx/5xx body's `{problems: [{code, message}]}` (fields unread). |
| 307 | +#[derive(Deserialize)] |
| 308 | +struct Problems { |
| 309 | + problems: Vec<Problem>, |
| 310 | +} |
| 311 | + |
| 312 | +#[derive(Deserialize)] |
| 313 | +struct Problem { |
| 314 | + code: String, |
| 315 | + message: String, |
| 316 | +} |
| 317 | + |
| 318 | +/// A release: the run that built it and the artifact that is it. |
| 319 | +#[derive(Debug)] |
| 320 | +struct Release { |
| 321 | + /// The tag the run ran on (`v0.1.0`). |
| 322 | + tag: String, |
| 323 | + run: u64, |
| 324 | + artifact: Artifact, |
| 325 | +} |
| 326 | + |
| 327 | +impl Release { |
| 328 | + fn download_path(&self, targets: &Targets) -> String { |
| 329 | + format!( |
| 330 | + "/{}/actions/runs/{}/artifacts/{}", |
| 331 | + targets.repo, self.run, self.artifact.id |
| 332 | + ) |
| 333 | + } |
| 334 | +} |
| 335 | + |
| 336 | +/// The release `version` names (a tag, with or without the `v`), else the |
| 337 | +/// newest: the artifact of the latest successful `release` run on a |
| 338 | +/// version tag. This is the interim, CI-artifact discovery; toboggan#94's |
| 339 | +/// real releases replace this function alone. |
| 340 | +fn discover( |
| 341 | + client: &Client, |
| 342 | + targets: &Targets, |
| 343 | + version: Option<&str>, |
| 344 | + platform: &str, |
| 345 | +) -> Result<Release, String> { |
| 346 | + let wanted = version.map(normalize_tag); |
| 347 | + let mut candidates = Vec::new(); |
| 348 | + for page in 1..=10 { |
| 349 | + let runs: Runs = client.get( |
| 350 | + &format!("/{}/actions", targets.repo), |
| 351 | + &[ |
| 352 | + ("workflow", targets.workflow.clone()), |
| 353 | + ("page", page.to_string()), |
| 354 | + ], |
| 355 | + )?; |
| 356 | + candidates.extend(runs.runs.into_iter().filter(|run| { |
| 357 | + run.event == "push" |
| 358 | + && run.state == "success" |
| 359 | + && tag_of(run).is_some_and(|tag| { |
| 360 | + Version::parse(tag).is_some() && wanted.as_ref().is_none_or(|w| *w == tag) |
| 361 | + }) |
| 362 | + })); |
| 363 | + if !runs.more { |
| 364 | + break; |
| 365 | + } |
| 366 | + } |
| 367 | + // Newest first: the timestamp, then the run number breaks a tie. |
| 368 | + candidates.sort_by(|a, b| { |
| 369 | + b.created_at |
| 370 | + .cmp(&a.created_at) |
| 371 | + .then(b.number.cmp(&a.number)) |
| 372 | + }); |
| 373 | + let run = candidates.first().ok_or_else(|| match &wanted { |
| 374 | + Some(tag) => format!( |
| 375 | + "no successful `{}` run on tag {tag} (tags a release workflow ran on create one)", |
| 376 | + targets.workflow |
| 377 | + ), |
| 378 | + None => format!( |
| 379 | + "no release found: no successful `{}` run on a tag yet (the first tag creates one)", |
| 380 | + targets.workflow |
| 381 | + ), |
| 382 | + })?; |
| 383 | + let tag = tag_of(run).expect("candidates are tag runs").to_string(); |
| 384 | + // The artifacts are in the run's own answer, not the list's. |
| 385 | + let full: Run = client.get( |
| 386 | + &format!("/{}/actions/runs/{}", targets.repo, run.number), |
| 387 | + &[], |
| 388 | + )?; |
| 389 | + let name = format!("louise-{tag}-{platform}"); |
| 390 | + let artifact = full |
| 391 | + .artifacts |
| 392 | + .into_iter() |
| 393 | + .find(|a| a.name == name) |
| 394 | + .ok_or_else(|| format!("run {} has no artifact {name}", run.number))?; |
| 395 | + Ok(Release { |
| 396 | + tag, |
| 397 | + run: run.number, |
| 398 | + artifact, |
| 399 | + }) |
| 400 | +} |
| 401 | + |
| 402 | +/// A run's tag, when it ran on one (`refs/tags/v0.1.0` → `v0.1.0`). |
| 403 | +fn tag_of(run: &Run) -> Option<&str> { |
| 404 | + run.git_ref.strip_prefix("refs/tags/") |
| 405 | +} |
| 406 | + |
| 407 | +/// A version as the tag that names it: `0.1.0` → `v0.1.0`. |
| 408 | +fn normalize_tag(version: &str) -> String { |
| 409 | + match version.strip_prefix('v') { |
| 410 | + Some(_) => version.to_string(), |
| 411 | + None => format!("v{version}"), |
| 412 | + } |
| 413 | +} |
| 414 | + |
| 415 | +// ------------------------------------------------------------------ transport |
| 416 | + |
| 417 | +/// The HTTPS client: MessagePack GETs and one streaming download, as |
| 418 | +/// `tob`'s `src/api.rs` does them. HTTPS only: no `http://` URL is ever |
| 419 | +/// built (the host is an authority, the scheme written here). |
| 420 | +struct Client { |
| 421 | + agent: ureq::Agent, |
| 422 | + base: String, |
| 423 | + token: Option<String>, |
| 424 | +} |
| 425 | + |
| 426 | +impl Client { |
| 427 | + fn new(host: &str, token: Option<String>) -> Result<Client, String> { |
| 428 | + if host.contains("://") || host.contains('/') { |
| 429 | + return Err(format!("{host}: a host, not a URL (https is always used)")); |
| 430 | + } |
| 431 | + let agent = ureq::Agent::config_builder() |
| 432 | + // Statuses are answers to read (problems), not transport errors. |
| 433 | + .http_status_as_error(false) |
| 434 | + .redirect_auth_headers(ureq::config::RedirectAuthHeaders::SameHost) |
| 435 | + .user_agent(format!("louise/{}", env!("CARGO_PKG_VERSION"))) |
| 436 | + .accept("application/msgpack") |
| 437 | + .timeout_connect(Some(Duration::from_secs(15))) |
| 438 | + .timeout_global(Some(Duration::from_secs(120))) |
| 439 | + .build() |
| 440 | + .new_agent(); |
| 441 | + Ok(Client { |
| 442 | + agent, |
| 443 | + base: format!("https://{host}/api"), |
| 444 | + token, |
| 445 | + }) |
| 446 | + } |
| 447 | + |
| 448 | + fn get<T: serde::de::DeserializeOwned>( |
| 449 | + &self, |
| 450 | + path: &str, |
| 451 | + query: &[(&str, String)], |
| 452 | + ) -> Result<T, String> { |
| 453 | + let mut request = self.agent.get(format!("{}{path}", self.base)); |
| 454 | + if let Some(token) = &self.token { |
| 455 | + request = request.header("Authorization", format!("Bearer {token}")); |
| 456 | + } |
| 457 | + for (key, value) in query { |
| 458 | + request = request.query(*key, value); |
| 459 | + } |
| 460 | + let mut response = request |
| 461 | + .call() |
| 462 | + .map_err(|e| format!("cannot reach the forge: {e}"))?; |
| 463 | + let status = response.status().as_u16(); |
| 464 | + let body = response |
| 465 | + .body_mut() |
| 466 | + .with_config() |
| 467 | + .limit(MAX_ANSWER_BYTES) |
| 468 | + .read_to_vec() |
| 469 | + .map_err(|e| format!("cannot read the answer to GET {path}: {e}"))?; |
| 470 | + self.problems(status, &body)?; |
| 471 | + rmp_serde::from_slice(&body) |
| 472 | + .map_err(|e| format!("the answer to GET {path} is not what the API describes: {e}")) |
| 473 | + } |
| 474 | + |
| 475 | + /// `path`'s bytes to `dest`, through `dest.part` renamed once whole, |
| 476 | + /// so a failure leaves no half file under the name; the byte count. |
| 477 | + fn download(&self, path: &str, dest: &Path) -> Result<u64, String> { |
| 478 | + let mut request = self |
| 479 | + .agent |
| 480 | + .get(format!("{}{path}", self.base)) |
| 481 | + .config() |
| 482 | + // An artifact can be large: the agent's two minutes are too few. |
| 483 | + .timeout_global(Some(Duration::from_secs(3600))) |
| 484 | + .build(); |
| 485 | + if let Some(token) = &self.token { |
| 486 | + request = request.header("Authorization", format!("Bearer {token}")); |
| 487 | + } |
| 488 | + let mut response = request |
| 489 | + .call() |
| 490 | + .map_err(|e| format!("cannot reach the forge: {e}"))?; |
| 491 | + let status = response.status().as_u16(); |
| 492 | + if status >= 400 { |
| 493 | + let body = response |
| 494 | + .body_mut() |
| 495 | + .with_config() |
| 496 | + .limit(MAX_ANSWER_BYTES) |
| 497 | + .read_to_vec() |
| 498 | + .unwrap_or_default(); |
| 499 | + self.problems(status, &body)?; |
| 500 | + } |
| 501 | + let mut part = dest.as_os_str().to_owned(); |
| 502 | + part.push(".part"); |
| 503 | + let part = PathBuf::from(part); |
| 504 | + let mut file = |
| 505 | + fs::File::create(&part).map_err(|e| format!("cannot write {}: {e}", part.display()))?; |
| 506 | + match std::io::copy(&mut response.into_body().into_reader(), &mut file) { |
| 507 | + Ok(written) => { |
| 508 | + fs::rename(&part, dest) |
| 509 | + .map_err(|e| format!("cannot write {}: {e}", dest.display()))?; |
| 510 | + Ok(written) |
| 511 | + } |
| 512 | + Err(e) => { |
| 513 | + let _ = fs::remove_file(&part); |
| 514 | + Err(format!("the download of {} broke off: {e}", dest.display())) |
| 515 | + } |
| 516 | + } |
| 517 | + } |
| 518 | + |
| 519 | + /// Nothing when `status` is 2xx, the body's problems as the error else. |
| 520 | + fn problems(&self, status: u16, body: &[u8]) -> Result<(), String> { |
| 521 | + if status < 400 { |
| 522 | + return Ok(()); |
| 523 | + } |
| 524 | + if status == 401 { |
| 525 | + let advice = if self.token.is_some() { |
| 526 | + "the token was refused (expired or revoked?)" |
| 527 | + } else { |
| 528 | + "it is internal: sign in with `tob auth login --hostname toboggan.cloud`, or set LOUISE_TOKEN" |
| 529 | + }; |
| 530 | + return Err(format!("the forge needs a token: {advice}")); |
| 531 | + } |
| 532 | + let problems = rmp_serde::from_slice::<Problems>(body) |
| 533 | + .map(|p| { |
| 534 | + p.problems |
| 535 | + .iter() |
| 536 | + .map(|p| format!("{}: {}", p.code, p.message)) |
| 537 | + .collect::<Vec<_>>() |
| 538 | + .join("; ") |
| 539 | + }) |
| 540 | + .unwrap_or_default(); |
| 541 | + if problems.is_empty() { |
| 542 | + Err(format!("the forge answered HTTP {status}")) |
| 543 | + } else { |
| 544 | + Err(problems) |
| 545 | + } |
| 546 | + } |
| 547 | +} |
| 548 | + |
| 549 | +// ------------------------------------------------------------------ the archive |
| 550 | + |
| 551 | +/// A release artifact's two members, read out of its zip. |
| 552 | +struct Members { |
| 553 | + /// `louise-<tag>-<platform>.tar.xz`. |
| 554 | + tarball: Vec<u8>, |
| 555 | + /// Its sha256 file's text (`<hex> <name>`). |
| 556 | + sha256: String, |
| 557 | +} |
| 558 | + |
| 559 | +/// The artifact is a zip (what upload-artifact stores) of the tarball and |
| 560 | +/// its sha256 file. Entries are looked up by name, tolerating a directory |
| 561 | +/// prefix (upload-artifact keeps the paths' common root). |
| 562 | +fn unzip(zip: &Path, tarball: &str) -> Result<Members, String> { |
| 563 | + let file = fs::File::open(zip).map_err(|e| format!("cannot read {}: {e}", zip.display()))?; |
| 564 | + let mut archive = zip::ZipArchive::new(std::io::BufReader::new(file)) |
| 565 | + .map_err(|e| format!("{} is not a zip: {e}", zip.display()))?; |
| 566 | + let mut entry = |name: &str| -> Result<Vec<u8>, String> { |
| 567 | + let names: Vec<String> = archive |
| 568 | + .file_names() |
| 569 | + .map(|n| n.map(|c| c.into_owned())) |
| 570 | + .collect::<Result<Vec<_>, _>>() |
| 571 | + .map_err(|e| format!("cannot list the artifact: {e}"))?; |
| 572 | + let found = names |
| 573 | + .iter() |
| 574 | + .find(|n| n.as_str() == name || n.ends_with(&format!("/{name}"))) |
| 575 | + .cloned() |
| 576 | + .ok_or_else(|| format!("the artifact has no {name} (it has: {})", names.join(", ")))?; |
| 577 | + let mut entry = archive |
| 578 | + .by_name(&found) |
| 579 | + .map_err(|e| format!("cannot open {found} in the artifact: {e}"))?; |
| 580 | + if entry.size() > MAX_MEMBER_BYTES { |
| 581 | + return Err(format!("{name} is too large to be a release member")); |
| 582 | + } |
| 583 | + let mut bytes = Vec::new(); |
| 584 | + entry |
| 585 | + .read_to_end(&mut bytes) |
| 586 | + .map_err(|e| format!("cannot read {name} from the artifact: {e}"))?; |
| 587 | + Ok(bytes) |
| 588 | + }; |
| 589 | + let sha256 = entry(&format!("{tarball}.sha256")).and_then(|bytes| { |
| 590 | + String::from_utf8(bytes).map_err(|_| "the sha256 file is not text".to_string()) |
| 591 | + })?; |
| 592 | + Ok(Members { |
| 593 | + tarball: entry(tarball)?, |
| 594 | + sha256, |
| 595 | + }) |
| 596 | +} |
| 597 | + |
| 598 | +/// The tarball's sha256 is the sha256 file's (the first word of it). |
| 599 | +fn verify_sha256(tarball: &[u8], sha256_file: &str) -> Result<(), String> { |
| 600 | + let expected = sha256_file |
| 601 | + .split_whitespace() |
| 602 | + .next() |
| 603 | + .ok_or("the sha256 file is empty")?; |
| 604 | + let got = hex(&Sha256::digest(tarball)); |
| 605 | + if !got.eq_ignore_ascii_case(expected) { |
| 606 | + return Err(format!( |
| 607 | + "the tarball's sha256 differs from the release's ({got} ≠ {expected}); not installing it" |
| 608 | + )); |
| 609 | + } |
| 610 | + Ok(()) |
| 611 | +} |
| 612 | + |
| 613 | +fn sha256_file(path: &Path) -> Result<String, String> { |
| 614 | + let bytes = fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 615 | + Ok(hex(&Sha256::digest(&bytes))) |
| 616 | +} |
| 617 | + |
| 618 | +fn hex(digest: &[u8]) -> String { |
| 619 | + digest.iter().map(|b| format!("{b:02x}")).collect() |
| 620 | +} |
| 621 | + |
| 622 | +/// `tar -xJf` into `dir`: `tar` is on every host the compiler targets |
| 623 | +/// (itself needs a C toolchain), and it reads the xz the release packs. |
| 624 | +fn untar(tarball: &[u8], dir: &Path) -> Result<(), String> { |
| 625 | + fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; |
| 626 | + let mut tar = std::process::Command::new("tar") |
| 627 | + .args(["-xJf", "-", "-C"]) |
| 628 | + .arg(dir) |
| 629 | + .arg("--no-same-owner") |
| 630 | + .stdin(std::process::Stdio::piped()) |
| 631 | + .stdout(std::process::Stdio::null()) |
| 632 | + .spawn() |
| 633 | + .map_err(|e| format!("cannot run tar (is it installed?): {e}"))?; |
| 634 | + let write = tar |
| 635 | + .stdin |
| 636 | + .as_mut() |
| 637 | + .expect("stdin is piped") |
| 638 | + .write_all(tarball); |
| 639 | + let status = tar.wait(); |
| 640 | + match (write, status) { |
| 641 | + (Ok(()), Ok(status)) if status.success() => Ok(()), |
| 642 | + (Err(e), _) => Err(format!("cannot feed tar: {e}")), |
| 643 | + (_, Ok(status)) => Err(format!("tar failed ({status})")), |
| 644 | + (_, Err(e)) => Err(format!("cannot run tar: {e}")), |
| 645 | + } |
| 646 | +} |
| 647 | + |
| 648 | +/// The extracted tarball's one directory, `louise-<tag>-<platform>/`. |
| 649 | +fn find_staged(unpacked: &Path, name: &str) -> Result<PathBuf, String> { |
| 650 | + let staged = unpacked.join(name); |
| 651 | + if staged.is_dir() { |
| 652 | + return Ok(staged); |
| 653 | + } |
| 654 | + // Tolerate the tarball's directory being named otherwise: any one |
| 655 | + // directory holding the members. |
| 656 | + let entries = fs::read_dir(unpacked) |
| 657 | + .map_err(|e| format!("cannot read {}: {e}", unpacked.display()))? |
| 658 | + .collect::<Result<Vec<_>, _>>() |
| 659 | + .map_err(|e| format!("cannot read {}: {e}", unpacked.display()))?; |
| 660 | + match entries.as_slice() { |
| 661 | + [one] if one.path().is_dir() => Ok(one.path()), |
| 662 | + _ => Err(format!("the tarball has no {name}/ directory")), |
| 663 | + } |
| 664 | +} |
| 665 | + |
| 666 | +/// The staged compiler runs and is the release's version: the last check |
| 667 | +/// before anything is replaced. |
| 668 | +fn sanity_check(staged: &Path, wanted: &Version) -> Result<(), String> { |
| 669 | + let binary = staged.join(BINARY); |
| 670 | + if !binary.is_file() { |
| 671 | + return Err(format!("the tarball has no {BINARY}")); |
| 672 | + } |
| 673 | + let out = std::process::Command::new(&binary) |
| 674 | + .arg("--version") |
| 675 | + .output() |
| 676 | + .map_err(|e| format!("the release's louise does not run: {e}"))?; |
| 677 | + if !out.status.success() { |
| 678 | + return Err("the release's louise --version failed".to_string()); |
| 679 | + } |
| 680 | + let reported = String::from_utf8_lossy(&out.stdout); |
| 681 | + let reported = reported |
| 682 | + .trim() |
| 683 | + .strip_prefix("louise ") |
| 684 | + .unwrap_or(reported.trim()); |
| 685 | + match Version::parse(reported) { |
| 686 | + Some(v) if v == *wanted => Ok(()), |
| 687 | + Some(v) => Err(format!( |
| 688 | + "the tarball's louise is {v}, not the tag's {wanted}; not installing it" |
| 689 | + )), |
| 690 | + None => Err(format!( |
| 691 | + "the release's louise --version printed {reported:?}, not a version" |
| 692 | + )), |
| 693 | + } |
| 694 | +} |
| 695 | + |
| 696 | +/// The members `staged` holds that an install would place, in install order. |
| 697 | +fn present_members(staged: &Path) -> Vec<String> { |
| 698 | + ARCHIVES |
| 699 | + .iter() |
| 700 | + .chain(OPTIONAL) |
| 701 | + .chain([&BINARY]) |
| 702 | + .filter(|m| staged.join(m).is_file()) |
| 703 | + .map(|m| m.to_string()) |
| 704 | + .collect() |
| 705 | +} |
| 706 | + |
| 707 | +/// Replace `dir`'s members with `staged`'s: the archives first, the |
| 708 | +/// compiler last (see [`ARCHIVES`]). Every member is checked to be there |
| 709 | +/// before anything moves, and each move is one rename over the old file. |
| 710 | +fn install(staged: &Path, dir: &Path) -> Result<(), String> { |
| 711 | + for member in ARCHIVES.iter().chain([&BINARY]) { |
| 712 | + if !staged.join(member).is_file() { |
| 713 | + return Err(format!("the tarball has no {member}; nothing was replaced")); |
| 714 | + } |
| 715 | + } |
| 716 | + for member in ARCHIVES.iter().chain(OPTIONAL).chain([&BINARY]) { |
| 717 | + let from = staged.join(member); |
| 718 | + if !from.is_file() { |
| 719 | + continue; |
| 720 | + } |
| 721 | + let mode = if *member == BINARY { 0o755 } else { 0o644 }; |
| 722 | + set_mode(&from, mode)?; |
| 723 | + fs::rename(&from, dir.join(member)) |
| 724 | + .map_err(|e| format!("cannot replace {}: {e}", dir.join(member).display()))?; |
| 725 | + } |
| 726 | + Ok(()) |
| 727 | +} |
| 728 | + |
| 729 | +#[cfg(unix)] |
| 730 | +fn set_mode(path: &Path, mode: u32) -> Result<(), String> { |
| 731 | + use std::os::unix::fs::PermissionsExt as _; |
| 732 | + fs::set_permissions(path, fs::Permissions::from_mode(mode)) |
| 733 | + .map_err(|e| format!("cannot set {}'s permissions: {e}", path.display())) |
| 734 | +} |
| 735 | + |
| 736 | +#[cfg(not(unix))] |
| 737 | +fn set_mode(_path: &Path, _mode: u32) -> Result<(), String> { |
| 738 | + Ok(()) |
| 739 | +} |
| 740 | + |
| 741 | +/// The directory the download and extraction happen in, next to the |
| 742 | +/// executable (the renames never cross filesystems); removed on drop, |
| 743 | +/// whatever happened. |
| 744 | +struct Staging(PathBuf); |
| 745 | + |
| 746 | +impl Staging { |
| 747 | + fn new(dir: &Path) -> Result<Staging, String> { |
| 748 | + let path = dir.join(format!(".louise-self-update-{}", std::process::id())); |
| 749 | + if path.exists() { |
| 750 | + fs::remove_dir_all(&path) |
| 751 | + .map_err(|e| format!("cannot clear {}: {e}", path.display()))?; |
| 752 | + } |
| 753 | + fs::create_dir_all(&path).map_err(|e| { |
| 754 | + format!( |
| 755 | + "cannot create {}: {e} (is {} writable?)", |
| 756 | + path.display(), |
| 757 | + dir.display() |
| 758 | + ) |
| 759 | + })?; |
| 760 | + Ok(Staging(path)) |
| 761 | + } |
| 762 | + |
| 763 | + fn path(&self) -> &Path { |
| 764 | + &self.0 |
| 765 | + } |
| 766 | +} |
| 767 | + |
| 768 | +impl Drop for Staging { |
| 769 | + fn drop(&mut self) { |
| 770 | + let _ = fs::remove_dir_all(&self.0); |
| 771 | + } |
| 772 | +} |
| 773 | + |
| 774 | +#[cfg(test)] |
| 775 | +mod tests { |
| 776 | + use super::*; |
| 777 | + |
| 778 | + fn run(number: u64, event: &str, git_ref: &str, state: &str, created_at: &str) -> Run { |
| 779 | + Run { |
| 780 | + number, |
| 781 | + event: event.into(), |
| 782 | + git_ref: git_ref.into(), |
| 783 | + state: state.into(), |
| 784 | + created_at: created_at.into(), |
| 785 | + artifacts: vec![], |
| 786 | + } |
| 787 | + } |
| 788 | + |
| 789 | + #[test] |
| 790 | + fn parses_versions() { |
| 791 | + assert_eq!( |
| 792 | + Version::parse("0.1.0"), |
| 793 | + Some(Version { |
| 794 | + major: 0, |
| 795 | + minor: 1, |
| 796 | + patch: 0 |
| 797 | + }) |
| 798 | + ); |
| 799 | + assert_eq!(Version::parse("v1.20.3"), Version::parse("1.20.3")); |
| 800 | + assert_eq!(Version::parse("0.1"), None); |
| 801 | + assert_eq!(Version::parse("0.1.0-rc.1"), None); |
| 802 | + assert_eq!(Version::parse("0.1.x"), None); |
| 803 | + assert_eq!(Version::parse(""), None); |
| 804 | + } |
| 805 | + |
| 806 | + #[test] |
| 807 | + fn compares_versions() { |
| 808 | + assert!(Version::parse("0.2.0") > Version::parse("0.1.9")); |
| 809 | + assert!(Version::parse("0.1.10") > Version::parse("0.1.9")); |
| 810 | + assert!(Version::parse("1.0.0") > Version::parse("0.99.99")); |
| 811 | + assert_eq!(Version::parse("v0.1.0"), Version::parse("0.1.0")); |
| 812 | + } |
| 813 | + |
| 814 | + #[test] |
| 815 | + fn tags_normalize() { |
| 816 | + assert_eq!(normalize_tag("0.1.0"), "v0.1.0"); |
| 817 | + assert_eq!(normalize_tag("v0.1.0"), "v0.1.0"); |
| 818 | + } |
| 819 | + |
| 820 | + #[test] |
| 821 | + fn picks_the_latest_successful_tag_run() { |
| 822 | + let runs = [ |
| 823 | + run( |
| 824 | + 1, |
| 825 | + "push", |
| 826 | + "refs/tags/v0.1.0", |
| 827 | + "success", |
| 828 | + "2026-10-19T10:00:00Z", |
| 829 | + ), |
| 830 | + run( |
| 831 | + 2, |
| 832 | + "push", |
| 833 | + "refs/tags/v0.2.0", |
| 834 | + "failure", |
| 835 | + "2026-10-19T11:00:00Z", |
| 836 | + ), |
| 837 | + run( |
| 838 | + 3, |
| 839 | + "push", |
| 840 | + "refs/heads/main", |
| 841 | + "success", |
| 842 | + "2026-10-19T12:00:00Z", |
| 843 | + ), |
| 844 | + run( |
| 845 | + 4, |
| 846 | + "pull_request", |
| 847 | + "refs/tags/v0.3.0", |
| 848 | + "success", |
| 849 | + "2026-10-19T13:00:00Z", |
| 850 | + ), |
| 851 | + run( |
| 852 | + 5, |
| 853 | + "push", |
| 854 | + "refs/tags/v0.2.0", |
| 855 | + "success", |
| 856 | + "2026-10-19T14:00:00Z", |
| 857 | + ), |
| 858 | + ]; |
| 859 | + let mut candidates: Vec<&Run> = runs |
| 860 | + .iter() |
| 861 | + .filter(|run| { |
| 862 | + run.event == "push" |
| 863 | + && run.state == "success" |
| 864 | + && tag_of(run).is_some_and(|tag| Version::parse(tag).is_some()) |
| 865 | + }) |
| 866 | + .collect(); |
| 867 | + candidates.sort_by(|a, b| { |
| 868 | + b.created_at |
| 869 | + .cmp(&a.created_at) |
| 870 | + .then(b.number.cmp(&a.number)) |
| 871 | + }); |
| 872 | + assert_eq!(candidates[0].number, 5); |
| 873 | + } |
| 874 | + |
| 875 | + #[test] |
| 876 | + fn picks_the_artifact_named_for_the_platform() { |
| 877 | + let artifact = |name: &str, id: u64| Artifact { |
| 878 | + id, |
| 879 | + name: name.into(), |
| 880 | + size: 1, |
| 881 | + sha256: None, |
| 882 | + }; |
| 883 | + let artifacts = vec![ |
| 884 | + artifact("louise-v0.1.0-aarch64-linux", 1), |
| 885 | + artifact("louise-v0.1.0-x86_64-linux", 2), |
| 886 | + ]; |
| 887 | + let name = format!("louise-{}-{}", "v0.1.0", platform().unwrap()); |
| 888 | + let found = artifacts.into_iter().find(|a| a.name == name).unwrap(); |
| 889 | + assert_eq!(found.id, 2); |
| 890 | + } |
| 891 | + |
| 892 | + #[test] |
| 893 | + fn reads_tob_hosts_toml() { |
| 894 | + let text = r#" |
| 895 | +[hosts."toboggan.cloud"] |
| 896 | +user = "ada" |
| 897 | +token = "toboggan_pat_secret" |
| 898 | + |
| 899 | +[hosts."localhost:8080"] |
| 900 | +user = "ada" |
| 901 | +token = "other" |
| 902 | +protocol = "http" |
| 903 | +"#; |
| 904 | + assert_eq!( |
| 905 | + token_in_hosts_toml(text, "toboggan.cloud").as_deref(), |
| 906 | + Some("toboggan_pat_secret") |
| 907 | + ); |
| 908 | + assert_eq!(token_in_hosts_toml(text, "elsewhere"), None); |
| 909 | + assert_eq!(token_in_hosts_toml("not toml [[", "toboggan.cloud"), None); |
| 910 | + } |
| 911 | + |
| 912 | + #[test] |
| 913 | + fn verifies_sha256_files() { |
| 914 | + // sha256sum of "louise" is what `sha256sum <<< -n` computes. |
| 915 | + let tarball = b"louise"; |
| 916 | + let digest = hex(&Sha256::digest(tarball)); |
| 917 | + let file = format!("{digest} louise-v0.1.0-x86_64-linux.tar.xz\n"); |
| 918 | + assert!(verify_sha256(tarball, &file).is_ok()); |
| 919 | + assert!(verify_sha256(b"other", &file).is_err()); |
| 920 | + assert!(verify_sha256(tarball, "").is_err()); |
| 921 | + } |
| 922 | + |
| 923 | + #[test] |
| 924 | + fn install_replaces_archives_then_the_binary() { |
| 925 | + let dir = std::env::temp_dir().join(format!("louise-install-full-{}", std::process::id())); |
| 926 | + let staged = dir.join("staged"); |
| 927 | + let dest = dir.join("dest"); |
| 928 | + fs::create_dir_all(&staged).unwrap(); |
| 929 | + fs::create_dir_all(&dest).unwrap(); |
| 930 | + // The old install. |
| 931 | + fs::write(dest.join(BINARY), b"old binary").unwrap(); |
| 932 | + for member in ARCHIVES { |
| 933 | + fs::write(dest.join(member), b"old").unwrap(); |
| 934 | + } |
| 935 | + // The staged one, complete with the optional member. |
| 936 | + fs::write(staged.join(BINARY), b"new binary").unwrap(); |
| 937 | + for member in ARCHIVES.iter().chain(OPTIONAL) { |
| 938 | + fs::write(staged.join(member), b"new").unwrap(); |
| 939 | + } |
| 940 | + |
| 941 | + install(&staged, &dest).unwrap(); |
| 942 | + assert_eq!(fs::read(dest.join(BINARY)).unwrap(), b"new binary"); |
| 943 | + for member in ARCHIVES.iter().chain(OPTIONAL) { |
| 944 | + assert_eq!(fs::read(dest.join(member)).unwrap(), b"new", "{member}"); |
| 945 | + } |
| 946 | + #[cfg(unix)] |
| 947 | + { |
| 948 | + use std::os::unix::fs::PermissionsExt as _; |
| 949 | + let mode = |m: &str| fs::metadata(dest.join(m)).unwrap().permissions().mode() & 0o777; |
| 950 | + assert_eq!(mode(BINARY), 0o755); |
| 951 | + assert_eq!(mode(ARCHIVES[0]), 0o644); |
| 952 | + } |
| 953 | + fs::remove_dir_all(&dir).unwrap(); |
| 954 | + } |
| 955 | + |
| 956 | + #[test] |
| 957 | + fn install_refuses_an_incomplete_tarball_without_touching_anything() { |
| 958 | + let dir = |
| 959 | + std::env::temp_dir().join(format!("louise-install-partial-{}", std::process::id())); |
| 960 | + let staged = dir.join("staged"); |
| 961 | + let dest = dir.join("dest"); |
| 962 | + fs::create_dir_all(&staged).unwrap(); |
| 963 | + fs::create_dir_all(&dest).unwrap(); |
| 964 | + fs::write(dest.join(BINARY), b"old binary").unwrap(); |
| 965 | + for member in ARCHIVES { |
| 966 | + fs::write(dest.join(member), b"old").unwrap(); |
| 967 | + } |
| 968 | + // The staged one lacks the binary. |
| 969 | + for member in ARCHIVES { |
| 970 | + fs::write(staged.join(member), b"new").unwrap(); |
| 971 | + } |
| 972 | + assert!(install(&staged, &dest).is_err()); |
| 973 | + assert_eq!(fs::read(dest.join(BINARY)).unwrap(), b"old binary"); |
| 974 | + for member in ARCHIVES { |
| 975 | + assert_eq!(fs::read(dest.join(member)).unwrap(), b"old", "{member}"); |
| 976 | + } |
| 977 | + fs::remove_dir_all(&dir).unwrap(); |
| 978 | + } |
| 979 | + |
| 980 | + /// The whole install path short of the network: a release zip is |
| 981 | + /// built in a temporary directory (the tarball with `tar`, the zip |
| 982 | + /// with the same crate the download path reads), then unzipped, |
| 983 | + /// verified, extracted, sanity-checked and installed. |
| 984 | + #[test] |
| 985 | + fn a_release_zip_installs_end_to_end() { |
| 986 | + if std::process::Command::new("tar") |
| 987 | + .arg("--version") |
| 988 | + .output() |
| 989 | + .is_err() |
| 990 | + { |
| 991 | + return; |
| 992 | + } |
| 993 | + let dir = std::env::temp_dir().join(format!("louise-e2e-{}", std::process::id())); |
| 994 | + let name = "louise-v9.9.9-x86_64-linux"; |
| 995 | + let release = dir.join(name); |
| 996 | + fs::create_dir_all(&release).unwrap(); |
| 997 | + // The "compiler": a script that answers --version as the tag says. |
| 998 | + fs::write(release.join(BINARY), b"#!/bin/sh\necho 'louise 9.9.9'\n").unwrap(); |
| 999 | + set_mode(&release.join(BINARY), 0o755).unwrap(); |
| 1000 | + for member in ARCHIVES.iter().chain(OPTIONAL) { |
| 1001 | + fs::write(release.join(member), b"archive").unwrap(); |
| 1002 | + } |
| 1003 | + let tarball = dir.join(format!("{name}.tar.xz")); |
| 1004 | + let status = std::process::Command::new("tar") |
| 1005 | + .args(["-cJf"]) |
| 1006 | + .arg(&tarball) |
| 1007 | + .arg("-C") |
| 1008 | + .arg(dir.as_os_str()) |
| 1009 | + .arg(name) |
| 1010 | + .status() |
| 1011 | + .unwrap(); |
| 1012 | + assert!(status.success()); |
| 1013 | + let sha256 = format!("{} {name}.tar.xz\n", sha256_file(&tarball).unwrap()); |
| 1014 | + |
| 1015 | + // The artifact zip, as upload-artifact stores it. |
| 1016 | + let zip_path = dir.join("artifact.zip"); |
| 1017 | + let mut zip = zip::ZipWriter::new(fs::File::create(&zip_path).unwrap()); |
| 1018 | + let options = zip::write::SimpleFileOptions::default() |
| 1019 | + .compression_method(zip::CompressionMethod::Deflated); |
| 1020 | + for (entry, bytes) in [ |
| 1021 | + (format!("{name}.tar.xz"), fs::read(&tarball).unwrap()), |
| 1022 | + (format!("{name}.tar.xz.sha256"), sha256.into_bytes()), |
| 1023 | + ] { |
| 1024 | + zip.start_file(entry, options).unwrap(); |
| 1025 | + zip.write_all(&bytes).unwrap(); |
| 1026 | + } |
| 1027 | + zip.finish().unwrap(); |
| 1028 | + |
| 1029 | + let members = unzip(&zip_path, &format!("{name}.tar.xz")).unwrap(); |
| 1030 | + verify_sha256(&members.tarball, &members.sha256).unwrap(); |
| 1031 | + let unpacked = dir.join("unpacked"); |
| 1032 | + untar(&members.tarball, &unpacked).unwrap(); |
| 1033 | + let staged = find_staged(&unpacked, name).unwrap(); |
| 1034 | + sanity_check(&staged, &Version::parse("v9.9.9").unwrap()).unwrap(); |
| 1035 | + // A staged tree whose binary reports another version is refused. |
| 1036 | + fs::write(staged.join(BINARY), b"#!/bin/sh\necho 'louise 9.9.8'\n").unwrap(); |
| 1037 | + assert!(sanity_check(&staged, &Version::parse("v9.9.9").unwrap()).is_err()); |
| 1038 | + fs::write(staged.join(BINARY), b"#!/bin/sh\necho 'louise 9.9.9'\n").unwrap(); |
| 1039 | + |
| 1040 | + let dest = dir.join("dest"); |
| 1041 | + fs::create_dir_all(&dest).unwrap(); |
| 1042 | + fs::write(dest.join(BINARY), b"old").unwrap(); |
| 1043 | + install(&staged, &dest).unwrap(); |
| 1044 | + let out = std::process::Command::new(dest.join(BINARY)) |
| 1045 | + .arg("--version") |
| 1046 | + .output() |
| 1047 | + .unwrap(); |
| 1048 | + assert_eq!( |
| 1049 | + String::from_utf8(out.stdout).unwrap().trim(), |
| 1050 | + "louise 9.9.9" |
| 1051 | + ); |
| 1052 | + assert_eq!( |
| 1053 | + present_members(&dest), |
| 1054 | + vec![ |
| 1055 | + "liblouise_rt.a", |
| 1056 | + "liblouise_rt-fast.a", |
| 1057 | + "liblouise_rt-lto.a", |
| 1058 | + "liblouise_rt-lto.llvm", |
| 1059 | + "louise" |
| 1060 | + ] |
| 1061 | + ); |
| 1062 | + fs::remove_dir_all(&dir).unwrap(); |
| 1063 | + } |
| 1064 | + |
| 1065 | + /// Against the real forge, read-only: the discovery path over HTTPS, |
| 1066 | + /// the token from tob's config, and MessagePack decoding. Run it with |
| 1067 | + /// |
| 1068 | + /// ```sh |
| 1069 | + /// cargo test -p louise -- --ignored live_discovery |
| 1070 | + /// ``` |
| 1071 | + /// |
| 1072 | + /// `LOUISE_UPDATE_REPO=gabla108/toboggan LOUISE_UPDATE_WORKFLOW=ci.yml` |
| 1073 | + /// points it at runs that exist before louise's first tag. |
| 1074 | + #[test] |
| 1075 | + #[ignore] |
| 1076 | + fn live_discovery() { |
| 1077 | + let targets = Targets::from_env(); |
| 1078 | + let client = Client::new(&targets.host, token(&targets.host)).unwrap(); |
| 1079 | + let runs: Runs = client |
| 1080 | + .get( |
| 1081 | + &format!("/{}/actions", targets.repo), |
| 1082 | + &[("workflow", targets.workflow.clone())], |
| 1083 | + ) |
| 1084 | + .unwrap(); |
| 1085 | + eprintln!( |
| 1086 | + "{}/{}: {} run(s), more={}", |
| 1087 | + targets.host, |
| 1088 | + targets.repo, |
| 1089 | + runs.runs.len(), |
| 1090 | + runs.more |
| 1091 | + ); |
| 1092 | + for run in &runs.runs { |
| 1093 | + eprintln!( |
| 1094 | + " #{} {} {} {} {}", |
| 1095 | + run.number, run.event, run.git_ref, run.state, run.created_at |
| 1096 | + ); |
| 1097 | + } |
| 1098 | + if let Some(first) = runs.runs.first() { |
| 1099 | + let full: Run = client |
| 1100 | + .get( |
| 1101 | + &format!("/{}/actions/runs/{}", targets.repo, first.number), |
| 1102 | + &[], |
| 1103 | + ) |
| 1104 | + .unwrap(); |
| 1105 | + for artifact in &full.artifacts { |
| 1106 | + eprintln!( |
| 1107 | + " artifact #{} {} ({} bytes, sha256 {:?})", |
| 1108 | + artifact.id, artifact.name, artifact.size, artifact.sha256 |
| 1109 | + ); |
| 1110 | + } |
| 1111 | + } |
| 1112 | + } |
| 1113 | + |
| 1114 | + /// The download path, read-only, against the artifact |
| 1115 | + /// `LOUISE_UPDATE_TEST_RUN`/`LOUISE_UPDATE_TEST_ARTIFACT` name (e.g. |
| 1116 | + /// tob's own: `85`/`249`), into a temporary file whose size and |
| 1117 | + /// sha256 are checked against the server's. |
| 1118 | + #[test] |
| 1119 | + #[ignore] |
| 1120 | + fn live_download() { |
| 1121 | + let (Ok(run), Ok(id)) = ( |
| 1122 | + std::env::var("LOUISE_UPDATE_TEST_RUN").map(|v| v.parse::<u64>().unwrap()), |
| 1123 | + std::env::var("LOUISE_UPDATE_TEST_ARTIFACT").map(|v| v.parse::<u64>().unwrap()), |
| 1124 | + ) else { |
| 1125 | + eprintln!("set LOUISE_UPDATE_TEST_RUN and LOUISE_UPDATE_TEST_ARTIFACT"); |
| 1126 | + return; |
| 1127 | + }; |
| 1128 | + let targets = Targets::from_env(); |
| 1129 | + let client = Client::new(&targets.host, token(&targets.host)).unwrap(); |
| 1130 | + let full: Run = client |
| 1131 | + .get(&format!("/{}/actions/runs/{run}", targets.repo), &[]) |
| 1132 | + .unwrap(); |
| 1133 | + let artifact = full.artifacts.iter().find(|a| a.id == id).unwrap(); |
| 1134 | + let dest = |
| 1135 | + std::env::temp_dir().join(format!("louise-live-download-{}", std::process::id())); |
| 1136 | + let release = Release { |
| 1137 | + tag: "test".into(), |
| 1138 | + run, |
| 1139 | + artifact: artifact.clone(), |
| 1140 | + }; |
| 1141 | + let size = client |
| 1142 | + .download(&release.download_path(&targets), &dest) |
| 1143 | + .unwrap(); |
| 1144 | + assert_eq!(size, artifact.size, "the byte count is the server's"); |
| 1145 | + if let Some(expected) = &artifact.sha256 { |
| 1146 | + assert_eq!(&sha256_file(&dest).unwrap(), expected); |
| 1147 | + eprintln!("sha256 matches: {expected}"); |
| 1148 | + } |
| 1149 | + eprintln!("{}: {} bytes to {}", artifact.name, size, dest.display()); |
| 1150 | + fs::remove_file(&dest).unwrap(); |
| 1151 | + } |
| 1152 | +} |