| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
use crate::config::Config; |
| 16 |
use crate::domain::{AppId, Status, Step, StepRunId, Target, Version}; |
| 17 |
use crate::events::{self, Event, EventTx}; |
| 18 |
use crate::ota::{OtaRegistry, PublishAuthority, Release}; |
| 19 |
use crate::state::ExecutorMap; |
| 20 |
use crate::topology::{DeployTarget, Kind}; |
| 21 |
use anyhow::{Context as _, Result}; |
| 22 |
use ops_core::live_log::LiveLog; |
| 23 |
use ops_exec::{Action, Executor, ObserveKind, Step as OpStep, SyncOpts}; |
| 24 |
use rhai::{Engine, EvalAltResult, Map}; |
| 25 |
use sha2::{Digest, Sha256}; |
| 26 |
use sqlx::SqlitePool; |
| 27 |
use std::collections::HashMap; |
| 28 |
use std::path::{Path, PathBuf}; |
| 29 |
use std::sync::atomic::{AtomicBool, Ordering}; |
| 30 |
use std::sync::{Arc, Mutex}; |
| 31 |
use tokio::runtime::Handle; |
| 32 |
use tokio::sync::Mutex as AsyncMutex; |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
fn action_for(step: Step, kind: Kind) -> Action { |
| 49 |
match step { |
| 50 |
Step::Checkout | Step::Prebuild | Step::Build => Action::Build, |
| 51 |
Step::Sign => Action::Sign, |
| 52 |
Step::Notarize => Action::Notarize, |
| 53 |
Step::Staple => Action::Staple, |
| 54 |
Step::Package => Action::Package, |
| 55 |
Step::Verify => match kind { |
| 56 |
Kind::App => Action::Observe(ObserveKind::Custom("gatekeeper".into())), |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
Kind::Library | Kind::Service => Action::Build, |
| 61 |
}, |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
Step::Publish | Step::Collect | Step::Handoff => Action::Package, |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
Step::Deploy => Action::Deploy, |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
struct StepState { |
| 80 |
run_id: StepRunId, |
| 81 |
step: Step, |
| 82 |
log: Arc<AsyncMutex<LiveLog>>, |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
failed: bool, |
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
deadline: std::time::Instant, |
| 94 |
} |
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
fn default_step_budget(step: Step) -> std::time::Duration { |
| 103 |
use std::time::Duration; |
| 104 |
let mins = match step { |
| 105 |
Step::Checkout => 10, |
| 106 |
|
| 107 |
Step::Prebuild => 45, |
| 108 |
|
| 109 |
Step::Build => 90, |
| 110 |
Step::Sign => 15, |
| 111 |
|
| 112 |
Step::Notarize => 60, |
| 113 |
Step::Staple => 10, |
| 114 |
Step::Package => 30, |
| 115 |
Step::Verify => 10, |
| 116 |
|
| 117 |
Step::Collect => 30, |
| 118 |
Step::Publish => 20, |
| 119 |
|
| 120 |
|
| 121 |
Step::Deploy => 15, |
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
Step::Handoff => 30, |
| 126 |
}; |
| 127 |
Duration::from_secs(mins * 60) |
| 128 |
} |
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
pub const DEPLOY_STAGING_ROOT: &str = "/var/tmp/bento-deploy"; |
| 140 |
|
| 141 |
|
| 142 |
pub struct RecipeCtx { |
| 143 |
pub app: AppId, |
| 144 |
pub version: Version, |
| 145 |
pub target: Target, |
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
pub build_host: String, |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
pub build_host_ssh: String, |
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
pub tag: String, |
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
pub repo: String, |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
pub repo_by_host: HashMap<String, String>, |
| 170 |
|
| 171 |
|
| 172 |
pub features: Vec<String>, |
| 173 |
|
| 174 |
|
| 175 |
pub kind: Kind, |
| 176 |
pub target_run_id: i64, |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
pub execs: Arc<ExecutorMap>, |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
pub syncs: Arc<ExecutorMap>, |
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
pub deploy: Option<DeployTarget>, |
| 194 |
pub pool: SqlitePool, |
| 195 |
pub events: EventTx, |
| 196 |
pub cfg: Arc<Config>, |
| 197 |
pub ota: Arc<OtaRegistry>, |
| 198 |
pub rt: Handle, |
| 199 |
current: Mutex<Option<StepState>>, |
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
gatekeeper_ok: Mutex<Option<bool>>, |
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
failed_steps: Mutex<Vec<Step>>, |
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
cancel: Arc<AtomicBool>, |
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
all_green_required: Option<Vec<Target>>, |
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
artifact_hashes: Mutex<HashMap<String, String>>, |
| 223 |
} |
| 224 |
|
| 225 |
impl RecipeCtx { |
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
fn published_versions(name: &str) -> Vec<String> { |
| 231 |
let url = format!("https://crates.io/api/v1/crates/{name}"); |
| 232 |
let Ok(out) = std::process::Command::new("curl") |
| 233 |
.args([ |
| 234 |
"-sS", |
| 235 |
"--max-time", |
| 236 |
"15", |
| 237 |
"-H", |
| 238 |
"User-Agent: bento-preflight", |
| 239 |
&url, |
| 240 |
]) |
| 241 |
.output() |
| 242 |
else { |
| 243 |
return Vec::new(); |
| 244 |
}; |
| 245 |
let Ok(v) = serde_json::from_slice::<serde_json::Value>(&out.stdout) else { |
| 246 |
return Vec::new(); |
| 247 |
}; |
| 248 |
v.get("versions") |
| 249 |
.and_then(|x| x.as_array()) |
| 250 |
.map(|a| { |
| 251 |
a.iter() |
| 252 |
.filter_map(|x| x.get("num").and_then(|n| n.as_str()).map(str::to_string)) |
| 253 |
.collect() |
| 254 |
}) |
| 255 |
.unwrap_or_default() |
| 256 |
} |
| 257 |
|
| 258 |
#[allow(clippy::too_many_arguments)] |
| 259 |
pub fn new( |
| 260 |
app: AppId, |
| 261 |
version: Version, |
| 262 |
target: Target, |
| 263 |
build_host: String, |
| 264 |
build_host_ssh: String, |
| 265 |
tag: String, |
| 266 |
repo: String, |
| 267 |
features: Vec<String>, |
| 268 |
kind: Kind, |
| 269 |
target_run_id: i64, |
| 270 |
execs: Arc<ExecutorMap>, |
| 271 |
syncs: Arc<ExecutorMap>, |
| 272 |
deploy: Option<DeployTarget>, |
| 273 |
pool: SqlitePool, |
| 274 |
events: EventTx, |
| 275 |
cfg: Arc<Config>, |
| 276 |
ota: Arc<OtaRegistry>, |
| 277 |
rt: Handle, |
| 278 |
cancel: Arc<AtomicBool>, |
| 279 |
all_green_required: Option<Vec<Target>>, |
| 280 |
) -> Self { |
| 281 |
Self { |
| 282 |
app, |
| 283 |
version, |
| 284 |
target, |
| 285 |
build_host, |
| 286 |
build_host_ssh, |
| 287 |
tag, |
| 288 |
repo, |
| 289 |
repo_by_host: HashMap::new(), |
| 290 |
features, |
| 291 |
kind, |
| 292 |
target_run_id, |
| 293 |
execs, |
| 294 |
syncs, |
| 295 |
deploy, |
| 296 |
pool, |
| 297 |
events, |
| 298 |
cfg, |
| 299 |
ota, |
| 300 |
rt, |
| 301 |
current: Mutex::new(None), |
| 302 |
gatekeeper_ok: Mutex::new(None), |
| 303 |
failed_steps: Mutex::new(Vec::new()), |
| 304 |
cancel, |
| 305 |
all_green_required, |
| 306 |
artifact_hashes: Mutex::new(HashMap::new()), |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
#[must_use] |
| 316 |
pub fn with_repo_by_host(mut self, repo_by_host: HashMap<String, String>) -> Self { |
| 317 |
self.repo_by_host = repo_by_host; |
| 318 |
self |
| 319 |
} |
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
pub fn repo_for(&self, host: &str) -> &str { |
| 326 |
self.repo_by_host |
| 327 |
.get(host) |
| 328 |
.map_or(self.repo.as_str(), String::as_str) |
| 329 |
} |
| 330 |
|
| 331 |
|
| 332 |
fn is_cancelled(&self) -> bool { |
| 333 |
self.cancel.load(Ordering::SeqCst) |
| 334 |
} |
| 335 |
|
| 336 |
fn now() -> String { |
| 337 |
chrono::Utc::now().to_rfc3339() |
| 338 |
} |
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
fn log_path(&self, step: Step, run_id: StepRunId) -> PathBuf { |
| 349 |
self.log_dir() |
| 350 |
.join(format!("{}.{}.log", step.as_str(), run_id.0)) |
| 351 |
} |
| 352 |
|
| 353 |
|
| 354 |
fn log_dir(&self) -> PathBuf { |
| 355 |
let target_dir = self.target.to_string().replace('/', "-"); |
| 356 |
self.cfg |
| 357 |
.logs_root |
| 358 |
.join(self.app.as_str()) |
| 359 |
.join(self.version.to_string()) |
| 360 |
.join(target_dir) |
| 361 |
} |
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
fn begin_step(self: &Arc<Self>, step: Step) -> Result<()> { |
| 366 |
anyhow::ensure!( |
| 367 |
!self.is_cancelled(), |
| 368 |
"build superseded by a newer request; aborting before `{}`", |
| 369 |
step.as_str() |
| 370 |
); |
| 371 |
self.finish_step(Status::Ok)?; |
| 372 |
let me = self.clone(); |
| 373 |
let started = Self::now(); |
| 374 |
let started_for_header = started.clone(); |
| 375 |
let run_id = self.rt.block_on(async move { |
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
let mut tx = me.pool.begin().await.context("begin step tx")?; |
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
let id: i64 = sqlx::query_scalar( |
| 384 |
"INSERT INTO step_runs (target_run_id, step, status, started_at) |
| 385 |
VALUES (?, ?, 'running', ?) RETURNING id", |
| 386 |
) |
| 387 |
.bind(me.target_run_id) |
| 388 |
.bind(step.as_str()) |
| 389 |
.bind(&started) |
| 390 |
.fetch_one(&mut *tx) |
| 391 |
.await |
| 392 |
.context("insert step_run")?; |
| 393 |
let log_ref = me |
| 394 |
.log_path(step, StepRunId(id)) |
| 395 |
.to_string_lossy() |
| 396 |
.into_owned(); |
| 397 |
sqlx::query("UPDATE step_runs SET log_ref = ? WHERE id = ?") |
| 398 |
.bind(&log_ref) |
| 399 |
.bind(id) |
| 400 |
.execute(&mut *tx) |
| 401 |
.await |
| 402 |
.context("set step_run log_ref")?; |
| 403 |
sqlx::query("UPDATE target_runs SET current_step = ? WHERE id = ?") |
| 404 |
.bind(step.as_str()) |
| 405 |
.bind(me.target_run_id) |
| 406 |
.execute(&mut *tx) |
| 407 |
.await |
| 408 |
.context("update current_step")?; |
| 409 |
tx.commit().await.context("commit step tx")?; |
| 410 |
anyhow::Ok(StepRunId(id)) |
| 411 |
})?; |
| 412 |
|
| 413 |
|
| 414 |
let events = self.events.clone(); |
| 415 |
let cb_run_id = run_id; |
| 416 |
let mut log = self.rt.block_on(LiveLog::open( |
| 417 |
self.log_path(step, run_id), |
| 418 |
Box::new(move |seq, text| { |
| 419 |
events::emit( |
| 420 |
&events, |
| 421 |
Event::StepLogChunk { |
| 422 |
run_id: cb_run_id, |
| 423 |
seq, |
| 424 |
text: text.to_string(), |
| 425 |
}, |
| 426 |
); |
| 427 |
}), |
| 428 |
)); |
| 429 |
|
| 430 |
events::emit( |
| 431 |
&self.events, |
| 432 |
Event::StepStart { |
| 433 |
run_id, |
| 434 |
app: self.app.clone(), |
| 435 |
version: self.version.clone(), |
| 436 |
target: self.target, |
| 437 |
step, |
| 438 |
}, |
| 439 |
); |
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
let header = format!( |
| 447 |
"=== bento {app} {version} {target} step={step} run_id={run_id} started={started_for_header} ===\n", |
| 448 |
app = self.app.as_str(), |
| 449 |
version = self.version, |
| 450 |
target = self.target, |
| 451 |
step = step.as_str(), |
| 452 |
); |
| 453 |
self.rt.block_on(async { |
| 454 |
use ops_core::remote::LogSink as _; |
| 455 |
log.write_chunk(header.as_bytes()).await; |
| 456 |
}); |
| 457 |
|
| 458 |
*self.current.lock().unwrap() = Some(StepState { |
| 459 |
run_id, |
| 460 |
step, |
| 461 |
log: Arc::new(AsyncMutex::new(log)), |
| 462 |
failed: false, |
| 463 |
deadline: std::time::Instant::now() + self.step_budget(step), |
| 464 |
}); |
| 465 |
Ok(()) |
| 466 |
} |
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
fn step_budget(&self, step: Step) -> std::time::Duration { |
| 471 |
self.cfg |
| 472 |
.step_timeout_secs |
| 473 |
.map_or_else(|| default_step_budget(step), std::time::Duration::from_secs) |
| 474 |
} |
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
fn step_deadline(&self) -> std::time::Instant { |
| 480 |
self.current.lock().unwrap().as_ref().map_or_else( |
| 481 |
|| std::time::Instant::now() + self.step_budget(Step::Build), |
| 482 |
|s| s.deadline, |
| 483 |
) |
| 484 |
} |
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
fn run_bounded<F, T>(&self, what: &str, fut: F) -> Result<T> |
| 493 |
where |
| 494 |
F: std::future::Future<Output = Result<T>>, |
| 495 |
{ |
| 496 |
let deadline = self.step_deadline(); |
| 497 |
let cancel = self.cancel.clone(); |
| 498 |
self.rt.block_on(async move { |
| 499 |
tokio::pin!(fut); |
| 500 |
let watch = async { |
| 501 |
|
| 502 |
|
| 503 |
while !cancel.load(Ordering::SeqCst) { |
| 504 |
tokio::time::sleep(std::time::Duration::from_millis(250)).await; |
| 505 |
} |
| 506 |
}; |
| 507 |
tokio::select! { |
| 508 |
r = &mut fut => r, |
| 509 |
() = tokio::time::sleep_until(deadline.into()) => { |
| 510 |
Err(anyhow::anyhow!("`{what}` exceeded its per-step deadline")) |
| 511 |
} |
| 512 |
() = watch => { |
| 513 |
Err(anyhow::anyhow!("build superseded by a newer request; aborting `{what}`")) |
| 514 |
} |
| 515 |
} |
| 516 |
}) |
| 517 |
} |
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
fn fail_current_step(&self) { |
| 523 |
if let Some(st) = self.current.lock().unwrap().as_mut() { |
| 524 |
st.failed = true; |
| 525 |
} |
| 526 |
} |
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
pub fn finish_step(self: &Arc<Self>, status: Status) -> Result<()> { |
| 533 |
let st = self.current.lock().unwrap().take(); |
| 534 |
let Some(st) = st else { return Ok(()) }; |
| 535 |
let status = if st.failed { Status::Failed } else { status }; |
| 536 |
if status == Status::Failed { |
| 537 |
self.failed_steps.lock().unwrap().push(st.step); |
| 538 |
} |
| 539 |
let me = self.clone(); |
| 540 |
self.rt.block_on(async move { |
| 541 |
|
| 542 |
if let Ok(m) = Arc::try_unwrap(st.log) { |
| 543 |
m.into_inner().close().await; |
| 544 |
} |
| 545 |
if let Err(e) = sqlx::query( |
| 546 |
"UPDATE step_runs SET status = ?, finished_at = ? WHERE id = ?", |
| 547 |
) |
| 548 |
.bind(status.as_str()) |
| 549 |
.bind(Self::now()) |
| 550 |
.bind(st.run_id.0) |
| 551 |
.execute(&me.pool) |
| 552 |
.await |
| 553 |
{ |
| 554 |
tracing::error!(step = st.step.as_str(), error = %e, "could not stamp step_run status"); |
| 555 |
} |
| 556 |
}); |
| 557 |
events::emit( |
| 558 |
&self.events, |
| 559 |
Event::StepDone { |
| 560 |
run_id: st.run_id, |
| 561 |
app: self.app.clone(), |
| 562 |
target: self.target, |
| 563 |
step: st.step, |
| 564 |
status, |
| 565 |
}, |
| 566 |
); |
| 567 |
Ok(()) |
| 568 |
} |
| 569 |
|
| 570 |
|
| 571 |
|
| 572 |
fn ensure_step(self: &Arc<Self>) -> Result<Arc<AsyncMutex<LiveLog>>> { |
| 573 |
if self.current.lock().unwrap().is_none() { |
| 574 |
self.begin_step(Step::Build)?; |
| 575 |
} |
| 576 |
Ok(self.current.lock().unwrap().as_ref().unwrap().log.clone()) |
| 577 |
} |
| 578 |
|
| 579 |
|
| 580 |
|
| 581 |
pub fn current_step(&self) -> Step { |
| 582 |
self.current |
| 583 |
.lock() |
| 584 |
.unwrap() |
| 585 |
.as_ref() |
| 586 |
.map_or(Step::Build, |s| s.step) |
| 587 |
} |
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
fn exec(&self, name: &str) -> Result<Arc<dyn ops_exec::Executor>> { |
| 592 |
self.execs |
| 593 |
.get(name) |
| 594 |
.cloned() |
| 595 |
.ok_or_else(|| anyhow::anyhow!("unknown build host `{name}` (not in topology)")) |
| 596 |
} |
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
fn host_sync(&self, name: &str) -> Result<Arc<dyn Executor>> { |
| 603 |
self.syncs |
| 604 |
.get(name) |
| 605 |
.cloned() |
| 606 |
.ok_or_else(|| anyhow::anyhow!("unknown build host `{name}` (not in topology)")) |
| 607 |
} |
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
fn run(self: &Arc<Self>, host: &str, cmd: &str) -> Result<(i32, String)> { |
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
|
| 620 |
let action = match &self.deploy { |
| 621 |
Some(d) if d.host == host => Action::Deploy, |
| 622 |
_ => action_for(self.current_step(), self.kind), |
| 623 |
}; |
| 624 |
self.run_as(host, cmd, action) |
| 625 |
} |
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
fn run_as(self: &Arc<Self>, host: &str, cmd: &str, action: Action) -> Result<(i32, String)> { |
| 630 |
let sink = self.ensure_step()?; |
| 631 |
let exec = self.exec(host)?; |
| 632 |
let cur = self.current_step(); |
| 633 |
let step = OpStep::shell(action, cmd.to_string()); |
| 634 |
|
| 635 |
|
| 636 |
|
| 637 |
|
| 638 |
let echo = format!("$ [{host}] {cmd}\n"); |
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
let label = format!("{cur} command on `{host}`"); |
| 643 |
let out = self.run_bounded(&label, async move { |
| 644 |
use ops_core::remote::LogSink as _; |
| 645 |
let mut guard = sink.lock().await; |
| 646 |
guard.write_chunk(echo.as_bytes()).await; |
| 647 |
exec.run_streaming(&step, &mut *guard).await |
| 648 |
})?; |
| 649 |
let code = out.status.code().unwrap_or(-1); |
| 650 |
let stdout = String::from_utf8_lossy(&out.stdout); |
| 651 |
let tail: String = stdout |
| 652 |
.chars() |
| 653 |
.rev() |
| 654 |
.take(2000) |
| 655 |
.collect::<Vec<_>>() |
| 656 |
.into_iter() |
| 657 |
.rev() |
| 658 |
.collect(); |
| 659 |
Ok((code, tail)) |
| 660 |
} |
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
fn checkout_sha(self: &Arc<Self>, host: &str) -> Result<String> { |
| 674 |
|
| 675 |
|
| 676 |
let repo = self.repo_for(host).to_string(); |
| 677 |
|
| 678 |
|
| 679 |
|
| 680 |
let _ = self.run(host, &git_fetch_cmd(&repo))?; |
| 681 |
let (code, err) = self.run(host, &git_worktree_pin_cmd(&repo, &self.tag))?; |
| 682 |
if code != 0 { |
| 683 |
let (probe, _) = self.run(host, &git_tag_exists_cmd(&repo, &self.tag))?; |
| 684 |
anyhow::bail!( |
| 685 |
"checkout of {} failed on `{host}`: {}", |
| 686 |
self.tag, |
| 687 |
worktree_failure_reason(&self.tag, probe == 0, &err) |
| 688 |
); |
| 689 |
} |
| 690 |
let (code, tail) = self.run(host, &git_rev_parse_cmd(&repo))?; |
| 691 |
anyhow::ensure!(code == 0, "rev-parse failed on `{host}`"); |
| 692 |
Ok(tail.trim().to_string()) |
| 693 |
} |
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
|
| 698 |
|
| 699 |
pub fn artifact_hashes(&self) -> HashMap<String, String> { |
| 700 |
self.artifact_hashes.lock().unwrap().clone() |
| 701 |
} |
| 702 |
|
| 703 |
|
| 704 |
|
| 705 |
|
| 706 |
|
| 707 |
|
| 708 |
fn resolve_artifact( |
| 709 |
self: &Arc<Self>, |
| 710 |
host: &str, |
| 711 |
glob: &str, |
| 712 |
required: bool, |
| 713 |
) -> Result<String> { |
| 714 |
ensure_glob_safe(glob)?; |
| 715 |
|
| 716 |
|
| 717 |
let cmd = format!("for __f in {glob}; do [ -e \"$__f\" ] && printf '%s\\n' \"$__f\"; done"); |
| 718 |
let (code, tail) = self.run(host, &cmd)?; |
| 719 |
anyhow::ensure!( |
| 720 |
code == 0, |
| 721 |
"resolving artifact glob `{glob}` on `{host}` exited {code}" |
| 722 |
); |
| 723 |
resolve_artifact_match(&tail, glob, required) |
| 724 |
} |
| 725 |
} |
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
#[allow( |
| 732 |
clippy::unnecessary_box_returns, |
| 733 |
reason = "rhai's error type is used boxed throughout its host-function API" |
| 734 |
)] |
| 735 |
fn rhai_err(e: impl std::fmt::Display) -> Box<EvalAltResult> { |
| 736 |
Box::new(EvalAltResult::ErrorRuntime( |
| 737 |
e.to_string().into(), |
| 738 |
rhai::Position::NONE, |
| 739 |
)) |
| 740 |
} |
| 741 |
|
| 742 |
|
| 743 |
#[derive(Debug, Clone)] |
| 744 |
pub struct CrateMeta { |
| 745 |
pub name: String, |
| 746 |
pub version: String, |
| 747 |
pub repository: Option<String>, |
| 748 |
pub description: Option<String>, |
| 749 |
pub licensed: bool, |
| 750 |
} |
| 751 |
|
| 752 |
|
| 753 |
pub fn crate_meta_from_json(raw: &str) -> Result<CrateMeta> { |
| 754 |
let v: serde_json::Value = serde_json::from_str(raw).context("parsing cargo metadata")?; |
| 755 |
let p = v |
| 756 |
.get("packages") |
| 757 |
.and_then(|p| p.as_array()) |
| 758 |
.and_then(|a| a.first()) |
| 759 |
.context("cargo metadata reported no package")?; |
| 760 |
let str_field = |k: &str| { |
| 761 |
p.get(k) |
| 762 |
.and_then(|x| x.as_str()) |
| 763 |
.filter(|s| !s.is_empty()) |
| 764 |
.map(str::to_string) |
| 765 |
}; |
| 766 |
Ok(CrateMeta { |
| 767 |
name: str_field("name").context("package has no name")?, |
| 768 |
version: str_field("version").context("package has no version")?, |
| 769 |
repository: str_field("repository"), |
| 770 |
description: str_field("description"), |
| 771 |
licensed: str_field("license").is_some() || str_field("license_file").is_some(), |
| 772 |
}) |
| 773 |
} |
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
pub fn crate_publish_problems( |
| 781 |
meta: &CrateMeta, |
| 782 |
repo_clonable: bool, |
| 783 |
published: &[String], |
| 784 |
credentials_present: bool, |
| 785 |
) -> Vec<String> { |
| 786 |
let mut out = Vec::new(); |
| 787 |
if !credentials_present { |
| 788 |
out.push( |
| 789 |
"no crates.io credentials on the publishing host: `cargo login` there first. \ |
| 790 |
Checked now rather than at the upload, so this fails in seconds instead of \ |
| 791 |
after a full build and verify." |
| 792 |
.to_string(), |
| 793 |
); |
| 794 |
} |
| 795 |
match &meta.repository { |
| 796 |
None => out.push( |
| 797 |
"no `repository` field: the crates.io page will show no source link, permanently" |
| 798 |
.to_string(), |
| 799 |
), |
| 800 |
Some(url) if !repo_clonable => out.push(format!( |
| 801 |
"`repository` is not publicly clonable: {url} \ |
| 802 |
(wrong URL, or the repo is private)" |
| 803 |
)), |
| 804 |
Some(_) => {} |
| 805 |
} |
| 806 |
if meta.description.is_none() { |
| 807 |
out.push("no `description`: crates.io requires one".to_string()); |
| 808 |
} |
| 809 |
if !meta.licensed { |
| 810 |
out.push("no `license` or `license-file`".to_string()); |
| 811 |
} |
| 812 |
if published.iter().any(|v| v == &meta.version) { |
| 813 |
out.push(format!( |
| 814 |
"version {} is already published; bump it", |
| 815 |
meta.version |
| 816 |
)); |
| 817 |
} |
| 818 |
out |
| 819 |
} |
| 820 |
|
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
|
| 826 |
pub fn version_from_repo(repo: &str, version_path: Option<&str>) -> Result<Version> { |
| 827 |
let root = expand_tilde(repo); |
| 828 |
if let Some(vp) = version_path { |
| 829 |
let path = root.join(vp); |
| 830 |
let raw = std::fs::read_to_string(&path) |
| 831 |
.with_context(|| format!("reading version file {}", path.display()))?; |
| 832 |
let ver = if std::path::Path::new(vp) |
| 833 |
.extension() |
| 834 |
.is_some_and(|e| e.eq_ignore_ascii_case("json")) |
| 835 |
{ |
| 836 |
version_from_tauri_json(&raw)? |
| 837 |
} else { |
| 838 |
version_from_cargo_toml(&raw)? |
| 839 |
}; |
| 840 |
return Version::parse(&ver).map_err(|e| anyhow::anyhow!(e)); |
| 841 |
} |
| 842 |
let tauri_conf = root.join("src-tauri").join("tauri.conf.json"); |
| 843 |
if tauri_conf.exists() { |
| 844 |
let raw = std::fs::read_to_string(&tauri_conf) |
| 845 |
.with_context(|| format!("reading {}", tauri_conf.display()))?; |
| 846 |
return Version::parse(&version_from_tauri_json(&raw)?).map_err(|e| anyhow::anyhow!(e)); |
| 847 |
} |
| 848 |
let cargo_toml = root.join("Cargo.toml"); |
| 849 |
let raw = std::fs::read_to_string(&cargo_toml).with_context(|| { |
| 850 |
format!( |
| 851 |
"reading {} (no tauri.conf.json either)", |
| 852 |
cargo_toml.display() |
| 853 |
) |
| 854 |
})?; |
| 855 |
Version::parse(&version_from_cargo_toml(&raw)?).map_err(|e| anyhow::anyhow!(e)) |
| 856 |
} |
| 857 |
|
| 858 |
|
| 859 |
fn version_from_tauri_json(raw: &str) -> Result<String> { |
| 860 |
let v: serde_json::Value = serde_json::from_str(raw).context("parsing tauri.conf.json")?; |
| 861 |
v.get("version") |
| 862 |
.and_then(|x| x.as_str()) |
| 863 |
.map(str::to_owned) |
| 864 |
.context("no `version` in tauri.conf.json") |
| 865 |
} |
| 866 |
|
| 867 |
|
| 868 |
|
| 869 |
fn version_from_cargo_toml(raw: &str) -> Result<String> { |
| 870 |
let doc: toml::Value = toml::from_str(raw).context("parsing Cargo.toml")?; |
| 871 |
doc.get("package") |
| 872 |
.and_then(|p| p.get("version")) |
| 873 |
.or_else(|| { |
| 874 |
doc.get("workspace") |
| 875 |
.and_then(|w| w.get("package")) |
| 876 |
.and_then(|p| p.get("version")) |
| 877 |
}) |
| 878 |
.and_then(|v| v.as_str()) |
| 879 |
.map(str::to_owned) |
| 880 |
.context("no `[package].version` or `[workspace.package].version` in Cargo.toml") |
| 881 |
} |
| 882 |
|
| 883 |
|
| 884 |
|
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
|
| 892 |
|
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
pub fn check_version_consistency( |
| 898 |
repo: &str, |
| 899 |
version_path: Option<&str>, |
| 900 |
expected: &Version, |
| 901 |
) -> Result<()> { |
| 902 |
let root = expand_tilde(repo); |
| 903 |
let mut sources: Vec<(String, String)> = Vec::new(); |
| 904 |
for rel in version_sources(version_path) { |
| 905 |
let path = root.join(&rel); |
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
match std::fs::read_to_string(&path) { |
| 910 |
Ok(raw) => sources.push((rel, raw)), |
| 911 |
Err(e) if version_path == Some(rel.as_str()) => { |
| 912 |
return Err(e).with_context(|| format!("reading version file {}", path.display())); |
| 913 |
} |
| 914 |
Err(_) => {} |
| 915 |
} |
| 916 |
} |
| 917 |
versions_agree(repo, &sources, version_path, expected) |
| 918 |
} |
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
pub fn version_sources(version_path: Option<&str>) -> Vec<String> { |
| 926 |
let mut rels: Vec<String> = version_path.into_iter().map(str::to_string).collect(); |
| 927 |
for conventional in ["src-tauri/tauri.conf.json", "Cargo.toml"] { |
| 928 |
if version_path != Some(conventional) { |
| 929 |
rels.push(conventional.to_string()); |
| 930 |
} |
| 931 |
} |
| 932 |
rels |
| 933 |
} |
| 934 |
|
| 935 |
|
| 936 |
|
| 937 |
|
| 938 |
|
| 939 |
|
| 940 |
|
| 941 |
|
| 942 |
|
| 943 |
|
| 944 |
|
| 945 |
pub fn versions_agree( |
| 946 |
where_: &str, |
| 947 |
sources: &[(String, String)], |
| 948 |
version_path: Option<&str>, |
| 949 |
expected: &Version, |
| 950 |
) -> Result<()> { |
| 951 |
let mut found: Vec<(String, Version)> = Vec::new(); |
| 952 |
for (rel, raw) in sources { |
| 953 |
|
| 954 |
|
| 955 |
let as_json = std::path::Path::new(rel) |
| 956 |
.extension() |
| 957 |
.is_some_and(|e| e.eq_ignore_ascii_case("json")); |
| 958 |
let ver = if as_json { |
| 959 |
version_from_tauri_json(raw) |
| 960 |
} else { |
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
match version_from_cargo_toml(raw) { |
| 966 |
Ok(v) => Ok(v), |
| 967 |
Err(e) if version_path == Some(rel.as_str()) => Err(e), |
| 968 |
Err(_) => continue, |
| 969 |
} |
| 970 |
}?; |
| 971 |
found.push(( |
| 972 |
rel.clone(), |
| 973 |
Version::parse(&ver).map_err(|e| anyhow::anyhow!(e))?, |
| 974 |
)); |
| 975 |
} |
| 976 |
|
| 977 |
let disagree: Vec<&(String, Version)> = found.iter().filter(|(_, v)| v != expected).collect(); |
| 978 |
anyhow::ensure!( |
| 979 |
disagree.is_empty(), |
| 980 |
"version drift in {where_}: building {expected} but {}", |
| 981 |
disagree |
| 982 |
.iter() |
| 983 |
.map(|(src, v)| format!("{src} says {v}")) |
| 984 |
.collect::<Vec<_>>() |
| 985 |
.join(", ") |
| 986 |
); |
| 987 |
Ok(()) |
| 988 |
} |
| 989 |
|
| 990 |
|
| 991 |
|
| 992 |
|
| 993 |
|
| 994 |
|
| 995 |
|
| 996 |
pub fn git_show_file_cmd(dir: &str, tag: &str, rel: &str) -> String { |
| 997 |
format!("git -C \"{dir}\" show \"{tag}:./{rel}\"") |
| 998 |
} |
| 999 |
|
| 1000 |
|
| 1001 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 1006 |
fn versions_in_filename(name: &str) -> Vec<Version> { |
| 1007 |
name.split(|c: char| !(c.is_ascii_digit() || c == '.')) |
| 1008 |
.filter_map(|run| { |
| 1009 |
let f: Vec<&str> = run.split('.').filter(|s| !s.is_empty()).collect(); |
| 1010 |
if f.len() >= 3 && f[..3].iter().all(|s| s.chars().all(|c| c.is_ascii_digit())) { |
| 1011 |
Version::parse(&format!("{}.{}.{}", f[0], f[1], f[2])).ok() |
| 1012 |
} else { |
| 1013 |
None |
| 1014 |
} |
| 1015 |
}) |
| 1016 |
.collect() |
| 1017 |
} |
| 1018 |
|
| 1019 |
|
| 1020 |
|
| 1021 |
|
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 1025 |
|
| 1026 |
fn assert_artifact_version(name: &str, expected: &Version) -> Result<()> { |
| 1027 |
let versions = versions_in_filename(name); |
| 1028 |
anyhow::ensure!( |
| 1029 |
versions.is_empty() || versions.iter().any(|v| v.core() == expected.core()), |
| 1030 |
"collected artifact `{name}` carries version {} but the build is {expected}; \ |
| 1031 |
a stale artifact was left in the output dir — clean it so only {expected} remains", |
| 1032 |
versions |
| 1033 |
.iter() |
| 1034 |
.map(ToString::to_string) |
| 1035 |
.collect::<Vec<_>>() |
| 1036 |
.join("/"), |
| 1037 |
); |
| 1038 |
Ok(()) |
| 1039 |
} |
| 1040 |
|
| 1041 |
|
| 1042 |
|
| 1043 |
fn sha256_file(path: &Path) -> Result<String> { |
| 1044 |
let mut file = |
| 1045 |
std::fs::File::open(path).with_context(|| format!("hashing {}", path.display()))?; |
| 1046 |
let mut hasher = Sha256::new(); |
| 1047 |
std::io::copy(&mut file, &mut hasher) |
| 1048 |
.with_context(|| format!("reading {} to hash", path.display()))?; |
| 1049 |
Ok(hex_lower(&hasher.finalize())) |
| 1050 |
} |
| 1051 |
|
| 1052 |
|
| 1053 |
|
| 1054 |
|
| 1055 |
|
| 1056 |
|
| 1057 |
|
| 1058 |
|
| 1059 |
|
| 1060 |
|
| 1061 |
|
| 1062 |
|
| 1063 |
|
| 1064 |
|
| 1065 |
|
| 1066 |
|
| 1067 |
|
| 1068 |
|
| 1069 |
|
| 1070 |
fn collected_files(root: &Path) -> std::io::Result<Vec<(String, PathBuf)>> { |
| 1071 |
fn walk(dir: &Path, root: &Path, out: &mut Vec<(String, PathBuf)>) -> std::io::Result<()> { |
| 1072 |
for entry in std::fs::read_dir(dir)? { |
| 1073 |
let entry = entry?; |
| 1074 |
let ft = entry.file_type()?; |
| 1075 |
let path = entry.path(); |
| 1076 |
if ft.is_dir() { |
| 1077 |
walk(&path, root, out)?; |
| 1078 |
} else if ft.is_file() { |
| 1079 |
let rel = path |
| 1080 |
.strip_prefix(root) |
| 1081 |
.unwrap_or(&path) |
| 1082 |
.components() |
| 1083 |
.map(|c| c.as_os_str().to_string_lossy()) |
| 1084 |
.collect::<Vec<_>>() |
| 1085 |
.join("/"); |
| 1086 |
out.push((rel, path)); |
| 1087 |
} |
| 1088 |
|
| 1089 |
|
| 1090 |
} |
| 1091 |
Ok(()) |
| 1092 |
} |
| 1093 |
let mut out = Vec::new(); |
| 1094 |
walk(root, root, &mut out)?; |
| 1095 |
out.sort_by(|a, b| a.0.cmp(&b.0)); |
| 1096 |
Ok(out) |
| 1097 |
} |
| 1098 |
|
| 1099 |
|
| 1100 |
fn hex_lower(bytes: &[u8]) -> String { |
| 1101 |
use std::fmt::Write as _; |
| 1102 |
let mut s = String::with_capacity(bytes.len() * 2); |
| 1103 |
for b in bytes { |
| 1104 |
let _ = write!(s, "{b:02x}"); |
| 1105 |
} |
| 1106 |
s |
| 1107 |
} |
| 1108 |
|
| 1109 |
|
| 1110 |
|
| 1111 |
|
| 1112 |
|
| 1113 |
|
| 1114 |
|
| 1115 |
|
| 1116 |
|
| 1117 |
|
| 1118 |
|
| 1119 |
|
| 1120 |
|
| 1121 |
|
| 1122 |
|
| 1123 |
pub fn git_fetch_cmd(repo: &str) -> String { |
| 1124 |
format!("git -C {repo} fetch --all --tags --prune") |
| 1125 |
} |
| 1126 |
|
| 1127 |
|
| 1128 |
|
| 1129 |
|
| 1130 |
|
| 1131 |
|
| 1132 |
|
| 1133 |
|
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 1137 |
|
| 1138 |
|
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
pub fn tracked_lock_under_patch_cmd(repo: &str) -> String { |
| 1146 |
format!( |
| 1147 |
"git -C {repo} ls-files --error-unmatch Cargo.lock >/dev/null 2>&1 || exit 1; \ |
| 1148 |
d=$(cd {repo} && pwd -P) || exit 1; \ |
| 1149 |
while [ -n \"$d\" ] && [ \"$d\" != / ]; do \ |
| 1150 |
for c in \"$d/.cargo/config.toml\" \"$d/.cargo/config\"; do \ |
| 1151 |
[ -f \"$c\" ] && grep -q '^\\[patch' \"$c\" && exit 0; \ |
| 1152 |
done; d=$(dirname \"$d\"); done; exit 1" |
| 1153 |
) |
| 1154 |
} |
| 1155 |
|
| 1156 |
|
| 1157 |
|
| 1158 |
|
| 1159 |
pub fn tracked_lock_under_patch_problem(repo: &str) -> String { |
| 1160 |
format!( |
| 1161 |
"`Cargo.lock` is tracked and {repo} sits under a `.cargo/config.toml` \ |
| 1162 |
declaring `[patch]`. Cargo re-resolves there and rewrites the lock, so \ |
| 1163 |
`cargo publish --dry-run` will refuse the tree as dirty and name only \ |
| 1164 |
the lock. Untrack it: `git rm --cached Cargo.lock`. Every other library \ |
| 1165 |
in this tree already does. Not `--allow-dirty`, which publishes a lock \ |
| 1166 |
nobody reviewed, and not committing the rewritten lock, which resolves \ |
| 1167 |
differently on the next machine and fails there instead. The build \ |
| 1168 |
worktree is under `~/Code` on purpose so the patch block applies to it; \ |
| 1169 |
that is not the half to change." |
| 1170 |
) |
| 1171 |
} |
| 1172 |
|
| 1173 |
|
| 1174 |
|
| 1175 |
|
| 1176 |
|
| 1177 |
|
| 1178 |
pub fn git_tag_exists_cmd(repo: &str, tag: &str) -> String { |
| 1179 |
format!("git -C {repo} rev-parse -q --verify \"refs/tags/{tag}^{{commit}}\"") |
| 1180 |
} |
| 1181 |
|
| 1182 |
|
| 1183 |
|
| 1184 |
|
| 1185 |
|
| 1186 |
|
| 1187 |
|
| 1188 |
pub fn git_toplevel_and_prefix_cmd(repo: &str) -> String { |
| 1189 |
format!("git -C {repo} rev-parse --show-toplevel --show-prefix") |
| 1190 |
} |
| 1191 |
|
| 1192 |
|
| 1193 |
|
| 1194 |
|
| 1195 |
|
| 1196 |
|
| 1197 |
pub fn parse_toplevel_and_prefix(out: &str) -> Option<(String, String)> { |
| 1198 |
let mut lines = out.split('\n'); |
| 1199 |
let toplevel = lines.next()?.trim().to_string(); |
| 1200 |
let prefix = lines.next()?.trim().to_string(); |
| 1201 |
(!toplevel.is_empty()).then_some((toplevel, prefix)) |
| 1202 |
} |
| 1203 |
|
| 1204 |
|
| 1205 |
|
| 1206 |
|
| 1207 |
|
| 1208 |
|
| 1209 |
pub fn repo_dir_name(toplevel: &str) -> &str { |
| 1210 |
toplevel |
| 1211 |
.trim_end_matches('/') |
| 1212 |
.rsplit('/') |
| 1213 |
.next() |
| 1214 |
.unwrap_or(toplevel) |
| 1215 |
} |
| 1216 |
|
| 1217 |
|
| 1218 |
|
| 1219 |
pub fn app_dir_in_worktree(worktree: &str, prefix: &str) -> String { |
| 1220 |
let prefix = prefix.trim_matches('/'); |
| 1221 |
if prefix.is_empty() { |
| 1222 |
worktree.to_string() |
| 1223 |
} else { |
| 1224 |
format!("{}/{prefix}", worktree.trim_end_matches('/')) |
| 1225 |
} |
| 1226 |
} |
| 1227 |
|
| 1228 |
|
| 1229 |
|
| 1230 |
|
| 1231 |
|
| 1232 |
|
| 1233 |
pub fn git_worktree_probe_cmd(worktree: &str) -> String { |
| 1234 |
format!("git -C \"{worktree}\" rev-parse --git-dir") |
| 1235 |
} |
| 1236 |
|
| 1237 |
|
| 1238 |
|
| 1239 |
|
| 1240 |
pub fn git_worktree_prune_cmd(toplevel: &str) -> String { |
| 1241 |
format!("git -C \"{toplevel}\" worktree prune") |
| 1242 |
} |
| 1243 |
|
| 1244 |
|
| 1245 |
|
| 1246 |
pub fn git_worktree_add_cmd(toplevel: &str, worktree: &str, tag: &str) -> String { |
| 1247 |
format!("git -C \"{toplevel}\" worktree add --detach --force \"{worktree}\" \"{tag}\"") |
| 1248 |
} |
| 1249 |
|
| 1250 |
|
| 1251 |
|
| 1252 |
|
| 1253 |
|
| 1254 |
|
| 1255 |
|
| 1256 |
pub fn git_worktree_pin_cmd(worktree: &str, tag: &str) -> String { |
| 1257 |
format!("git -C \"{worktree}\" checkout --detach --force \"{tag}\"") |
| 1258 |
} |
| 1259 |
|
| 1260 |
|
| 1261 |
|
| 1262 |
|
| 1263 |
|
| 1264 |
|
| 1265 |
|
| 1266 |
|
| 1267 |
pub fn worktree_failure_reason(tag: &str, tag_exists: bool, stderr: &str) -> String { |
| 1268 |
if !tag_exists { |
| 1269 |
return format!("tag {tag} does not exist there (is it created and pushed?)"); |
| 1270 |
} |
| 1271 |
let stderr = stderr.trim(); |
| 1272 |
if stderr.is_empty() { |
| 1273 |
format!("tag {tag} exists, and git said nothing about why") |
| 1274 |
} else { |
| 1275 |
stderr.to_string() |
| 1276 |
} |
| 1277 |
} |
| 1278 |
|
| 1279 |
|
| 1280 |
|
| 1281 |
pub fn git_rev_parse_cmd(repo: &str) -> String { |
| 1282 |
format!("git -C {repo} rev-parse HEAD") |
| 1283 |
} |
| 1284 |
|
| 1285 |
|
| 1286 |
pub fn expand_tilde(p: &str) -> PathBuf { |
| 1287 |
if let Some(rest) = p.strip_prefix("~/") |
| 1288 |
&& let Ok(home) = std::env::var("HOME") |
| 1289 |
{ |
| 1290 |
return Path::new(&home).join(rest); |
| 1291 |
} |
| 1292 |
PathBuf::from(p) |
| 1293 |
} |
| 1294 |
|
| 1295 |
|
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
|
| 1300 |
|
| 1301 |
fn ensure_glob_safe(glob: &str) -> Result<()> { |
| 1302 |
anyhow::ensure!( |
| 1303 |
!glob.chars().any(|c| matches!( |
| 1304 |
c, |
| 1305 |
';' | '&' | '|' | '$' | '`' | '\'' | '"' | '\\' | ' ' | '\n' | '(' | ')' | '<' | '>' |
| 1306 |
)), |
| 1307 |
"glob `{glob}` contains shell metacharacters" |
| 1308 |
); |
| 1309 |
Ok(()) |
| 1310 |
} |
| 1311 |
|
| 1312 |
|
| 1313 |
|
| 1314 |
|
| 1315 |
|
| 1316 |
|
| 1317 |
|
| 1318 |
|
| 1319 |
fn resolve_artifact_match(listing: &str, glob: &str, required: bool) -> Result<String> { |
| 1320 |
let matches: Vec<&str> = listing |
| 1321 |
.lines() |
| 1322 |
.map(str::trim) |
| 1323 |
.filter(|l| !l.is_empty()) |
| 1324 |
.collect(); |
| 1325 |
match matches.as_slice() { |
| 1326 |
[] if required => anyhow::bail!("no artifact matched glob `{glob}`"), |
| 1327 |
[] => Ok(String::new()), |
| 1328 |
[one] => Ok((*one).to_string()), |
| 1329 |
many => anyhow::bail!( |
| 1330 |
"glob `{glob}` is ambiguous: {} artifacts matched ({}). \ |
| 1331 |
The build left more than one behind; clean stale artifacts so exactly one remains.", |
| 1332 |
many.len(), |
| 1333 |
many.join(", ") |
| 1334 |
), |
| 1335 |
} |
| 1336 |
} |
| 1337 |
|
| 1338 |
|
| 1339 |
|
| 1340 |
pub fn build_engine(ctx: &Arc<RecipeCtx>) -> Engine { |
| 1341 |
let mut engine = Engine::new(); |
| 1342 |
|
| 1343 |
engine.set_max_operations(5_000_000); |
| 1344 |
engine.set_max_call_levels(64); |
| 1345 |
engine.set_max_string_size(0); |
| 1346 |
|
| 1347 |
|
| 1348 |
{ |
| 1349 |
let ctx = ctx.clone(); |
| 1350 |
engine.register_fn( |
| 1351 |
"step", |
| 1352 |
move |name: &str| -> Result<(), Box<EvalAltResult>> { |
| 1353 |
let step: Step = name.parse().map_err(rhai_err)?; |
| 1354 |
ctx.begin_step(step).map_err(rhai_err) |
| 1355 |
}, |
| 1356 |
); |
| 1357 |
} |
| 1358 |
|
| 1359 |
|
| 1360 |
|
| 1361 |
|
| 1362 |
|
| 1363 |
|
| 1364 |
|
| 1365 |
|
| 1366 |
{ |
| 1367 |
let ctx = ctx.clone(); |
| 1368 |
engine.register_fn( |
| 1369 |
"sh", |
| 1370 |
move |host: &str, cmd: &str| -> Result<Map, Box<EvalAltResult>> { |
| 1371 |
let (code, tail) = ctx.run(host, cmd).map_err(rhai_err)?; |
| 1372 |
let mut m = Map::new(); |
| 1373 |
m.insert("code".into(), (code as i64).into()); |
| 1374 |
m.insert("stdout_tail".into(), tail.into()); |
| 1375 |
Ok(m) |
| 1376 |
}, |
| 1377 |
); |
| 1378 |
} |
| 1379 |
|
| 1380 |
|
| 1381 |
|
| 1382 |
|
| 1383 |
|
| 1384 |
|
| 1385 |
{ |
| 1386 |
let ctx = ctx.clone(); |
| 1387 |
engine.register_fn( |
| 1388 |
"sh_ok", |
| 1389 |
move |host: &str, cmd: &str| -> Result<(), Box<EvalAltResult>> { |
| 1390 |
let (code, _) = ctx.run(host, cmd).map_err(rhai_err)?; |
| 1391 |
if code != 0 { |
| 1392 |
|
| 1393 |
|
| 1394 |
ctx.fail_current_step(); |
| 1395 |
return Err(rhai_err(format!( |
| 1396 |
"command on `{host}` exited {code}: {cmd}" |
| 1397 |
))); |
| 1398 |
} |
| 1399 |
Ok(()) |
| 1400 |
}, |
| 1401 |
); |
| 1402 |
} |
| 1403 |
|
| 1404 |
|
| 1405 |
|
| 1406 |
|
| 1407 |
|
| 1408 |
|
| 1409 |
|
| 1410 |
|
| 1411 |
|
| 1412 |
|
| 1413 |
{ |
| 1414 |
let ctx = ctx.clone(); |
| 1415 |
engine.register_fn( |
| 1416 |
"resolve_artifact", |
| 1417 |
move |host: &str, glob: &str| -> Result<String, Box<EvalAltResult>> { |
| 1418 |
ctx.resolve_artifact(host, glob, true).map_err(rhai_err) |
| 1419 |
}, |
| 1420 |
); |
| 1421 |
} |
| 1422 |
|
| 1423 |
|
| 1424 |
|
| 1425 |
|
| 1426 |
|
| 1427 |
|
| 1428 |
{ |
| 1429 |
let ctx = ctx.clone(); |
| 1430 |
engine.register_fn( |
| 1431 |
"resolve_artifact_opt", |
| 1432 |
move |host: &str, glob: &str| -> Result<String, Box<EvalAltResult>> { |
| 1433 |
ctx.resolve_artifact(host, glob, false).map_err(rhai_err) |
| 1434 |
}, |
| 1435 |
); |
| 1436 |
} |
| 1437 |
|
| 1438 |
|
| 1439 |
{ |
| 1440 |
let ctx = ctx.clone(); |
| 1441 |
engine.register_fn("log", move |msg: &str| -> Result<(), Box<EvalAltResult>> { |
| 1442 |
let sink = ctx.ensure_step().map_err(rhai_err)?; |
| 1443 |
let line = format!("[recipe] {msg}\n"); |
| 1444 |
ctx.rt.block_on(async { |
| 1445 |
use ops_core::remote::LogSink; |
| 1446 |
sink.lock().await.write_chunk(line.as_bytes()).await; |
| 1447 |
}); |
| 1448 |
Ok(()) |
| 1449 |
}); |
| 1450 |
} |
| 1451 |
|
| 1452 |
|
| 1453 |
{ |
| 1454 |
let ctx = ctx.clone(); |
| 1455 |
engine.register_fn( |
| 1456 |
"version_of", |
| 1457 |
move |app: &str| -> Result<String, Box<EvalAltResult>> { |
| 1458 |
|
| 1459 |
if app != ctx.app.as_str() { |
| 1460 |
return Err(rhai_err(format!( |
| 1461 |
"version_of: `{app}` is not the app being built" |
| 1462 |
))); |
| 1463 |
} |
| 1464 |
Ok(ctx.version.to_string()) |
| 1465 |
}, |
| 1466 |
); |
| 1467 |
} |
| 1468 |
|
| 1469 |
|
| 1470 |
{ |
| 1471 |
let ctx = ctx.clone(); |
| 1472 |
engine.register_fn("version", move || -> String { ctx.version.to_string() }); |
| 1473 |
} |
| 1474 |
|
| 1475 |
|
| 1476 |
{ |
| 1477 |
let ctx = ctx.clone(); |
| 1478 |
engine.register_fn("build_host", move || -> String { ctx.build_host.clone() }); |
| 1479 |
} |
| 1480 |
|
| 1481 |
|
| 1482 |
|
| 1483 |
|
| 1484 |
|
| 1485 |
|
| 1486 |
{ |
| 1487 |
let ctx = ctx.clone(); |
| 1488 |
engine.register_fn("repo", move || -> String { |
| 1489 |
ctx.repo_for(&ctx.build_host).to_string() |
| 1490 |
}); |
| 1491 |
} |
| 1492 |
|
| 1493 |
|
| 1494 |
|
| 1495 |
|
| 1496 |
|
| 1497 |
{ |
| 1498 |
let ctx = ctx.clone(); |
| 1499 |
engine.register_fn( |
| 1500 |
"checkout_sha", |
| 1501 |
move |host: &str| -> Result<String, Box<EvalAltResult>> { |
| 1502 |
ctx.checkout_sha(host).map_err(rhai_err) |
| 1503 |
}, |
| 1504 |
); |
| 1505 |
} |
| 1506 |
|
| 1507 |
|
| 1508 |
|
| 1509 |
|
| 1510 |
|
| 1511 |
{ |
| 1512 |
let ctx = ctx.clone(); |
| 1513 |
engine.register_fn( |
| 1514 |
"crate_preflight", |
| 1515 |
move || -> Result<String, Box<EvalAltResult>> { |
| 1516 |
|
| 1517 |
|
| 1518 |
|
| 1519 |
let repo = expand_tilde(&ctx.repo); |
| 1520 |
|
| 1521 |
let out = std::process::Command::new("cargo") |
| 1522 |
.args(["metadata", "--no-deps", "--format-version", "1"]) |
| 1523 |
.current_dir(&repo) |
| 1524 |
.output() |
| 1525 |
.map_err(|e| format!("running cargo metadata in {}: {e}", repo.display()))?; |
| 1526 |
if !out.status.success() { |
| 1527 |
return Err(format!( |
| 1528 |
"cargo metadata failed in {}: {}", |
| 1529 |
repo.display(), |
| 1530 |
String::from_utf8_lossy(&out.stderr).trim() |
| 1531 |
) |
| 1532 |
.into()); |
| 1533 |
} |
| 1534 |
let meta = crate_meta_from_json(&String::from_utf8_lossy(&out.stdout)) |
| 1535 |
.map_err(|e| e.to_string())?; |
| 1536 |
|
| 1537 |
|
| 1538 |
|
| 1539 |
let clonable = meta.repository.as_ref().is_some_and(|url| { |
| 1540 |
std::process::Command::new("git") |
| 1541 |
.args(["ls-remote", url]) |
| 1542 |
.env("GIT_TERMINAL_PROMPT", "0") |
| 1543 |
.output() |
| 1544 |
.is_ok_and(|o| o.status.success()) |
| 1545 |
}); |
| 1546 |
|
| 1547 |
|
| 1548 |
|
| 1549 |
|
| 1550 |
|
| 1551 |
|
| 1552 |
|
| 1553 |
|
| 1554 |
|
| 1555 |
let creds = |
| 1556 |
ctx.run( |
| 1557 |
&ctx.build_host.clone(), |
| 1558 |
"cargo login --help >/dev/null 2>&1 && \ |
| 1559 |
test -s \"${CARGO_HOME:-$HOME/.cargo}/credentials.toml\" \ |
| 1560 |
|| test -s \"${CARGO_HOME:-$HOME/.cargo}/credentials\"", |
| 1561 |
) |
| 1562 |
.map_err(|e| { |
| 1563 |
format!( |
| 1564 |
"could not check crates.io credentials on `{}`: {e}", |
| 1565 |
ctx.build_host |
| 1566 |
) |
| 1567 |
})? |
| 1568 |
.0 == 0; |
| 1569 |
|
| 1570 |
|
| 1571 |
|
| 1572 |
|
| 1573 |
|
| 1574 |
|
| 1575 |
|
| 1576 |
let build_repo = ctx.repo_for(&ctx.build_host).to_string(); |
| 1577 |
let patched_lock = |
| 1578 |
ctx.run( |
| 1579 |
&ctx.build_host.clone(), |
| 1580 |
&tracked_lock_under_patch_cmd(&build_repo), |
| 1581 |
) |
| 1582 |
.map_err(|e| { |
| 1583 |
format!( |
| 1584 |
"could not check for a tracked Cargo.lock on `{}`: {e}", |
| 1585 |
ctx.build_host |
| 1586 |
) |
| 1587 |
})? |
| 1588 |
.0 == 0; |
| 1589 |
|
| 1590 |
let published = RecipeCtx::published_versions(&meta.name); |
| 1591 |
let mut problems = crate_publish_problems(&meta, clonable, &published, creds); |
| 1592 |
if patched_lock { |
| 1593 |
problems.push(tracked_lock_under_patch_problem(&build_repo)); |
| 1594 |
} |
| 1595 |
if !problems.is_empty() { |
| 1596 |
return Err(format!( |
| 1597 |
"{} {} is not safe to publish:\n - {}", |
| 1598 |
meta.name, |
| 1599 |
meta.version, |
| 1600 |
problems.join("\n - ") |
| 1601 |
) |
| 1602 |
.into()); |
| 1603 |
} |
| 1604 |
Ok(format!("{} {} passed preflight", meta.name, meta.version)) |
| 1605 |
}, |
| 1606 |
); |
| 1607 |
} |
| 1608 |
|
| 1609 |
|
| 1610 |
|
| 1611 |
|
| 1612 |
{ |
| 1613 |
let ctx = ctx.clone(); |
| 1614 |
engine.register_fn("feature_flags", move || -> String { |
| 1615 |
if ctx.features.is_empty() { |
| 1616 |
String::new() |
| 1617 |
} else { |
| 1618 |
format!("--features {}", ctx.features.join(",")) |
| 1619 |
} |
| 1620 |
}); |
| 1621 |
} |
| 1622 |
|
| 1623 |
|
| 1624 |
|
| 1625 |
{ |
| 1626 |
let ctx = ctx.clone(); |
| 1627 |
engine.register_fn("target", move || -> String { ctx.target.to_string() }); |
| 1628 |
} |
| 1629 |
{ |
| 1630 |
let ctx = ctx.clone(); |
| 1631 |
engine.register_fn("platform", move || -> String { |
| 1632 |
ctx.target.platform.as_str().to_string() |
| 1633 |
}); |
| 1634 |
} |
| 1635 |
{ |
| 1636 |
let ctx = ctx.clone(); |
| 1637 |
engine.register_fn("arch", move || -> String { |
| 1638 |
ctx.target.arch.as_str().to_string() |
| 1639 |
}); |
| 1640 |
} |
| 1641 |
|
| 1642 |
|
| 1643 |
{ |
| 1644 |
let ctx = ctx.clone(); |
| 1645 |
engine.register_fn("secret", move |key: &str| -> Result<String, Box<EvalAltResult>> { |
| 1646 |
|
| 1647 |
|
| 1648 |
|
| 1649 |
|
| 1650 |
|
| 1651 |
|
| 1652 |
let safe = !key.is_empty() |
| 1653 |
&& !key.contains('\\') |
| 1654 |
&& std::path::Path::new(key) |
| 1655 |
.components() |
| 1656 |
.all(|c| matches!(c, std::path::Component::Normal(_))); |
| 1657 |
if !safe { |
| 1658 |
return Err(rhai_err( |
| 1659 |
"secret key must be a relative path under secrets_root (no `..`, `.`, absolute paths, or backslashes)", |
| 1660 |
)); |
| 1661 |
} |
| 1662 |
let path = ctx.cfg.secrets_root.join(key); |
| 1663 |
std::fs::read_to_string(&path) |
| 1664 |
.map(|s| s.trim_end().to_string()) |
| 1665 |
.map_err(|e| rhai_err(format!("secret `{key}`: {e}"))) |
| 1666 |
}); |
| 1667 |
} |
| 1668 |
|
| 1669 |
|
| 1670 |
{ |
| 1671 |
let ctx = ctx.clone(); |
| 1672 |
engine.register_fn( |
| 1673 |
"env", |
| 1674 |
move |host: &str, key: &str| -> Result<String, Box<EvalAltResult>> { |
| 1675 |
|
| 1676 |
|
| 1677 |
|
| 1678 |
|
| 1679 |
|
| 1680 |
if key.is_empty() |
| 1681 |
|| !key |
| 1682 |
.chars() |
| 1683 |
.next() |
| 1684 |
.is_some_and(|c| c == '_' || c.is_ascii_alphabetic()) |
| 1685 |
|| !key.chars().all(|c| c == '_' || c.is_ascii_alphanumeric()) |
| 1686 |
{ |
| 1687 |
return Err(rhai_err(format!( |
| 1688 |
"env name `{key}` must be a shell identifier ([A-Za-z_][A-Za-z0-9_]*)" |
| 1689 |
))); |
| 1690 |
} |
| 1691 |
|
| 1692 |
let (code, tail) = ctx |
| 1693 |
.run(host, &format!("printf '%s' \"${{{key}}}\"")) |
| 1694 |
.map_err(rhai_err)?; |
| 1695 |
if code != 0 { |
| 1696 |
return Err(rhai_err(format!("env `{key}` on `{host}` failed"))); |
| 1697 |
} |
| 1698 |
Ok(tail.trim().to_string()) |
| 1699 |
}, |
| 1700 |
); |
| 1701 |
} |
| 1702 |
|
| 1703 |
|
| 1704 |
{ |
| 1705 |
let ctx = ctx.clone(); |
| 1706 |
engine.register_fn( |
| 1707 |
"collect", |
| 1708 |
move |host: &str, |
| 1709 |
glob: &str, |
| 1710 |
app: &str, |
| 1711 |
version: &str| |
| 1712 |
-> Result<(), Box<EvalAltResult>> { |
| 1713 |
ctx.collect(host, glob, app, version).map_err(rhai_err) |
| 1714 |
}, |
| 1715 |
); |
| 1716 |
} |
| 1717 |
|
| 1718 |
|
| 1719 |
{ |
| 1720 |
let ctx = ctx.clone(); |
| 1721 |
engine.register_fn( |
| 1722 |
"publish", |
| 1723 |
move |channel: &str, |
| 1724 |
app: &str, |
| 1725 |
target: &str, |
| 1726 |
version: &str, |
| 1727 |
artifact: &str, |
| 1728 |
meta: Map| |
| 1729 |
-> Result<String, Box<EvalAltResult>> { |
| 1730 |
ctx.publish(channel, app, target, version, artifact, &meta) |
| 1731 |
.map_err(rhai_err) |
| 1732 |
}, |
| 1733 |
); |
| 1734 |
} |
| 1735 |
|
| 1736 |
|
| 1737 |
|
| 1738 |
|
| 1739 |
|
| 1740 |
|
| 1741 |
|
| 1742 |
|
| 1743 |
|
| 1744 |
|
| 1745 |
{ |
| 1746 |
let ctx = ctx.clone(); |
| 1747 |
engine.register_fn( |
| 1748 |
"deploy", |
| 1749 |
move |binary: &str| -> Result<String, Box<EvalAltResult>> { |
| 1750 |
ctx.deploy(binary).map_err(rhai_err) |
| 1751 |
}, |
| 1752 |
); |
| 1753 |
} |
| 1754 |
|
| 1755 |
|
| 1756 |
|
| 1757 |
|
| 1758 |
|
| 1759 |
{ |
| 1760 |
let ctx = ctx.clone(); |
| 1761 |
engine.register_fn( |
| 1762 |
"deploy_host", |
| 1763 |
move || -> Result<String, Box<EvalAltResult>> { |
| 1764 |
ctx.deploy_target() |
| 1765 |
.map(|d| d.host.clone()) |
| 1766 |
.map_err(rhai_err) |
| 1767 |
}, |
| 1768 |
); |
| 1769 |
} |
| 1770 |
|
| 1771 |
|
| 1772 |
|
| 1773 |
|
| 1774 |
|
| 1775 |
{ |
| 1776 |
let ctx = ctx.clone(); |
| 1777 |
engine.register_fn( |
| 1778 |
"service_name", |
| 1779 |
move || -> Result<String, Box<EvalAltResult>> { |
| 1780 |
ctx.deploy_target() |
| 1781 |
.map(|d| d.service.clone()) |
| 1782 |
.map_err(rhai_err) |
| 1783 |
}, |
| 1784 |
); |
| 1785 |
} |
| 1786 |
{ |
| 1787 |
let ctx = ctx.clone(); |
| 1788 |
engine.register_fn( |
| 1789 |
"install_path", |
| 1790 |
move || -> Result<String, Box<EvalAltResult>> { |
| 1791 |
ctx.deploy_target() |
| 1792 |
.map(|d| d.install_path.clone()) |
| 1793 |
.map_err(rhai_err) |
| 1794 |
}, |
| 1795 |
); |
| 1796 |
} |
| 1797 |
{ |
| 1798 |
let ctx = ctx.clone(); |
| 1799 |
engine.register_fn( |
| 1800 |
"health_url", |
| 1801 |
move || -> Result<String, Box<EvalAltResult>> { |
| 1802 |
ctx.deploy_target() |
| 1803 |
.map(|d| d.health_url.clone().unwrap_or_default()) |
| 1804 |
.map_err(rhai_err) |
| 1805 |
}, |
| 1806 |
); |
| 1807 |
} |
| 1808 |
|
| 1809 |
|
| 1810 |
|
| 1811 |
|
| 1812 |
|
| 1813 |
|
| 1814 |
|
| 1815 |
|
| 1816 |
|
| 1817 |
|
| 1818 |
|
| 1819 |
|
| 1820 |
|
| 1821 |
|
| 1822 |
|
| 1823 |
|
| 1824 |
|
| 1825 |
|
| 1826 |
|
| 1827 |
|
| 1828 |
|
| 1829 |
|
| 1830 |
|
| 1831 |
|
| 1832 |
|
| 1833 |
|
| 1834 |
{ |
| 1835 |
let ctx = ctx.clone(); |
| 1836 |
engine.register_fn( |
| 1837 |
"glibc_check", |
| 1838 |
move |binary: &str| -> Result<String, Box<EvalAltResult>> { |
| 1839 |
let (needs, has) = ctx.glibc_check(binary).map_err(rhai_err)?; |
| 1840 |
Ok(format!( |
| 1841 |
"glibc: binary needs {needs}, service host has {has}" |
| 1842 |
)) |
| 1843 |
}, |
| 1844 |
); |
| 1845 |
} |
| 1846 |
|
| 1847 |
|
| 1848 |
|
| 1849 |
|
| 1850 |
|
| 1851 |
|
| 1852 |
|
| 1853 |
register_macos_fns(&mut engine, ctx); |
| 1854 |
|
| 1855 |
engine |
| 1856 |
} |
| 1857 |
|
| 1858 |
|
| 1859 |
|
| 1860 |
|
| 1861 |
|
| 1862 |
|
| 1863 |
|
| 1864 |
|
| 1865 |
|
| 1866 |
|
| 1867 |
fn max_glibc_symbol(objdump_out: &str) -> Option<(u64, u64)> { |
| 1868 |
objdump_out |
| 1869 |
.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '_' || c.is_ascii_alphabetic())) |
| 1870 |
.filter_map(|tok| tok.strip_prefix("GLIBC_")) |
| 1871 |
.filter_map(parse_glibc_version) |
| 1872 |
.max() |
| 1873 |
} |
| 1874 |
|
| 1875 |
|
| 1876 |
fn parse_glibc_version(s: &str) -> Option<(u64, u64)> { |
| 1877 |
let mut parts = s.split('.'); |
| 1878 |
let major = parts.next()?.parse().ok()?; |
| 1879 |
let minor = parts.next()?.parse().ok()?; |
| 1880 |
Some((major, minor)) |
| 1881 |
} |
| 1882 |
|
| 1883 |
|
| 1884 |
|
| 1885 |
|
| 1886 |
fn glibc_from_ldd(ldd_out: &str) -> Option<(u64, u64)> { |
| 1887 |
let first = ldd_out.lines().find(|l| !l.trim().is_empty())?; |
| 1888 |
parse_glibc_version(first.split_whitespace().last()?) |
| 1889 |
} |
| 1890 |
|
| 1891 |
impl RecipeCtx { |
| 1892 |
|
| 1893 |
fn deploy_target(&self) -> Result<&DeployTarget> { |
| 1894 |
self.deploy.as_ref().ok_or_else(|| { |
| 1895 |
anyhow::anyhow!( |
| 1896 |
"no deploy destination for {} {}: the app is `kind = \"{}\"`, and only a \ |
| 1897 |
service declares [[deploy]] entries", |
| 1898 |
self.app, |
| 1899 |
self.target, |
| 1900 |
match self.kind { |
| 1901 |
Kind::App => "app", |
| 1902 |
Kind::Library => "library", |
| 1903 |
Kind::Service => "service", |
| 1904 |
} |
| 1905 |
) |
| 1906 |
}) |
| 1907 |
} |
| 1908 |
|
| 1909 |
|
| 1910 |
|
| 1911 |
fn glibc_check(self: &Arc<Self>, binary: &str) -> Result<(String, String)> { |
| 1912 |
let d = self.deploy_target()?.clone(); |
| 1913 |
|
| 1914 |
|
| 1915 |
let (code, out) = self.run( |
| 1916 |
&self.build_host.clone(), |
| 1917 |
&format!( |
| 1918 |
"objdump -T {binary} 2>/dev/null | grep -o 'GLIBC_[0-9.]*' | sort -uV || true" |
| 1919 |
), |
| 1920 |
)?; |
| 1921 |
anyhow::ensure!(code == 0, "reading glibc symbols from {binary} failed"); |
| 1922 |
let Some(needs) = max_glibc_symbol(&out) else { |
| 1923 |
return Ok(("none".into(), "n/a".into())); |
| 1924 |
}; |
| 1925 |
let (code, ldd) = self.run(&d.host, "ldd --version")?; |
| 1926 |
anyhow::ensure!( |
| 1927 |
code == 0, |
| 1928 |
"could not read glibc version on service host `{}`", |
| 1929 |
d.host |
| 1930 |
); |
| 1931 |
let has = glibc_from_ldd(&ldd).ok_or_else(|| { |
| 1932 |
anyhow::anyhow!( |
| 1933 |
"could not parse glibc version from `ldd --version` on `{}`", |
| 1934 |
d.host |
| 1935 |
) |
| 1936 |
})?; |
| 1937 |
anyhow::ensure!( |
| 1938 |
needs <= has, |
| 1939 |
"binary needs glibc {}.{} but `{}` has {}.{} — it would fail to exec after the \ |
| 1940 |
unit restarted onto it. Build on a host no newer than the service host.", |
| 1941 |
needs.0, |
| 1942 |
needs.1, |
| 1943 |
d.host, |
| 1944 |
has.0, |
| 1945 |
has.1, |
| 1946 |
); |
| 1947 |
Ok(( |
| 1948 |
format!("{}.{}", needs.0, needs.1), |
| 1949 |
format!("{}.{}", has.0, has.1), |
| 1950 |
)) |
| 1951 |
} |
| 1952 |
|
| 1953 |
|
| 1954 |
|
| 1955 |
|
| 1956 |
|
| 1957 |
|
| 1958 |
|
| 1959 |
|
| 1960 |
|
| 1961 |
|
| 1962 |
|
| 1963 |
|
| 1964 |
|
| 1965 |
|
| 1966 |
|
| 1967 |
fn deploy(self: &Arc<Self>, binary: &str) -> Result<String> { |
| 1968 |
anyhow::ensure!( |
| 1969 |
!self.is_cancelled(), |
| 1970 |
"build superseded by a newer request; refusing to deploy" |
| 1971 |
); |
| 1972 |
|
| 1973 |
|
| 1974 |
|
| 1975 |
let failed = self.failed_steps.lock().unwrap().clone(); |
| 1976 |
anyhow::ensure!( |
| 1977 |
failed.is_empty(), |
| 1978 |
"refusing to deploy {} {}: {} failed earlier in this run", |
| 1979 |
self.app, |
| 1980 |
self.version, |
| 1981 |
failed |
| 1982 |
.iter() |
| 1983 |
.map(ToString::to_string) |
| 1984 |
.collect::<Vec<_>>() |
| 1985 |
.join(", "), |
| 1986 |
); |
| 1987 |
let d = self.deploy_target()?.clone(); |
| 1988 |
ensure_glob_safe(binary)?; |
| 1989 |
|
| 1990 |
|
| 1991 |
|
| 1992 |
let staged = format!("{DEPLOY_STAGING_ROOT}/{}", self.app); |
| 1993 |
let staged_bin = format!("{staged}/{}", self.app); |
| 1994 |
let deploy_exec = self.exec(&d.host)?; |
| 1995 |
anyhow::ensure!( |
| 1996 |
deploy_exec.capabilities().permits(&Action::Deploy), |
| 1997 |
"service host `{}` is not granted the `deploy` capability", |
| 1998 |
d.host |
| 1999 |
); |
| 2000 |
|
| 2001 |
self.run_ok(&d.host, &format!("mkdir -p {staged}"))?; |
| 2002 |
if self.build_host_ssh == d.host { |
| 2003 |
|
| 2004 |
|
| 2005 |
|
| 2006 |
self.run_ok(&d.host, &format!("cp -f {binary} {staged_bin}"))?; |
| 2007 |
} else { |
| 2008 |
|
| 2009 |
|
| 2010 |
|
| 2011 |
let tmp = tempfile::tempdir().context("staging dir for deploy")?; |
| 2012 |
let local = tmp.path().join(self.app.as_str()); |
| 2013 |
self.pull_for_deploy(binary, &local)?; |
| 2014 |
let (dest, opts) = (PathBuf::from(&staged), SyncOpts::default()); |
| 2015 |
let dir = tmp.path().to_path_buf(); |
| 2016 |
self.run_bounded(&format!("stage {} on `{}`", self.app, d.host), async move { |
| 2017 |
deploy_exec.push_dir(&dir, &dest, &opts).await |
| 2018 |
}) |
| 2019 |
.with_context(|| format!("staging {} onto `{}`", self.app, d.host))?; |
| 2020 |
} |
| 2021 |
|
| 2022 |
|
| 2023 |
|
| 2024 |
self.run_ok( |
| 2025 |
&d.host, |
| 2026 |
&format!( |
| 2027 |
"{} {staged_bin} {} {}", |
| 2028 |
self.cfg.deploy_installer, d.install_path, d.service |
| 2029 |
), |
| 2030 |
)?; |
| 2031 |
Ok(format!( |
| 2032 |
"{} {} installed at {} on `{}`; {} restarted", |
| 2033 |
self.app, self.version, d.install_path, d.host, d.service |
| 2034 |
)) |
| 2035 |
} |
| 2036 |
|
| 2037 |
|
| 2038 |
|
| 2039 |
|
| 2040 |
|
| 2041 |
|
| 2042 |
|
| 2043 |
|
| 2044 |
|
| 2045 |
fn pull_for_deploy(self: &Arc<Self>, remote: &str, local: &Path) -> Result<()> { |
| 2046 |
let host = self.build_host.clone(); |
| 2047 |
let remote_path = expand_tilde(remote); |
| 2048 |
if self.build_host_ssh == "local" || self.build_host_ssh.is_empty() { |
| 2049 |
std::fs::copy(&remote_path, local).with_context(|| { |
| 2050 |
format!("staging {} from the daemon host", remote_path.display()) |
| 2051 |
})?; |
| 2052 |
return Ok(()); |
| 2053 |
} |
| 2054 |
let sync = self.host_sync(&host)?; |
| 2055 |
let (src, dst, opts) = (remote_path, local.to_path_buf(), SyncOpts::default()); |
| 2056 |
self.run_bounded(&format!("fetch {remote} from `{host}`"), async move { |
| 2057 |
sync.pull_file(&src, &dst, &opts).await |
| 2058 |
}) |
| 2059 |
.with_context(|| format!("fetching {remote} from `{host}` to deploy")) |
| 2060 |
} |
| 2061 |
|
| 2062 |
|
| 2063 |
|
| 2064 |
fn run_ok(self: &Arc<Self>, host: &str, cmd: &str) -> Result<String> { |
| 2065 |
let (code, tail) = self.run(host, cmd)?; |
| 2066 |
if code != 0 { |
| 2067 |
self.fail_current_step(); |
| 2068 |
anyhow::bail!("command on `{host}` exited {code}: {cmd}\n{tail}"); |
| 2069 |
} |
| 2070 |
Ok(tail) |
| 2071 |
} |
| 2072 |
|
| 2073 |
|
| 2074 |
|
| 2075 |
|
| 2076 |
|
| 2077 |
|
| 2078 |
|
| 2079 |
|
| 2080 |
fn collect_dest(&self, app: &str, version: &str) -> PathBuf { |
| 2081 |
self.cfg |
| 2082 |
.dist_root |
| 2083 |
.join(app) |
| 2084 |
.join(version) |
| 2085 |
.join(crate::archive::target_slug(self.target)) |
| 2086 |
} |
| 2087 |
|
| 2088 |
fn collect(self: &Arc<Self>, host: &str, glob: &str, app: &str, version: &str) -> Result<()> { |
| 2089 |
let dest = self.collect_dest(app, version); |
| 2090 |
let dest_s = dest.to_string_lossy().into_owned(); |
| 2091 |
|
| 2092 |
|
| 2093 |
ensure_glob_safe(glob)?; |
| 2094 |
std::fs::create_dir_all(&dest) |
| 2095 |
.with_context(|| format!("creating collect dest {dest_s}"))?; |
| 2096 |
|
| 2097 |
|
| 2098 |
|
| 2099 |
|
| 2100 |
|
| 2101 |
let sync = self.host_sync(host)?; |
| 2102 |
let opts = SyncOpts::precompressed(); |
| 2103 |
|
| 2104 |
|
| 2105 |
let dest_pull = dest.clone(); |
| 2106 |
self.run_bounded(&format!("collect {glob} from `{host}`"), async move { |
| 2107 |
sync.pull_glob(glob, &dest_pull, &opts).await |
| 2108 |
}) |
| 2109 |
.with_context(|| format!("collect {glob} from `{host}`"))?; |
| 2110 |
|
| 2111 |
|
| 2112 |
|
| 2113 |
|
| 2114 |
|
| 2115 |
|
| 2116 |
|
| 2117 |
|
| 2118 |
|
| 2119 |
|
| 2120 |
|
| 2121 |
|
| 2122 |
|
| 2123 |
|
| 2124 |
for (rel, path) in |
| 2125 |
collected_files(&dest).with_context(|| format!("listing collect dest {dest_s}"))? |
| 2126 |
{ |
| 2127 |
|
| 2128 |
|
| 2129 |
|
| 2130 |
let name = path |
| 2131 |
.file_name() |
| 2132 |
.map_or_else(|| rel.clone(), |n| n.to_string_lossy().into_owned()); |
| 2133 |
assert_artifact_version(&name, &self.version)?; |
| 2134 |
let digest = sha256_file(&path)?; |
| 2135 |
self.artifact_hashes.lock().unwrap().insert(rel, digest); |
| 2136 |
} |
| 2137 |
|
| 2138 |
|
| 2139 |
|
| 2140 |
|
| 2141 |
|
| 2142 |
|
| 2143 |
|
| 2144 |
|
| 2145 |
|
| 2146 |
let (cfg, app_id, version, target) = ( |
| 2147 |
self.cfg.clone(), |
| 2148 |
self.app.clone(), |
| 2149 |
self.version.clone(), |
| 2150 |
self.target, |
| 2151 |
); |
| 2152 |
let dest_archive = dest.clone(); |
| 2153 |
self.run_bounded("deposit in the archive", async move { |
| 2154 |
crate::archive::deposit(&cfg, &dest_archive, &app_id, &version, target).await |
| 2155 |
})?; |
| 2156 |
|
| 2157 |
events::emit( |
| 2158 |
&self.events, |
| 2159 |
Event::ArtifactCollected { |
| 2160 |
app: self.app.clone(), |
| 2161 |
target: self.target, |
| 2162 |
path: dest_s, |
| 2163 |
bytes: dir_size(&dest).unwrap_or(0), |
| 2164 |
}, |
| 2165 |
); |
| 2166 |
Ok(()) |
| 2167 |
} |
| 2168 |
|
| 2169 |
|
| 2170 |
|
| 2171 |
|
| 2172 |
|
| 2173 |
fn assert_siblings_green(self: &Arc<Self>, declared: &[Target]) -> Result<()> { |
| 2174 |
let me = self.clone(); |
| 2175 |
let (app_s, ver_s) = (self.app.to_string(), self.version.to_string()); |
| 2176 |
let rows: Vec<(String, String)> = self.rt.block_on(async move { |
| 2177 |
sqlx::query_as( |
| 2178 |
"SELECT target, status FROM target_runs tr |
| 2179 |
WHERE app = ?1 AND version = ?2 |
| 2180 |
AND id = (SELECT MAX(id) FROM target_runs |
| 2181 |
WHERE app = ?1 AND version = ?2 AND target = tr.target)", |
| 2182 |
) |
| 2183 |
.bind(app_s) |
| 2184 |
.bind(ver_s) |
| 2185 |
.fetch_all(&me.pool) |
| 2186 |
.await |
| 2187 |
.unwrap_or_default() |
| 2188 |
}); |
| 2189 |
let status_of = |t: &Target| -> Option<String> { |
| 2190 |
let key = t.to_string(); |
| 2191 |
rows.iter() |
| 2192 |
.find(|(name, _)| name == &key) |
| 2193 |
.map(|(_, s)| s.clone()) |
| 2194 |
}; |
| 2195 |
let not_green: Vec<String> = declared |
| 2196 |
.iter() |
| 2197 |
.filter(|t| **t != self.target) |
| 2198 |
.filter(|t| status_of(t).as_deref() != Some("ok")) |
| 2199 |
.map(|t| format!("{t} ({})", status_of(t).unwrap_or_else(|| "no run".into()))) |
| 2200 |
.collect(); |
| 2201 |
anyhow::ensure!( |
| 2202 |
not_green.is_empty(), |
| 2203 |
"all-targets-green gate: refusing to publish {} {} — not green: {}", |
| 2204 |
self.app, |
| 2205 |
self.version, |
| 2206 |
not_green.join(", "), |
| 2207 |
); |
| 2208 |
Ok(()) |
| 2209 |
} |
| 2210 |
|
| 2211 |
fn publish( |
| 2212 |
self: &Arc<Self>, |
| 2213 |
channel: &str, |
| 2214 |
app: &str, |
| 2215 |
target: &str, |
| 2216 |
version: &str, |
| 2217 |
artifact: &str, |
| 2218 |
meta: &Map, |
| 2219 |
) -> Result<String> { |
| 2220 |
|
| 2221 |
|
| 2222 |
|
| 2223 |
anyhow::ensure!( |
| 2224 |
!self.is_cancelled(), |
| 2225 |
"build superseded by a newer request; refusing to publish" |
| 2226 |
); |
| 2227 |
|
| 2228 |
|
| 2229 |
|
| 2230 |
|
| 2231 |
|
| 2232 |
|
| 2233 |
if let Some(declared) = self.all_green_required.clone() { |
| 2234 |
self.assert_siblings_green(&declared)?; |
| 2235 |
} |
| 2236 |
let backend = self |
| 2237 |
.ota |
| 2238 |
.get(channel) |
| 2239 |
.ok_or_else(|| anyhow::anyhow!("unknown publish channel `{channel}`"))?; |
| 2240 |
let target: Target = target.parse().map_err(|e: String| anyhow::anyhow!(e))?; |
| 2241 |
let version = Version::parse(version).map_err(|e| anyhow::anyhow!(e))?; |
| 2242 |
let app = AppId::new(app); |
| 2243 |
|
| 2244 |
|
| 2245 |
|
| 2246 |
|
| 2247 |
anyhow::ensure!( |
| 2248 |
backend.supports(target), |
| 2249 |
"publish channel `{channel}` does not support target {target}", |
| 2250 |
); |
| 2251 |
|
| 2252 |
|
| 2253 |
|
| 2254 |
|
| 2255 |
|
| 2256 |
|
| 2257 |
{ |
| 2258 |
let (app_s, target_s, chan_s) = |
| 2259 |
(app.to_string(), target.to_string(), channel.to_string()); |
| 2260 |
let me = self.clone(); |
| 2261 |
let latest: Option<Version> = self.rt.block_on(async move { |
| 2262 |
let rows: Vec<(String,)> = sqlx::query_as( |
| 2263 |
"SELECT version FROM releases WHERE app = ? AND target = ? AND channel = ?", |
| 2264 |
) |
| 2265 |
.bind(app_s) |
| 2266 |
.bind(target_s) |
| 2267 |
.bind(chan_s) |
| 2268 |
.fetch_all(&me.pool) |
| 2269 |
.await |
| 2270 |
.unwrap_or_default(); |
| 2271 |
rows.into_iter() |
| 2272 |
.filter_map(|(v,)| Version::parse(&v).ok()) |
| 2273 |
.max() |
| 2274 |
}); |
| 2275 |
if let Some(latest) = latest { |
| 2276 |
anyhow::ensure!( |
| 2277 |
version > latest, |
| 2278 |
"refusing to publish {app} {version} to `{channel}` ({target}): \ |
| 2279 |
not newer than the last published {latest}", |
| 2280 |
); |
| 2281 |
} |
| 2282 |
} |
| 2283 |
|
| 2284 |
|
| 2285 |
|
| 2286 |
|
| 2287 |
|
| 2288 |
let authority = { |
| 2289 |
let failed = self.failed_steps.lock().unwrap(); |
| 2290 |
let gatekeeper = *self.gatekeeper_ok.lock().unwrap(); |
| 2291 |
PublishAuthority::prove(target, failed.as_slice(), gatekeeper)? |
| 2292 |
}; |
| 2293 |
let notes = meta |
| 2294 |
.get("notes") |
| 2295 |
.and_then(|v| v.clone().into_string().ok()) |
| 2296 |
.unwrap_or_default(); |
| 2297 |
|
| 2298 |
let artifact_path = { |
| 2299 |
let p = PathBuf::from(artifact); |
| 2300 |
if p.is_absolute() { |
| 2301 |
p |
| 2302 |
} else { |
| 2303 |
self.collect_dest(app.as_str(), &version.to_string()) |
| 2304 |
.join(artifact) |
| 2305 |
} |
| 2306 |
}; |
| 2307 |
let rel = Release { |
| 2308 |
app: &app, |
| 2309 |
target, |
| 2310 |
version: &version, |
| 2311 |
notes, |
| 2312 |
}; |
| 2313 |
let receipt = backend |
| 2314 |
.publish(&rel, &artifact_path, &authority) |
| 2315 |
.with_context(|| format!("publish to `{channel}`"))?; |
| 2316 |
|
| 2317 |
|
| 2318 |
|
| 2319 |
|
| 2320 |
|
| 2321 |
|
| 2322 |
|
| 2323 |
|
| 2324 |
|
| 2325 |
|
| 2326 |
|
| 2327 |
|
| 2328 |
let artifact_hash: Option<String> = artifact_path |
| 2329 |
.file_name() |
| 2330 |
.and_then(|n| n.to_str()) |
| 2331 |
.and_then(|n| self.artifact_hashes.lock().unwrap().get(n).cloned()) |
| 2332 |
.or_else(|| sha256_file(&artifact_path).ok()); |
| 2333 |
let me = self.clone(); |
| 2334 |
let (app_s, target_s, ver_s, chan_s) = ( |
| 2335 |
app.to_string(), |
| 2336 |
target.to_string(), |
| 2337 |
version.to_string(), |
| 2338 |
channel.to_string(), |
| 2339 |
); |
| 2340 |
self.rt |
| 2341 |
.block_on(async move { |
| 2342 |
sqlx::query( |
| 2343 |
"INSERT OR IGNORE INTO releases (app, target, version, channel, artifact_hash, published_at) |
| 2344 |
VALUES (?, ?, ?, ?, ?, ?)", |
| 2345 |
) |
| 2346 |
.bind(app_s) |
| 2347 |
.bind(target_s) |
| 2348 |
.bind(ver_s) |
| 2349 |
.bind(chan_s) |
| 2350 |
.bind(artifact_hash) |
| 2351 |
.bind(Self::now()) |
| 2352 |
.execute(&me.pool) |
| 2353 |
.await |
| 2354 |
}) |
| 2355 |
.context("recording release in the idempotency ledger (artifact published but ledger write failed)")?; |
| 2356 |
events::emit( |
| 2357 |
&self.events, |
| 2358 |
Event::PublishOk { |
| 2359 |
app: self.app.clone(), |
| 2360 |
target: self.target, |
| 2361 |
channel: channel.to_string(), |
| 2362 |
}, |
| 2363 |
); |
| 2364 |
Ok(receipt) |
| 2365 |
} |
| 2366 |
} |
| 2367 |
|
| 2368 |
fn dir_size(p: &Path) -> Option<i64> { |
| 2369 |
let mut total = 0i64; |
| 2370 |
for entry in std::fs::read_dir(p).ok()? { |
| 2371 |
let entry = entry.ok()?; |
| 2372 |
let md = entry.metadata().ok()?; |
| 2373 |
if md.is_file() { |
| 2374 |
total += md.len() as i64; |
| 2375 |
} else if md.is_dir() { |
| 2376 |
|
| 2377 |
total += dir_size(&entry.path()).unwrap_or(0); |
| 2378 |
} |
| 2379 |
} |
| 2380 |
Some(total) |
| 2381 |
} |
| 2382 |
|
| 2383 |
|
| 2384 |
|
| 2385 |
|
| 2386 |
|
| 2387 |
|
| 2388 |
fn register_macos_fns(engine: &mut Engine, ctx: &Arc<RecipeCtx>) { |
| 2389 |
{ |
| 2390 |
let ctx = ctx.clone(); |
| 2391 |
engine.register_fn( |
| 2392 |
"verify_gatekeeper", |
| 2393 |
move |host: &str, path: &str| -> Result<bool, Box<EvalAltResult>> { |
| 2394 |
|
| 2395 |
|
| 2396 |
|
| 2397 |
|
| 2398 |
|
| 2399 |
|
| 2400 |
let q = ops_core::remote::sh_quote(path); |
| 2401 |
let cmd = format!( |
| 2402 |
"out=$(spctl --assess -vv --type install {q} 2>&1); printf '%s\\n' \"$out\"; \ |
| 2403 |
printf '%s' \"$out\" | grep -q 'source=Notarized Developer ID' \ |
| 2404 |
&& echo BENTO_GATEKEEPER_OK || echo BENTO_GATEKEEPER_FAIL", |
| 2405 |
); |
| 2406 |
let (_, tail) = ctx.run(host, &cmd).map_err(rhai_err)?; |
| 2407 |
let accepted = tail.contains("BENTO_GATEKEEPER_OK"); |
| 2408 |
|
| 2409 |
|
| 2410 |
|
| 2411 |
*ctx.gatekeeper_ok.lock().unwrap() = Some(accepted); |
| 2412 |
if !accepted { |
| 2413 |
ctx.fail_current_step(); |
| 2414 |
} |
| 2415 |
Ok(accepted) |
| 2416 |
}, |
| 2417 |
); |
| 2418 |
} |
| 2419 |
{ |
| 2420 |
let ctx = ctx.clone(); |
| 2421 |
engine.register_fn( |
| 2422 |
"codesign", |
| 2423 |
move |host: &str, identity: &str, path: &str| -> Result<(), Box<EvalAltResult>> { |
| 2424 |
let cmd = format!( |
| 2425 |
"codesign --force --options runtime --timestamp --sign {} {}", |
| 2426 |
ops_core::remote::sh_quote(identity), |
| 2427 |
ops_core::remote::sh_quote(path), |
| 2428 |
); |
| 2429 |
let (code, _) = ctx.run(host, &cmd).map_err(rhai_err)?; |
| 2430 |
if code != 0 { |
| 2431 |
return Err(rhai_err("codesign failed")); |
| 2432 |
} |
| 2433 |
Ok(()) |
| 2434 |
}, |
| 2435 |
); |
| 2436 |
} |
| 2437 |
{ |
| 2438 |
let ctx = ctx.clone(); |
| 2439 |
engine.register_fn( |
| 2440 |
"staple", |
| 2441 |
move |host: &str, path: &str| -> Result<(), Box<EvalAltResult>> { |
| 2442 |
let (code, _) = ctx |
| 2443 |
.run( |
| 2444 |
host, |
| 2445 |
&format!("xcrun stapler staple {}", ops_core::remote::sh_quote(path)), |
| 2446 |
) |
| 2447 |
.map_err(rhai_err)?; |
| 2448 |
if code != 0 { |
| 2449 |
return Err(rhai_err("stapler failed")); |
| 2450 |
} |
| 2451 |
Ok(()) |
| 2452 |
}, |
| 2453 |
); |
| 2454 |
} |
| 2455 |
{ |
| 2456 |
let ctx = ctx.clone(); |
| 2457 |
engine.register_fn( |
| 2458 |
"notarize", |
| 2459 |
move |host: &str, path: &str| -> Result<String, Box<EvalAltResult>> { |
| 2460 |
ctx.notarize(host, path).map_err(rhai_err) |
| 2461 |
}, |
| 2462 |
); |
| 2463 |
} |
| 2464 |
{ |
| 2465 |
let ctx = ctx.clone(); |
| 2466 |
engine.register_fn( |
| 2467 |
"keychain_open", |
| 2468 |
move |host: &str, name: &str| -> Result<(), Box<EvalAltResult>> { |
| 2469 |
|
| 2470 |
|
| 2471 |
let (code, _) = ctx |
| 2472 |
.run( |
| 2473 |
host, |
| 2474 |
&format!( |
| 2475 |
". ~/.tauri/passwords.env && ./dist/build-keychain.sh open {}", |
| 2476 |
ops_core::remote::sh_quote(name) |
| 2477 |
), |
| 2478 |
) |
| 2479 |
.map_err(rhai_err)?; |
| 2480 |
if code != 0 { |
| 2481 |
return Err(rhai_err("keychain_open failed")); |
| 2482 |
} |
| 2483 |
Ok(()) |
| 2484 |
}, |
| 2485 |
); |
| 2486 |
} |
| 2487 |
{ |
| 2488 |
let ctx = ctx.clone(); |
| 2489 |
engine.register_fn( |
| 2490 |
"keychain_close", |
| 2491 |
move |host: &str, name: &str| -> Result<(), Box<EvalAltResult>> { |
| 2492 |
let _ = ctx.run( |
| 2493 |
host, |
| 2494 |
&format!( |
| 2495 |
"./dist/build-keychain.sh close {}", |
| 2496 |
ops_core::remote::sh_quote(name) |
| 2497 |
), |
| 2498 |
); |
| 2499 |
Ok(()) |
| 2500 |
}, |
| 2501 |
); |
| 2502 |
} |
| 2503 |
} |
| 2504 |
|
| 2505 |
impl RecipeCtx { |
| 2506 |
|
| 2507 |
|
| 2508 |
fn notarize(self: &Arc<Self>, host: &str, path: &str) -> Result<String> { |
| 2509 |
const MAX_ATTEMPTS: u32 = 3; |
| 2510 |
let backoff = self |
| 2511 |
.cfg |
| 2512 |
.notarize_backoff_secs |
| 2513 |
.map_or(std::time::Duration::from_secs(15), |s| { |
| 2514 |
std::time::Duration::from_secs(s) |
| 2515 |
}); |
| 2516 |
let cmd = format!( |
| 2517 |
". ~/.tauri/passwords.env && xcrun notarytool submit {} \ |
| 2518 |
--key \"$NOTARY_KEY\" --key-id \"$NOTARY_KEY_ID\" --issuer \"$NOTARY_ISSUER\" \ |
| 2519 |
--wait --output-format json", |
| 2520 |
ops_core::remote::sh_quote(path), |
| 2521 |
); |
| 2522 |
let mut last = String::new(); |
| 2523 |
for attempt in 1..=MAX_ATTEMPTS { |
| 2524 |
let (code, tail) = self.run(host, &cmd)?; |
| 2525 |
if code == 0 && notary_accepted(&tail) { |
| 2526 |
return Ok(tail); |
| 2527 |
} |
| 2528 |
last = tail; |
| 2529 |
if attempt < MAX_ATTEMPTS { |
| 2530 |
events::emit( |
| 2531 |
&self.events, |
| 2532 |
Event::NotarizeRetry { |
| 2533 |
app: self.app.clone(), |
| 2534 |
target: self.target, |
| 2535 |
attempt, |
| 2536 |
reason: format!("exit {code}"), |
| 2537 |
}, |
| 2538 |
); |
| 2539 |
self.rt.block_on(tokio::time::sleep(backoff)); |
| 2540 |
} |
| 2541 |
} |
| 2542 |
anyhow::bail!("notarization failed after {MAX_ATTEMPTS} attempts: {last}") |
| 2543 |
} |
| 2544 |
} |
| 2545 |
|
| 2546 |
|
| 2547 |
|
| 2548 |
|
| 2549 |
|
| 2550 |
|
| 2551 |
|
| 2552 |
fn notary_accepted(output: &str) -> bool { |
| 2553 |
let (Some(start), Some(end)) = (output.find('{'), output.rfind('}')) else { |
| 2554 |
return false; |
| 2555 |
}; |
| 2556 |
if start > end { |
| 2557 |
return false; |
| 2558 |
} |
| 2559 |
serde_json::from_str::<serde_json::Value>(&output[start..=end]) |
| 2560 |
.ok() |
| 2561 |
.and_then(|v| { |
| 2562 |
v.get("status") |
| 2563 |
.and_then(|s| s.as_str()) |
| 2564 |
.map(|s| s.eq_ignore_ascii_case("accepted")) |
| 2565 |
}) |
| 2566 |
.unwrap_or(false) |
| 2567 |
} |
| 2568 |
|
| 2569 |
#[cfg(test)] |
| 2570 |
mod tests { |
| 2571 |
use super::*; |
| 2572 |
|
| 2573 |
|
| 2574 |
|
| 2575 |
|
| 2576 |
|
| 2577 |
pub(crate) fn write_bundle_fixture(root: &Path) { |
| 2578 |
std::fs::create_dir_all(root.join("migrations")).unwrap(); |
| 2579 |
std::fs::write(root.join("pom"), b"binary-bytes").unwrap(); |
| 2580 |
std::fs::write(root.join("migrations/001_init.sql"), b"create table a;").unwrap(); |
| 2581 |
std::fs::write(root.join("migrations/002_next.sql"), b"alter table a;").unwrap(); |
| 2582 |
} |
| 2583 |
|
| 2584 |
|
| 2585 |
|
| 2586 |
|
| 2587 |
|
| 2588 |
|
| 2589 |
|
| 2590 |
|
| 2591 |
|
| 2592 |
pub(crate) const BUNDLE_FIXTURE_MANIFEST: &str = concat!( |
| 2593 |
"e4c908e219c533fa7ad7ea1634398f9bf51637ba20717769ada545bab26d7368 migrations/001_init.sql\n", |
| 2594 |
"b026fd51bae096b34672cefdb781b6585b13efb53bc301d50c305f422552a380 migrations/002_next.sql\n", |
| 2595 |
"71227a7f160afca3fb3c39f448735886dda7bd366252580c2222fb87d4bb4d85 pom\n", |
| 2596 |
); |
| 2597 |
|
| 2598 |
|
| 2599 |
|
| 2600 |
|
| 2601 |
|
| 2602 |
|
| 2603 |
|
| 2604 |
|
| 2605 |
#[test] |
| 2606 |
fn a_collected_bundle_manifests_exactly_as_the_verifier_will_read_it() { |
| 2607 |
let dir = tempfile::tempdir().unwrap(); |
| 2608 |
write_bundle_fixture(dir.path()); |
| 2609 |
|
| 2610 |
let files = collected_files(dir.path()).unwrap(); |
| 2611 |
assert_eq!( |
| 2612 |
files.iter().map(|(r, _)| r.as_str()).collect::<Vec<_>>(), |
| 2613 |
vec!["migrations/001_init.sql", "migrations/002_next.sql", "pom"], |
| 2614 |
"recursive, relative, sorted" |
| 2615 |
); |
| 2616 |
|
| 2617 |
let hashes: Vec<(String, String)> = files |
| 2618 |
.into_iter() |
| 2619 |
.map(|(rel, path)| (rel, sha256_file(&path).unwrap())) |
| 2620 |
.collect(); |
| 2621 |
let manifest = ops_artifact::Manifest::new(hashes).unwrap(); |
| 2622 |
assert_eq!(manifest.to_text(), BUNDLE_FIXTURE_MANIFEST); |
| 2623 |
} |
| 2624 |
|
| 2625 |
|
| 2626 |
|
| 2627 |
|
| 2628 |
#[test] |
| 2629 |
#[cfg(unix)] |
| 2630 |
fn a_symlink_in_the_collect_dir_is_not_part_of_the_bundle() { |
| 2631 |
let dir = tempfile::tempdir().unwrap(); |
| 2632 |
write_bundle_fixture(dir.path()); |
| 2633 |
let outside = dir.path().join("..").join("secret.env"); |
| 2634 |
std::fs::write(&outside, b"TOKEN=1").ok(); |
| 2635 |
std::os::unix::fs::symlink(&outside, dir.path().join("link.env")).unwrap(); |
| 2636 |
|
| 2637 |
let files = collected_files(dir.path()).unwrap(); |
| 2638 |
assert!( |
| 2639 |
!files.iter().any(|(rel, _)| rel.contains("link.env")), |
| 2640 |
"{files:?}" |
| 2641 |
); |
| 2642 |
} |
| 2643 |
|
| 2644 |
|
| 2645 |
|
| 2646 |
|
| 2647 |
#[tokio::test] |
| 2648 |
async fn begin_step_bails_when_cancelled() { |
| 2649 |
let dir = tempfile::tempdir().unwrap(); |
| 2650 |
let cfg = Arc::new(Config::for_tests(dir.path())); |
| 2651 |
let pool = crate::db::open(&cfg.db_path).await.unwrap(); |
| 2652 |
let cancel = Arc::new(AtomicBool::new(true)); |
| 2653 |
let ctx = Arc::new(RecipeCtx::new( |
| 2654 |
AppId::new("demo"), |
| 2655 |
Version::parse("0.1.0").unwrap(), |
| 2656 |
"linux/x86_64".parse().unwrap(), |
| 2657 |
"fw13".into(), |
| 2658 |
"local".into(), |
| 2659 |
"v0.1.0".into(), |
| 2660 |
"/tmp".into(), |
| 2661 |
vec![], |
| 2662 |
Kind::App, |
| 2663 |
1, |
| 2664 |
Arc::new(std::collections::HashMap::new()), |
| 2665 |
Arc::new(std::collections::HashMap::new()), |
| 2666 |
None, |
| 2667 |
pool, |
| 2668 |
crate::events::channel(), |
| 2669 |
cfg, |
| 2670 |
Arc::new(OtaRegistry::standard("https://makenot.work")), |
| 2671 |
tokio::runtime::Handle::current(), |
| 2672 |
cancel.clone(), |
| 2673 |
None, |
| 2674 |
)); |
| 2675 |
|
| 2676 |
|
| 2677 |
let err = ctx.begin_step(Step::Build).unwrap_err(); |
| 2678 |
assert!(err.to_string().contains("supersede"), "got: {err}"); |
| 2679 |
assert!(ctx.is_cancelled()); |
| 2680 |
} |
| 2681 |
|
| 2682 |
|
| 2683 |
|
| 2684 |
|
| 2685 |
#[tokio::test] |
| 2686 |
async fn feature_flags_renders_whole_flag_or_empty() { |
| 2687 |
async fn flags_for(features: Vec<String>) -> String { |
| 2688 |
let dir = tempfile::tempdir().unwrap(); |
| 2689 |
let cfg = Arc::new(Config::for_tests(dir.path())); |
| 2690 |
let pool = crate::db::open(&cfg.db_path).await.unwrap(); |
| 2691 |
let ctx = Arc::new(RecipeCtx::new( |
| 2692 |
AppId::new("demo"), |
| 2693 |
Version::parse("0.1.0").unwrap(), |
| 2694 |
"linux/x86_64".parse().unwrap(), |
| 2695 |
"fw13".into(), |
| 2696 |
"local".into(), |
| 2697 |
"v0.1.0".into(), |
| 2698 |
"/tmp".into(), |
| 2699 |
features, |
| 2700 |
Kind::App, |
| 2701 |
1, |
| 2702 |
Arc::new(std::collections::HashMap::new()), |
| 2703 |
Arc::new(std::collections::HashMap::new()), |
| 2704 |
None, |
| 2705 |
pool, |
| 2706 |
crate::events::channel(), |
| 2707 |
cfg, |
| 2708 |
Arc::new(OtaRegistry::standard("https://makenot.work")), |
| 2709 |
tokio::runtime::Handle::current(), |
| 2710 |
Arc::new(AtomicBool::new(false)), |
| 2711 |
None, |
| 2712 |
)); |
| 2713 |
let engine = build_engine(&ctx); |
| 2714 |
engine.eval::<String>("feature_flags()").unwrap() |
| 2715 |
} |
| 2716 |
|
| 2717 |
assert_eq!(flags_for(vec![]).await, ""); |
| 2718 |
assert_eq!( |
| 2719 |
flags_for(vec!["supernote".into()]).await, |
| 2720 |
"--features supernote" |
| 2721 |
); |
| 2722 |
assert_eq!( |
| 2723 |
flags_for(vec!["supernote".into(), "extra".into()]).await, |
| 2724 |
"--features supernote,extra" |
| 2725 |
); |
| 2726 |
} |
| 2727 |
|
| 2728 |
|
| 2729 |
|
| 2730 |
|
| 2731 |
|
| 2732 |
|
| 2733 |
|
| 2734 |
#[tokio::test] |
| 2735 |
async fn repo_resolves_per_build_host() { |
| 2736 |
async fn repo_on(build_host: &str) -> String { |
| 2737 |
let dir = tempfile::tempdir().unwrap(); |
| 2738 |
let cfg = Arc::new(Config::for_tests(dir.path())); |
| 2739 |
let pool = crate::db::open(&cfg.db_path).await.unwrap(); |
| 2740 |
let ctx = Arc::new( |
| 2741 |
RecipeCtx::new( |
| 2742 |
AppId::new("demo"), |
| 2743 |
Version::parse("0.1.0").unwrap(), |
| 2744 |
"linux/x86_64".parse().unwrap(), |
| 2745 |
build_host.into(), |
| 2746 |
"local".into(), |
| 2747 |
"v0.1.0".into(), |
| 2748 |
"~/Code/Apps/demo".into(), |
| 2749 |
vec![], |
| 2750 |
Kind::App, |
| 2751 |
1, |
| 2752 |
Arc::new(std::collections::HashMap::new()), |
| 2753 |
Arc::new(std::collections::HashMap::new()), |
| 2754 |
None, |
| 2755 |
pool, |
| 2756 |
crate::events::channel(), |
| 2757 |
cfg, |
| 2758 |
Arc::new(OtaRegistry::standard("https://makenot.work")), |
| 2759 |
tokio::runtime::Handle::current(), |
| 2760 |
Arc::new(AtomicBool::new(false)), |
| 2761 |
None, |
| 2762 |
) |
| 2763 |
.with_repo_by_host(HashMap::from([( |
| 2764 |
"windows-x86".to_string(), |
| 2765 |
"C:/Users/me/Code/Apps/demo".to_string(), |
| 2766 |
)])), |
| 2767 |
); |
| 2768 |
build_engine(&ctx).eval::<String>("repo()").unwrap() |
| 2769 |
} |
| 2770 |
|
| 2771 |
assert_eq!(repo_on("windows-x86").await, "C:/Users/me/Code/Apps/demo"); |
| 2772 |
assert_eq!(repo_on("fw13").await, "~/Code/Apps/demo"); |
| 2773 |
} |
| 2774 |
|
| 2775 |
|
| 2776 |
|
| 2777 |
|
| 2778 |
#[tokio::test] |
| 2779 |
async fn secret_reads_under_root_and_blocks_traversal() { |
| 2780 |
let dir = tempfile::tempdir().unwrap(); |
| 2781 |
let cfg = Config::for_tests(dir.path()); |
| 2782 |
|
| 2783 |
|
| 2784 |
std::fs::create_dir_all(&cfg.secrets_root).unwrap(); |
| 2785 |
std::fs::write(cfg.secrets_root.join("token"), "s3cr3t\n").unwrap(); |
| 2786 |
std::fs::create_dir_all(cfg.secrets_root.join("app")).unwrap(); |
| 2787 |
std::fs::write(cfg.secrets_root.join("app").join("key"), "nested").unwrap(); |
| 2788 |
|
| 2789 |
std::fs::write(dir.path().join("outside"), "leak").unwrap(); |
| 2790 |
|
| 2791 |
let cfg = Arc::new(cfg); |
| 2792 |
let pool = crate::db::open(&cfg.db_path).await.unwrap(); |
| 2793 |
let ctx = Arc::new(RecipeCtx::new( |
| 2794 |
AppId::new("demo"), |
| 2795 |
Version::parse("0.1.0").unwrap(), |
| 2796 |
"linux/x86_64".parse().unwrap(), |
| 2797 |
"fw13".into(), |
| 2798 |
"local".into(), |
| 2799 |
"v0.1.0".into(), |
| 2800 |
"/tmp".into(), |
| 2801 |
vec![], |
| 2802 |
Kind::App, |
| 2803 |
1, |
| 2804 |
Arc::new(std::collections::HashMap::new()), |
| 2805 |
Arc::new(std::collections::HashMap::new()), |
| 2806 |
None, |
| 2807 |
pool, |
| 2808 |
crate::events::channel(), |
| 2809 |
cfg, |
| 2810 |
Arc::new(OtaRegistry::standard("https://makenot.work")), |
| 2811 |
tokio::runtime::Handle::current(), |
| 2812 |
Arc::new(AtomicBool::new(false)), |
| 2813 |
None, |
| 2814 |
)); |
| 2815 |
let engine = build_engine(&ctx); |
| 2816 |
|
| 2817 |
|
| 2818 |
assert_eq!( |
| 2819 |
engine.eval::<String>(r#"secret("token")"#).unwrap(), |
| 2820 |
"s3cr3t" |
| 2821 |
); |
| 2822 |
|
| 2823 |
assert_eq!( |
| 2824 |
engine.eval::<String>(r#"secret("app/key")"#).unwrap(), |
| 2825 |
"nested" |
| 2826 |
); |
| 2827 |
|
| 2828 |
|
| 2829 |
|
| 2830 |
for bad in [ |
| 2831 |
r#"secret("../outside")"#, |
| 2832 |
r#"secret("/etc/passwd")"#, |
| 2833 |
r#"secret("")"#, |
| 2834 |
] { |
| 2835 |
let err = engine.eval::<String>(bad).unwrap_err().to_string(); |
| 2836 |
assert!( |
| 2837 |
err.contains("relative path under secrets_root"), |
| 2838 |
"`{bad}` should hit the traversal guard, got: {err}" |
| 2839 |
); |
| 2840 |
} |
| 2841 |
|
| 2842 |
|
| 2843 |
let err = engine |
| 2844 |
.eval::<String>(r#"secret("nope")"#) |
| 2845 |
.unwrap_err() |
| 2846 |
.to_string(); |
| 2847 |
assert!(err.contains("secret `nope`"), "got: {err}"); |
| 2848 |
} |
| 2849 |
|
| 2850 |
|
| 2851 |
#[test] |
| 2852 |
fn preflight_catches_a_dead_repository_url() { |
| 2853 |
|
| 2854 |
|
| 2855 |
let meta = CrateMeta { |
| 2856 |
name: "pter".into(), |
| 2857 |
version: "0.1.0".into(), |
| 2858 |
repository: Some("https://github.com/maxjacobson/pter".into()), |
| 2859 |
description: Some("d".into()), |
| 2860 |
licensed: true, |
| 2861 |
}; |
| 2862 |
let problems = crate_publish_problems(&meta, false, &[], true); |
| 2863 |
assert_eq!(problems.len(), 1, "{problems:?}"); |
| 2864 |
assert!( |
| 2865 |
problems[0].contains("not publicly clonable"), |
| 2866 |
"{problems:?}" |
| 2867 |
); |
| 2868 |
|
| 2869 |
|
| 2870 |
assert!(crate_publish_problems(&meta, true, &[], true).is_empty()); |
| 2871 |
} |
| 2872 |
|
| 2873 |
#[test] |
| 2874 |
fn preflight_requires_the_fields_crates_io_bakes_in() { |
| 2875 |
let bare = CrateMeta { |
| 2876 |
name: "x".into(), |
| 2877 |
version: "0.1.0".into(), |
| 2878 |
repository: None, |
| 2879 |
description: None, |
| 2880 |
licensed: false, |
| 2881 |
}; |
| 2882 |
let problems = crate_publish_problems(&bare, false, &[], true); |
| 2883 |
assert_eq!(problems.len(), 3, "{problems:?}"); |
| 2884 |
assert!(problems.iter().any(|p| p.contains("repository"))); |
| 2885 |
assert!(problems.iter().any(|p| p.contains("description"))); |
| 2886 |
assert!(problems.iter().any(|p| p.contains("license"))); |
| 2887 |
} |
| 2888 |
|
| 2889 |
|
| 2890 |
|
| 2891 |
|
| 2892 |
|
| 2893 |
|
| 2894 |
|
| 2895 |
#[test] |
| 2896 |
fn a_library_verify_is_not_gated_on_gatekeeper() { |
| 2897 |
assert_eq!( |
| 2898 |
action_for(Step::Verify, Kind::Library), |
| 2899 |
Action::Build, |
| 2900 |
"a crate preflight runs the build toolchain; that is what it needs", |
| 2901 |
); |
| 2902 |
assert_eq!( |
| 2903 |
action_for(Step::Verify, Kind::App), |
| 2904 |
Action::Observe(ObserveKind::Custom("gatekeeper".into())), |
| 2905 |
"an app's verify still proves the bundle is signed and notarized", |
| 2906 |
); |
| 2907 |
} |
| 2908 |
|
| 2909 |
|
| 2910 |
|
| 2911 |
#[test] |
| 2912 |
fn a_default_host_can_run_a_library_verify_and_not_an_app_one() { |
| 2913 |
let caps = |
| 2914 |
ops_exec::CapabilitySet::from_tokens(["build", "package"], ["build-log", "artifact"]); |
| 2915 |
assert!(caps.permits(&action_for(Step::Verify, Kind::Library))); |
| 2916 |
assert!(!caps.permits(&action_for(Step::Verify, Kind::App))); |
| 2917 |
} |
| 2918 |
|
| 2919 |
|
| 2920 |
|
| 2921 |
#[test] |
| 2922 |
fn no_other_step_changes_with_the_kind() { |
| 2923 |
for step in [ |
| 2924 |
Step::Checkout, |
| 2925 |
Step::Prebuild, |
| 2926 |
Step::Build, |
| 2927 |
Step::Sign, |
| 2928 |
Step::Notarize, |
| 2929 |
Step::Staple, |
| 2930 |
Step::Package, |
| 2931 |
Step::Publish, |
| 2932 |
Step::Collect, |
| 2933 |
] { |
| 2934 |
assert_eq!( |
| 2935 |
action_for(step, Kind::App), |
| 2936 |
action_for(step, Kind::Library), |
| 2937 |
"{step:?} should not depend on the kind", |
| 2938 |
); |
| 2939 |
} |
| 2940 |
} |
| 2941 |
|
| 2942 |
#[test] |
| 2943 |
fn preflight_rejects_republishing_the_same_version() { |
| 2944 |
let meta = CrateMeta { |
| 2945 |
name: "makeover".into(), |
| 2946 |
version: "0.10.0".into(), |
| 2947 |
repository: Some("https://git.sr.ht/~maxmj/makeover".into()), |
| 2948 |
description: Some("d".into()), |
| 2949 |
licensed: true, |
| 2950 |
}; |
| 2951 |
let problems = |
| 2952 |
crate_publish_problems(&meta, true, &["0.9.0".into(), "0.10.0".into()], true); |
| 2953 |
assert_eq!(problems.len(), 1, "{problems:?}"); |
| 2954 |
assert!(problems[0].contains("already published"), "{problems:?}"); |
| 2955 |
|
| 2956 |
|
| 2957 |
let mut next = meta.clone(); |
| 2958 |
next.version = "0.11.0".into(); |
| 2959 |
assert!(crate_publish_problems(&next, true, &["0.10.0".into()], true).is_empty()); |
| 2960 |
} |
| 2961 |
|
| 2962 |
|
| 2963 |
|
| 2964 |
|
| 2965 |
|
| 2966 |
#[test] |
| 2967 |
fn preflight_reports_missing_credentials_up_front() { |
| 2968 |
let meta = CrateMeta { |
| 2969 |
name: "makeover".into(), |
| 2970 |
version: "0.11.0".into(), |
| 2971 |
repository: Some("https://git.sr.ht/~maxmj/makeover".into()), |
| 2972 |
description: Some("d".into()), |
| 2973 |
licensed: true, |
| 2974 |
}; |
| 2975 |
|
| 2976 |
let problems = crate_publish_problems(&meta, true, &[], false); |
| 2977 |
assert_eq!(problems.len(), 1, "{problems:?}"); |
| 2978 |
assert!(problems[0].contains("credentials"), "{problems:?}"); |
| 2979 |
assert!( |
| 2980 |
problems[0].contains("cargo login"), |
| 2981 |
"should say how to fix it" |
| 2982 |
); |
| 2983 |
|
| 2984 |
|
| 2985 |
assert!(crate_publish_problems(&meta, true, &[], true).is_empty()); |
| 2986 |
} |
| 2987 |
|
| 2988 |
#[test] |
| 2989 |
fn crate_meta_reads_cargo_metadata_json() { |
| 2990 |
let raw = r#"{"packages":[{"name":"makeover","version":"0.10.0", |
| 2991 |
"repository":"https://git.sr.ht/~maxmj/makeover","description":"themes", |
| 2992 |
"license":"MIT"}]}"#; |
| 2993 |
let m = crate_meta_from_json(raw).unwrap(); |
| 2994 |
assert_eq!(m.name, "makeover"); |
| 2995 |
assert_eq!(m.version, "0.10.0"); |
| 2996 |
assert!(m.licensed); |
| 2997 |
assert_eq!( |
| 2998 |
m.repository.as_deref(), |
| 2999 |
Some("https://git.sr.ht/~maxmj/makeover") |
| 3000 |
); |
| 3001 |
|
| 3002 |
|
| 3003 |
|
| 3004 |
let lf = r#"{"packages":[{"name":"x","version":"0.1.0","license":"", |
| 3005 |
"license_file":"LICENSE","description":""}]}"#; |
| 3006 |
let m = crate_meta_from_json(lf).unwrap(); |
| 3007 |
assert!(m.licensed); |
| 3008 |
assert!(m.description.is_none()); |
| 3009 |
} |
| 3010 |
|
| 3011 |
|
| 3012 |
|
| 3013 |
|
| 3014 |
|
| 3015 |
|
| 3016 |
#[test] |
| 3017 |
fn expand_tilde_handles_home() { |
| 3018 |
let home = PathBuf::from(std::env::var("HOME").expect("HOME is set")); |
| 3019 |
assert_eq!(expand_tilde("~/Code/x"), home.join("Code/x")); |
| 3020 |
assert_eq!(expand_tilde("/abs/path"), PathBuf::from("/abs/path")); |
| 3021 |
} |
| 3022 |
|
| 3023 |
|
| 3024 |
|
| 3025 |
#[test] |
| 3026 |
fn resolve_artifact_match_wants_exactly_one() { |
| 3027 |
|
| 3028 |
assert_eq!( |
| 3029 |
resolve_artifact_match(" /d/App.AppImage \n", "*.AppImage", true).unwrap(), |
| 3030 |
"/d/App.AppImage" |
| 3031 |
); |
| 3032 |
} |
| 3033 |
|
| 3034 |
#[test] |
| 3035 |
fn resolve_artifact_match_zero_depends_on_required() { |
| 3036 |
|
| 3037 |
|
| 3038 |
let err = resolve_artifact_match("", "*.dmg", true).unwrap_err(); |
| 3039 |
assert!(err.to_string().contains("no artifact matched"), "{err}"); |
| 3040 |
|
| 3041 |
assert_eq!( |
| 3042 |
resolve_artifact_match("\n \n", "*.deb", false).unwrap(), |
| 3043 |
"" |
| 3044 |
); |
| 3045 |
} |
| 3046 |
|
| 3047 |
#[test] |
| 3048 |
fn resolve_artifact_match_rejects_ambiguous() { |
| 3049 |
|
| 3050 |
|
| 3051 |
for required in [true, false] { |
| 3052 |
let err = |
| 3053 |
resolve_artifact_match("/d/old.deb\n/d/new.deb\n", "*.deb", required).unwrap_err(); |
| 3054 |
let msg = err.to_string(); |
| 3055 |
assert!(msg.contains("ambiguous"), "{msg}"); |
| 3056 |
assert!(msg.contains("old.deb") && msg.contains("new.deb"), "{msg}"); |
| 3057 |
} |
| 3058 |
} |
| 3059 |
|
| 3060 |
#[test] |
| 3061 |
fn ensure_glob_safe_allows_paths_bars_commands() { |
| 3062 |
|
| 3063 |
assert!(ensure_glob_safe("~/Code/app/dist/*.AppImage").is_ok()); |
| 3064 |
assert!(ensure_glob_safe("/t/App_1.2.3-x86_64.dmg").is_ok()); |
| 3065 |
|
| 3066 |
for bad in ["*.dmg; rm -rf /", "$(evil)", "a|b", "a b"] { |
| 3067 |
assert!(ensure_glob_safe(bad).is_err(), "should reject {bad:?}"); |
| 3068 |
} |
| 3069 |
} |
| 3070 |
|
| 3071 |
|
| 3072 |
|
| 3073 |
#[test] |
| 3074 |
fn version_from_tauri_json_reads_version() { |
| 3075 |
assert_eq!( |
| 3076 |
version_from_tauri_json(r#"{"version":"0.4.2"}"#).unwrap(), |
| 3077 |
"0.4.2" |
| 3078 |
); |
| 3079 |
assert!(version_from_tauri_json(r#"{"productName":"X"}"#).is_err()); |
| 3080 |
} |
| 3081 |
|
| 3082 |
#[test] |
| 3083 |
fn version_from_cargo_toml_prefers_package_then_workspace() { |
| 3084 |
|
| 3085 |
assert_eq!( |
| 3086 |
version_from_cargo_toml("[package]\nname = \"x\"\nversion = \"0.5.0\"\n").unwrap(), |
| 3087 |
"0.5.0" |
| 3088 |
); |
| 3089 |
|
| 3090 |
assert_eq!( |
| 3091 |
version_from_cargo_toml("[workspace.package]\nversion = \"1.2.3\"\n").unwrap(), |
| 3092 |
"1.2.3" |
| 3093 |
); |
| 3094 |
|
| 3095 |
assert!(version_from_cargo_toml("[workspace]\nmembers = []\n").is_err()); |
| 3096 |
} |
| 3097 |
|
| 3098 |
#[test] |
| 3099 |
fn version_from_repo_default_and_explicit_paths() { |
| 3100 |
let tmp = tempfile::tempdir().unwrap(); |
| 3101 |
let root = tmp.path(); |
| 3102 |
|
| 3103 |
|
| 3104 |
let tauri = root.join("tauri"); |
| 3105 |
std::fs::create_dir_all(tauri.join("src-tauri")).unwrap(); |
| 3106 |
std::fs::write( |
| 3107 |
tauri.join("src-tauri/tauri.conf.json"), |
| 3108 |
r#"{"version":"0.4.2"}"#, |
| 3109 |
) |
| 3110 |
.unwrap(); |
| 3111 |
assert_eq!( |
| 3112 |
version_from_repo(tauri.to_str().unwrap(), None) |
| 3113 |
.unwrap() |
| 3114 |
.to_string(), |
| 3115 |
"0.4.2" |
| 3116 |
); |
| 3117 |
|
| 3118 |
|
| 3119 |
let ws = root.join("ws"); |
| 3120 |
std::fs::create_dir_all(ws.join("crates/app")).unwrap(); |
| 3121 |
std::fs::write( |
| 3122 |
ws.join("Cargo.toml"), |
| 3123 |
"[workspace]\nmembers = [\"crates/app\"]\n", |
| 3124 |
) |
| 3125 |
.unwrap(); |
| 3126 |
std::fs::write( |
| 3127 |
ws.join("crates/app/Cargo.toml"), |
| 3128 |
"[package]\nname = \"app\"\nversion = \"0.5.0\"\n", |
| 3129 |
) |
| 3130 |
.unwrap(); |
| 3131 |
assert_eq!( |
| 3132 |
version_from_repo(ws.to_str().unwrap(), Some("crates/app/Cargo.toml")) |
| 3133 |
.unwrap() |
| 3134 |
.to_string(), |
| 3135 |
"0.5.0" |
| 3136 |
); |
| 3137 |
} |
| 3138 |
|
| 3139 |
|
| 3140 |
|
| 3141 |
fn ver(s: &str) -> Version { |
| 3142 |
Version::parse(s).unwrap() |
| 3143 |
} |
| 3144 |
|
| 3145 |
#[test] |
| 3146 |
fn version_consistency_passes_when_all_sources_agree() { |
| 3147 |
let tmp = tempfile::tempdir().unwrap(); |
| 3148 |
let repo = tmp.path(); |
| 3149 |
std::fs::create_dir_all(repo.join("src-tauri")).unwrap(); |
| 3150 |
std::fs::write( |
| 3151 |
repo.join("src-tauri/tauri.conf.json"), |
| 3152 |
r#"{"version":"0.5.0"}"#, |
| 3153 |
) |
| 3154 |
.unwrap(); |
| 3155 |
std::fs::write( |
| 3156 |
repo.join("Cargo.toml"), |
| 3157 |
"[package]\nname = \"app\"\nversion = \"0.5.0\"\n", |
| 3158 |
) |
| 3159 |
.unwrap(); |
| 3160 |
check_version_consistency(repo.to_str().unwrap(), None, &ver("0.5.0")).unwrap(); |
| 3161 |
} |
| 3162 |
|
| 3163 |
#[test] |
| 3164 |
fn version_consistency_flags_tauri_vs_cargo_drift() { |
| 3165 |
|
| 3166 |
|
| 3167 |
let tmp = tempfile::tempdir().unwrap(); |
| 3168 |
let repo = tmp.path(); |
| 3169 |
std::fs::create_dir_all(repo.join("src-tauri")).unwrap(); |
| 3170 |
std::fs::write( |
| 3171 |
repo.join("src-tauri/tauri.conf.json"), |
| 3172 |
r#"{"version":"0.5.0"}"#, |
| 3173 |
) |
| 3174 |
.unwrap(); |
| 3175 |
std::fs::write( |
| 3176 |
repo.join("Cargo.toml"), |
| 3177 |
"[package]\nname = \"app\"\nversion = \"0.4.0\"\n", |
| 3178 |
) |
| 3179 |
.unwrap(); |
| 3180 |
let err = |
| 3181 |
check_version_consistency(repo.to_str().unwrap(), None, &ver("0.5.0")).unwrap_err(); |
| 3182 |
let msg = format!("{err:#}"); |
| 3183 |
assert!(msg.contains("Cargo.toml says 0.4.0"), "{msg}"); |
| 3184 |
} |
| 3185 |
|
| 3186 |
#[test] |
| 3187 |
fn version_consistency_flags_explicit_version_the_repo_does_not_reflect() { |
| 3188 |
let tmp = tempfile::tempdir().unwrap(); |
| 3189 |
let repo = tmp.path(); |
| 3190 |
std::fs::create_dir_all(repo.join("src-tauri")).unwrap(); |
| 3191 |
std::fs::write( |
| 3192 |
repo.join("src-tauri/tauri.conf.json"), |
| 3193 |
r#"{"version":"0.5.0"}"#, |
| 3194 |
) |
| 3195 |
.unwrap(); |
| 3196 |
let err = |
| 3197 |
check_version_consistency(repo.to_str().unwrap(), None, &ver("9.9.9")).unwrap_err(); |
| 3198 |
assert!(format!("{err:#}").contains("building 9.9.9")); |
| 3199 |
} |
| 3200 |
|
| 3201 |
#[test] |
| 3202 |
fn version_consistency_single_source_never_invents_drift() { |
| 3203 |
|
| 3204 |
|
| 3205 |
let tmp = tempfile::tempdir().unwrap(); |
| 3206 |
let repo = tmp.path(); |
| 3207 |
std::fs::create_dir_all(repo.join("crates/app")).unwrap(); |
| 3208 |
std::fs::write( |
| 3209 |
repo.join("Cargo.toml"), |
| 3210 |
"[workspace]\nmembers = [\"crates/app\"]\n", |
| 3211 |
) |
| 3212 |
.unwrap(); |
| 3213 |
std::fs::write( |
| 3214 |
repo.join("crates/app/Cargo.toml"), |
| 3215 |
"[package]\nname = \"app\"\nversion = \"0.5.0\"\n", |
| 3216 |
) |
| 3217 |
.unwrap(); |
| 3218 |
check_version_consistency( |
| 3219 |
repo.to_str().unwrap(), |
| 3220 |
Some("crates/app/Cargo.toml"), |
| 3221 |
&ver("0.5.0"), |
| 3222 |
) |
| 3223 |
.unwrap(); |
| 3224 |
} |
| 3225 |
|
| 3226 |
|
| 3227 |
|
| 3228 |
#[test] |
| 3229 |
fn versions_in_filename_extracts_only_real_semvers() { |
| 3230 |
assert_eq!( |
| 3231 |
versions_in_filename("GoingsOn_0.5.0_aarch64.dmg"), |
| 3232 |
vec![ver("0.5.0")] |
| 3233 |
); |
| 3234 |
assert_eq!( |
| 3235 |
versions_in_filename("AudioFiles-0.4.0-x86_64.AppImage"), |
| 3236 |
vec![ver("0.4.0")] |
| 3237 |
); |
| 3238 |
|
| 3239 |
assert!(versions_in_filename("latest.json").is_empty()); |
| 3240 |
assert!(versions_in_filename("app.sig").is_empty()); |
| 3241 |
} |
| 3242 |
|
| 3243 |
#[test] |
| 3244 |
fn assert_artifact_version_rejects_a_stale_artifact() { |
| 3245 |
|
| 3246 |
let err = |
| 3247 |
assert_artifact_version("AudioFiles-0.4.0-x86_64.AppImage", &ver("0.5.0")).unwrap_err(); |
| 3248 |
assert!(format!("{err:#}").contains("stale artifact"), "{err:#}"); |
| 3249 |
|
| 3250 |
assert_artifact_version("GoingsOn_0.5.0_aarch64.dmg", &ver("0.5.0")).unwrap(); |
| 3251 |
assert_artifact_version("latest.json", &ver("0.5.0")).unwrap(); |
| 3252 |
} |
| 3253 |
|
| 3254 |
|
| 3255 |
|
| 3256 |
|
| 3257 |
|
| 3258 |
|
| 3259 |
#[test] |
| 3260 |
fn glibc_versions_parse_from_what_the_tools_actually_print() { |
| 3261 |
|
| 3262 |
|
| 3263 |
let objdump = "GLIBC_2.2.5\nGLIBC_2.34\nGLIBC_2.9\nGLIBC_2.17\n"; |
| 3264 |
assert_eq!(max_glibc_symbol(objdump), Some((2, 34))); |
| 3265 |
|
| 3266 |
assert_eq!(max_glibc_symbol(""), None); |
| 3267 |
|
| 3268 |
|
| 3269 |
assert_eq!( |
| 3270 |
glibc_from_ldd("ldd (Ubuntu GLIBC 2.39-0ubuntu8.8) 2.39\nCopyright...\n"), |
| 3271 |
Some((2, 39)) |
| 3272 |
); |
| 3273 |
assert_eq!( |
| 3274 |
glibc_from_ldd("ldd (GNU libc) 2.41\nCopyright (C) 2025\n"), |
| 3275 |
Some((2, 41)) |
| 3276 |
); |
| 3277 |
assert_eq!(glibc_from_ldd(""), None); |
| 3278 |
} |
| 3279 |
|
| 3280 |
|
| 3281 |
|
| 3282 |
|
| 3283 |
#[test] |
| 3284 |
fn glibc_requirement_is_satisfied_by_equal_or_newer_only() { |
| 3285 |
let needs = max_glibc_symbol("GLIBC_2.41").unwrap(); |
| 3286 |
assert!(needs > glibc_from_ldd("ldd (Ubuntu GLIBC 2.39) 2.39").unwrap()); |
| 3287 |
assert!(needs <= glibc_from_ldd("ldd (GNU libc) 2.41").unwrap()); |
| 3288 |
assert!(needs <= glibc_from_ldd("ldd (GNU libc) 2.42").unwrap()); |
| 3289 |
assert!(needs <= glibc_from_ldd("ldd (GNU libc) 3.0").unwrap()); |
| 3290 |
} |
| 3291 |
|
| 3292 |
|
| 3293 |
|
| 3294 |
|
| 3295 |
|
| 3296 |
#[tokio::test] |
| 3297 |
async fn deploy_host_fns_explain_a_missing_destination_by_kind() { |
| 3298 |
let dir = tempfile::tempdir().unwrap(); |
| 3299 |
let cfg = Arc::new(Config::for_tests(dir.path())); |
| 3300 |
let pool = crate::db::open(&cfg.db_path).await.unwrap(); |
| 3301 |
let ctx = Arc::new(RecipeCtx::new( |
| 3302 |
AppId::new("demo"), |
| 3303 |
Version::parse("0.1.0").unwrap(), |
| 3304 |
"linux/x86_64".parse().unwrap(), |
| 3305 |
"fw13".into(), |
| 3306 |
"local".into(), |
| 3307 |
"v0.1.0".into(), |
| 3308 |
"/tmp".into(), |
| 3309 |
vec![], |
| 3310 |
Kind::Library, |
| 3311 |
1, |
| 3312 |
Arc::new(std::collections::HashMap::new()), |
| 3313 |
Arc::new(std::collections::HashMap::new()), |
| 3314 |
None, |
| 3315 |
pool, |
| 3316 |
crate::events::channel(), |
| 3317 |
cfg, |
| 3318 |
Arc::new(OtaRegistry::standard("https://makenot.work")), |
| 3319 |
tokio::runtime::Handle::current(), |
| 3320 |
Arc::new(AtomicBool::new(false)), |
| 3321 |
None, |
| 3322 |
)); |
| 3323 |
let engine = build_engine(&ctx); |
| 3324 |
for call in [ |
| 3325 |
"deploy_host()", |
| 3326 |
"service_name()", |
| 3327 |
"install_path()", |
| 3328 |
"health_url()", |
| 3329 |
r#"deploy("/tmp/x")"#, |
| 3330 |
] { |
| 3331 |
let err = engine.eval::<String>(call).unwrap_err().to_string(); |
| 3332 |
assert!( |
| 3333 |
err.contains("library") && err.contains("no deploy destination"), |
| 3334 |
"`{call}` must fail on the kind, got: {err}" |
| 3335 |
); |
| 3336 |
} |
| 3337 |
} |
| 3338 |
|
| 3339 |
|
| 3340 |
|
| 3341 |
|
| 3342 |
|
| 3343 |
|
| 3344 |
|
| 3345 |
|
| 3346 |
|
| 3347 |
|
| 3348 |
#[tokio::test] |
| 3349 |
async fn a_service_host_is_addressed_on_the_deploy_plane_in_any_step() { |
| 3350 |
let dir = tempfile::tempdir().unwrap(); |
| 3351 |
let cfg = Arc::new(Config::for_tests(dir.path())); |
| 3352 |
let pool = crate::db::open(&cfg.db_path).await.unwrap(); |
| 3353 |
sqlx::query( |
| 3354 |
"INSERT INTO builds (id, app, version, status, created_at) \ |
| 3355 |
VALUES (1, 'demo', '0.1.0', 'running', '2026-07-30T00:00:00Z')", |
| 3356 |
) |
| 3357 |
.execute(&pool) |
| 3358 |
.await |
| 3359 |
.unwrap(); |
| 3360 |
sqlx::query( |
| 3361 |
"INSERT INTO target_runs (id, build_id, app, version, target, status, started_at) \ |
| 3362 |
VALUES (1, 1, 'demo', '0.1.0', 'linux/x86_64', 'running', '2026-07-30T00:00:00Z')", |
| 3363 |
) |
| 3364 |
.execute(&pool) |
| 3365 |
.await |
| 3366 |
.unwrap(); |
| 3367 |
|
| 3368 |
let deploy = crate::topology::DeployTarget { |
| 3369 |
target: "linux/x86_64".parse().unwrap(), |
| 3370 |
host: "local".into(), |
| 3371 |
port: None, |
| 3372 |
install_path: "/usr/local/bin/demo".into(), |
| 3373 |
service: "demo.service".into(), |
| 3374 |
health_url: None, |
| 3375 |
}; |
| 3376 |
let mut execs: crate::state::ExecutorMap = std::collections::HashMap::new(); |
| 3377 |
execs.insert("local".into(), crate::state::build_deploy_executor(&deploy)); |
| 3378 |
|
| 3379 |
|
| 3380 |
assert!(!execs["local"].capabilities().permits(&Action::Build)); |
| 3381 |
assert!(execs["local"].capabilities().permits(&Action::Deploy)); |
| 3382 |
|
| 3383 |
let ctx = Arc::new(RecipeCtx::new( |
| 3384 |
AppId::new("demo"), |
| 3385 |
Version::parse("0.1.0").unwrap(), |
| 3386 |
"linux/x86_64".parse().unwrap(), |
| 3387 |
"fw13".into(), |
| 3388 |
"local".into(), |
| 3389 |
"v0.1.0".into(), |
| 3390 |
"/tmp".into(), |
| 3391 |
vec![], |
| 3392 |
Kind::Service, |
| 3393 |
1, |
| 3394 |
Arc::new(execs), |
| 3395 |
Arc::new(std::collections::HashMap::new()), |
| 3396 |
Some(deploy), |
| 3397 |
pool, |
| 3398 |
crate::events::channel(), |
| 3399 |
cfg, |
| 3400 |
Arc::new(OtaRegistry::standard("https://makenot.work")), |
| 3401 |
tokio::runtime::Handle::current(), |
| 3402 |
Arc::new(AtomicBool::new(false)), |
| 3403 |
None, |
| 3404 |
)); |
| 3405 |
|
| 3406 |
let ctx_blocking = ctx.clone(); |
| 3407 |
tokio::task::spawn_blocking(move || { |
| 3408 |
|
| 3409 |
|
| 3410 |
ctx_blocking.begin_step(Step::Verify).unwrap(); |
| 3411 |
assert_eq!( |
| 3412 |
action_for(Step::Verify, Kind::Service), |
| 3413 |
Action::Build, |
| 3414 |
"the step's own action is the one that would be denied", |
| 3415 |
); |
| 3416 |
let (code, out) = ctx_blocking |
| 3417 |
.run("local", "echo reached-the-service-host") |
| 3418 |
.expect("a service host must be reachable during a verify step"); |
| 3419 |
assert_eq!(code, 0, "{out}"); |
| 3420 |
assert!(out.contains("reached-the-service-host"), "{out}"); |
| 3421 |
}) |
| 3422 |
.await |
| 3423 |
.unwrap(); |
| 3424 |
} |
| 3425 |
|
| 3426 |
|
| 3427 |
|
| 3428 |
|
| 3429 |
|
| 3430 |
|
| 3431 |
#[tokio::test] |
| 3432 |
async fn a_failed_step_bars_the_deploy() { |
| 3433 |
let dir = tempfile::tempdir().unwrap(); |
| 3434 |
let cfg = Arc::new(Config::for_tests(dir.path())); |
| 3435 |
let pool = crate::db::open(&cfg.db_path).await.unwrap(); |
| 3436 |
let deploy = crate::topology::DeployTarget { |
| 3437 |
target: "linux/x86_64".parse().unwrap(), |
| 3438 |
host: "local".into(), |
| 3439 |
port: None, |
| 3440 |
install_path: "/usr/local/bin/demo".into(), |
| 3441 |
service: "demo.service".into(), |
| 3442 |
health_url: None, |
| 3443 |
}; |
| 3444 |
|
| 3445 |
|
| 3446 |
sqlx::query( |
| 3447 |
"INSERT INTO builds (id, app, version, status, created_at) \ |
| 3448 |
VALUES (1, 'demo', '0.1.0', 'running', '2026-07-30T00:00:00Z')", |
| 3449 |
) |
| 3450 |
.execute(&pool) |
| 3451 |
.await |
| 3452 |
.unwrap(); |
| 3453 |
sqlx::query( |
| 3454 |
"INSERT INTO target_runs (id, build_id, app, version, target, status, started_at) \ |
| 3455 |
VALUES (1, 1, 'demo', '0.1.0', 'linux/x86_64', 'running', '2026-07-30T00:00:00Z')", |
| 3456 |
) |
| 3457 |
.execute(&pool) |
| 3458 |
.await |
| 3459 |
.unwrap(); |
| 3460 |
|
| 3461 |
let mut execs: crate::state::ExecutorMap = std::collections::HashMap::new(); |
| 3462 |
execs.insert("local".into(), crate::state::build_deploy_executor(&deploy)); |
| 3463 |
let ctx = Arc::new(RecipeCtx::new( |
| 3464 |
AppId::new("demo"), |
| 3465 |
Version::parse("0.1.0").unwrap(), |
| 3466 |
"linux/x86_64".parse().unwrap(), |
| 3467 |
"fw13".into(), |
| 3468 |
"local".into(), |
| 3469 |
"v0.1.0".into(), |
| 3470 |
"/tmp".into(), |
| 3471 |
vec![], |
| 3472 |
Kind::Service, |
| 3473 |
1, |
| 3474 |
Arc::new(execs), |
| 3475 |
Arc::new(std::collections::HashMap::new()), |
| 3476 |
Some(deploy), |
| 3477 |
pool, |
| 3478 |
crate::events::channel(), |
| 3479 |
cfg, |
| 3480 |
Arc::new(OtaRegistry::standard("https://makenot.work")), |
| 3481 |
tokio::runtime::Handle::current(), |
| 3482 |
Arc::new(AtomicBool::new(false)), |
| 3483 |
None, |
| 3484 |
)); |
| 3485 |
|
| 3486 |
|
| 3487 |
|
| 3488 |
let ctx_blocking = ctx.clone(); |
| 3489 |
tokio::task::spawn_blocking(move || { |
| 3490 |
ctx_blocking.begin_step(Step::Prebuild).unwrap(); |
| 3491 |
ctx_blocking.fail_current_step(); |
| 3492 |
ctx_blocking.finish_step(Status::Ok).unwrap(); |
| 3493 |
|
| 3494 |
let err = ctx_blocking.deploy("/tmp/demo").unwrap_err().to_string(); |
| 3495 |
assert!( |
| 3496 |
err.contains("refusing to deploy") && err.contains("prebuild"), |
| 3497 |
"must refuse and name the failed step, got: {err}" |
| 3498 |
); |
| 3499 |
}) |
| 3500 |
.await |
| 3501 |
.unwrap(); |
| 3502 |
} |
| 3503 |
|
| 3504 |
#[test] |
| 3505 |
fn every_step_has_a_nonzero_default_budget() { |
| 3506 |
|
| 3507 |
|
| 3508 |
for step in Step::ALL { |
| 3509 |
assert!( |
| 3510 |
default_step_budget(step) >= std::time::Duration::from_mins(1), |
| 3511 |
"{step} budget must be a sane ceiling", |
| 3512 |
); |
| 3513 |
} |
| 3514 |
} |
| 3515 |
|
| 3516 |
#[test] |
| 3517 |
fn sha256_file_is_lowercase_hex_of_contents() { |
| 3518 |
let tmp = tempfile::tempdir().unwrap(); |
| 3519 |
let f = tmp.path().join("a.bin"); |
| 3520 |
std::fs::write(&f, b"abc").unwrap(); |
| 3521 |
|
| 3522 |
assert_eq!( |
| 3523 |
sha256_file(&f).unwrap(), |
| 3524 |
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" |
| 3525 |
); |
| 3526 |
} |
| 3527 |
|
| 3528 |
|
| 3529 |
|
| 3530 |
fn target(s: &str) -> Target { |
| 3531 |
s.parse().unwrap() |
| 3532 |
} |
| 3533 |
|
| 3534 |
#[test] |
| 3535 |
fn publish_gate_blocks_macos_without_verification() { |
| 3536 |
|
| 3537 |
let err = PublishAuthority::prove(target("macos/aarch64"), &[], None).unwrap_err(); |
| 3538 |
assert!(format!("{err:#}").contains("never verified"), "{err:#}"); |
| 3539 |
} |
| 3540 |
|
| 3541 |
#[test] |
| 3542 |
fn publish_gate_blocks_macos_when_gatekeeper_rejected() { |
| 3543 |
let err = PublishAuthority::prove(target("macos/aarch64"), &[], Some(false)).unwrap_err(); |
| 3544 |
assert!( |
| 3545 |
format!("{err:#}").contains("Gatekeeper rejected"), |
| 3546 |
"{err:#}" |
| 3547 |
); |
| 3548 |
} |
| 3549 |
|
| 3550 |
#[test] |
| 3551 |
fn publish_gate_allows_macos_when_gatekeeper_accepted() { |
| 3552 |
PublishAuthority::prove(target("macos/aarch64"), &[], Some(true)).unwrap(); |
| 3553 |
|
| 3554 |
PublishAuthority::prove(target("ios/universal"), &[], Some(true)).unwrap(); |
| 3555 |
assert!(PublishAuthority::prove(target("ios/universal"), &[], None).is_err()); |
| 3556 |
} |
| 3557 |
|
| 3558 |
#[test] |
| 3559 |
fn publish_gate_does_not_require_gatekeeper_for_non_apple_targets() { |
| 3560 |
|
| 3561 |
PublishAuthority::prove(target("linux/x86_64"), &[], None).unwrap(); |
| 3562 |
PublishAuthority::prove(target("windows/x86_64"), &[], None).unwrap(); |
| 3563 |
} |
| 3564 |
|
| 3565 |
#[test] |
| 3566 |
fn publish_gate_blocks_when_any_prior_step_failed() { |
| 3567 |
|
| 3568 |
let err = |
| 3569 |
PublishAuthority::prove(target("linux/x86_64"), &[Step::Build], None).unwrap_err(); |
| 3570 |
assert!( |
| 3571 |
format!("{err:#}").contains("prior step(s) failed"), |
| 3572 |
"{err:#}" |
| 3573 |
); |
| 3574 |
assert!( |
| 3575 |
format!("{err:#}").contains("build"), |
| 3576 |
"names the failed step: {err:#}" |
| 3577 |
); |
| 3578 |
|
| 3579 |
let err = PublishAuthority::prove(target("macos/aarch64"), &[Step::Sign], Some(true)) |
| 3580 |
.unwrap_err(); |
| 3581 |
assert!( |
| 3582 |
format!("{err:#}").contains("prior step(s) failed"), |
| 3583 |
"{err:#}" |
| 3584 |
); |
| 3585 |
} |
| 3586 |
|
| 3587 |
#[test] |
| 3588 |
fn notary_accepted_parses_status_field() { |
| 3589 |
assert!(notary_accepted( |
| 3590 |
r#"{"id":"abc","status":"Accepted","message":"ok"}"# |
| 3591 |
)); |
| 3592 |
|
| 3593 |
assert!(notary_accepted( |
| 3594 |
"sourcing env...\n{\n \"status\": \"Accepted\"\n}\nbye" |
| 3595 |
)); |
| 3596 |
|
| 3597 |
assert!(notary_accepted(r#"{ "status" : "Accepted" }"#)); |
| 3598 |
} |
| 3599 |
|
| 3600 |
#[test] |
| 3601 |
fn notary_accepted_rejects_non_accepted_and_garbage() { |
| 3602 |
assert!(!notary_accepted(r#"{"status":"Invalid"}"#)); |
| 3603 |
assert!(!notary_accepted(r#"{"status":"In Progress"}"#)); |
| 3604 |
assert!(!notary_accepted("no json here")); |
| 3605 |
assert!(!notary_accepted("")); |
| 3606 |
|
| 3607 |
assert!(!notary_accepted(r#""status":"Accepted"}"#)); |
| 3608 |
|
| 3609 |
assert!(!notary_accepted( |
| 3610 |
r#"{"status":"Invalid","message":"expected status:Accepted"}"# |
| 3611 |
)); |
| 3612 |
} |
| 3613 |
|
| 3614 |
|
| 3615 |
|
| 3616 |
#[test] |
| 3617 |
fn toplevel_and_prefix_read_both_shapes_of_repo() { |
| 3618 |
let (top, prefix) = |
| 3619 |
parse_toplevel_and_prefix("/home/max/Code/MNW\npom/\n").expect("two lines"); |
| 3620 |
assert_eq!(top, "/home/max/Code/MNW"); |
| 3621 |
assert_eq!(prefix, "pom/"); |
| 3622 |
|
| 3623 |
let (top, prefix) = |
| 3624 |
parse_toplevel_and_prefix("/home/max/Code/Libraries/pter\n\n").expect("two lines"); |
| 3625 |
assert_eq!(top, "/home/max/Code/Libraries/pter"); |
| 3626 |
assert_eq!(prefix, ""); |
| 3627 |
assert!( |
| 3628 |
parse_toplevel_and_prefix("").is_none(), |
| 3629 |
"no answer is not an answer" |
| 3630 |
); |
| 3631 |
} |
| 3632 |
|
| 3633 |
#[test] |
| 3634 |
fn repo_dir_name_is_the_last_segment_on_every_platform() { |
| 3635 |
assert_eq!(repo_dir_name("/home/max/Code/MNW"), "MNW"); |
| 3636 |
assert_eq!(repo_dir_name("/home/max/Code/MNW/"), "MNW"); |
| 3637 |
|
| 3638 |
assert_eq!(repo_dir_name("C:/Users/me/Code/Apps/goingson"), "goingson"); |
| 3639 |
} |
| 3640 |
|
| 3641 |
|
| 3642 |
#[test] |
| 3643 |
fn app_dir_in_worktree_follows_the_prefix() { |
| 3644 |
assert_eq!( |
| 3645 |
app_dir_in_worktree("/home/max/Code/.bento/MNW/pom", "pom/"), |
| 3646 |
"/home/max/Code/.bento/MNW/pom/pom" |
| 3647 |
); |
| 3648 |
assert_eq!( |
| 3649 |
app_dir_in_worktree("/home/max/Code/.bento/pter/pter", ""), |
| 3650 |
"/home/max/Code/.bento/pter/pter" |
| 3651 |
); |
| 3652 |
} |
| 3653 |
|
| 3654 |
|
| 3655 |
|
| 3656 |
#[test] |
| 3657 |
fn worktree_failure_reason_names_the_tag_or_repeats_git() { |
| 3658 |
let missing = worktree_failure_reason("pom-v0.4.5", false, "irrelevant"); |
| 3659 |
assert!(missing.contains("does not exist"), "{missing}"); |
| 3660 |
let held = worktree_failure_reason( |
| 3661 |
"pom-v0.4.5", |
| 3662 |
true, |
| 3663 |
"fatal: '/home/max/Code/.bento/MNW/pom' already exists", |
| 3664 |
); |
| 3665 |
assert!(held.contains("already exists"), "{held}"); |
| 3666 |
let silent = worktree_failure_reason("pom-v0.4.5", true, " "); |
| 3667 |
assert!(silent.contains("said nothing"), "{silent}"); |
| 3668 |
} |
| 3669 |
|
| 3670 |
|
| 3671 |
|
| 3672 |
|
| 3673 |
fn probe(repo: &std::path::Path) -> bool { |
| 3674 |
std::process::Command::new("sh") |
| 3675 |
.arg("-c") |
| 3676 |
.arg(tracked_lock_under_patch_cmd(&repo.display().to_string())) |
| 3677 |
.status() |
| 3678 |
.unwrap() |
| 3679 |
.success() |
| 3680 |
} |
| 3681 |
|
| 3682 |
|
| 3683 |
|
| 3684 |
|
| 3685 |
|
| 3686 |
|
| 3687 |
|
| 3688 |
#[test] |
| 3689 |
fn a_tracked_lock_is_only_a_problem_under_a_patch_block() { |
| 3690 |
let root = tempfile::tempdir().unwrap(); |
| 3691 |
let repo = root.path().join("crate"); |
| 3692 |
std::fs::create_dir_all(&repo).unwrap(); |
| 3693 |
let git = |args: &[&str]| { |
| 3694 |
std::process::Command::new("git") |
| 3695 |
.args(args) |
| 3696 |
.current_dir(&repo) |
| 3697 |
.env("GIT_AUTHOR_NAME", "t") |
| 3698 |
.env("GIT_AUTHOR_EMAIL", "t@t") |
| 3699 |
.env("GIT_COMMITTER_NAME", "t") |
| 3700 |
.env("GIT_COMMITTER_EMAIL", "t@t") |
| 3701 |
.output() |
| 3702 |
.unwrap() |
| 3703 |
}; |
| 3704 |
git(&["init", "-q", "."]); |
| 3705 |
std::fs::write(repo.join("Cargo.lock"), "# lock\n").unwrap(); |
| 3706 |
|
| 3707 |
|
| 3708 |
assert!(!probe(&repo)); |
| 3709 |
|
| 3710 |
|
| 3711 |
|
| 3712 |
git(&["add", "Cargo.lock"]); |
| 3713 |
git(&["commit", "-qm", "lock"]); |
| 3714 |
assert!(!probe(&repo)); |
| 3715 |
|
| 3716 |
|
| 3717 |
std::fs::create_dir_all(root.path().join(".cargo")).unwrap(); |
| 3718 |
std::fs::write( |
| 3719 |
root.path().join(".cargo/config.toml"), |
| 3720 |
"[patch.\"https://makenot.work/git/max/docengine.git\"]\ndocengine = { path = \"x\" }\n", |
| 3721 |
) |
| 3722 |
.unwrap(); |
| 3723 |
assert!(probe(&repo)); |
| 3724 |
|
| 3725 |
|
| 3726 |
git(&["rm", "-q", "--cached", "Cargo.lock"]); |
| 3727 |
assert!(!probe(&repo)); |
| 3728 |
} |
| 3729 |
|
| 3730 |
|
| 3731 |
|
| 3732 |
#[test] |
| 3733 |
fn the_tracked_lock_message_names_both_facts_and_refuses_both_wrong_fixes() { |
| 3734 |
let msg = tracked_lock_under_patch_problem("~/Code/.bento/pter/pter"); |
| 3735 |
assert!(msg.contains("Cargo.lock"), "{msg}"); |
| 3736 |
assert!(msg.contains("[patch]"), "{msg}"); |
| 3737 |
assert!(msg.contains("git rm --cached"), "{msg}"); |
| 3738 |
assert!(msg.contains("--allow-dirty"), "{msg}"); |
| 3739 |
assert!(msg.contains("~/Code/.bento/pter/pter"), "{msg}"); |
| 3740 |
} |
| 3741 |
} |
| 3742 |
|