use crate::frozen::FrozenPlan;
use crate::plan;
use crate::wire::{wire_version, Digested};
use anyhow::{anyhow, bail, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
pub const SCRIPT: &str = "{script}";
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct WeightHint {
pub exclusive: bool,
pub services: usize,
pub timeout_minutes: Option<f64>,
pub tests: Option<usize>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DemandNode {
pub step_id: String,
pub job: String,
pub step: usize,
pub label: String,
pub cwd: String,
pub argv: Vec<String>,
pub key: Option<String>,
pub weight: WeightHint,
pub depends_on: Vec<String>,
pub conditional: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TaskDemand {
#[serde(default = "wire_version")]
pub schema_version: u32,
pub task_id: String,
pub nodes: Vec<DemandNode>,
}
impl Digested for TaskDemand {
fn schema_version(&self) -> u32 {
self.schema_version
}
}
pub(crate) fn history_key(workflows_dir: &str, workflow: &str, job: &str, label: &str) -> String {
format!(
"local-ci {} {job} {label}",
crate::report::short(workflows_dir, workflow)
)
}
fn shell_argv(shell: Option<&str>) -> Result<Vec<String>> {
let words = |w: &[&str]| w.iter().map(|s| s.to_string()).collect();
Ok(match shell.map(str::trim) {
None | Some("bash") => words(&["bash", "--noprofile", "--norc", "-eo", "pipefail", SCRIPT]),
Some("sh") => words(&["sh", "-e", SCRIPT]),
Some("python") => words(&["python3", SCRIPT]),
Some(custom) if custom.contains("{0}") => shlex::split(&custom.replace("{0}", SCRIPT))
.ok_or_else(|| anyhow!("bad shell `{custom}`"))?,
Some(other) => bail!("unsupported shell `{other}`"),
})
}
pub(crate) fn workspace_dir(what: &str, dir: &str) -> Result<String> {
crate::artifact::normalize_rel(dir)
.map_err(|e| anyhow!("{what} {dir:?} is not a directory below the workspace: {e}"))
}
pub fn plan_task_demand(fp: &FrozenPlan, task_id: &str) -> Result<TaskDemand> {
let task = fp
.task(task_id)
.ok_or_else(|| anyhow!("the plan has no task `{task_id}`"))?;
let plan = fp.to_plan();
let wi = plan
.selected
.iter()
.position(|s| s.wf.file == task.workflow)
.ok_or_else(|| anyhow!("the plan has no workflow {}", task.workflow))?;
let w = &plan.selected[wi].wf;
let recipe = crate::setup::derive_in(&plan, &plan::hoist(&plan), task)?;
let prepared: BTreeSet<(&str, usize)> = recipe
.steps
.iter()
.flat_map(|s| &s.at)
.filter(|a| a.workflow == task.workflow)
.map(|a| (a.job.as_str(), a.index))
.collect();
if let Some(ts) = &task.shard {
workspace_dir("the shard's working directory", &ts.dir)?;
}
let mut nodes: Vec<DemandNode> = vec![];
let mut shard_step = false;
for id in &task.jobs {
let job = w
.jobs
.iter()
.find(|j| &j.id == id)
.ok_or_else(|| anyhow!("the task has job `{id}`, which its workflow has not"))?;
let exclusive = plan::is_exclusive(job);
for (n, s) in job.steps.iter().enumerate() {
let Some(run) = s.run.as_ref().filter(|_| s.uses.is_none()) else {
continue;
};
let shard = task.shard.as_ref().filter(|t| t.step == n);
shard_step |= shard.is_some();
if crate::script::remote_effect(run) {
continue;
}
let label = s.label();
if let Some(ts) = shard {
if plan::step_dir(w, job, s) != ts.dir {
bail!(
"task {}: the working directory of step {n} is not {:?}, where its tests were listed",
task.id,
ts.dir
);
}
crate::exec::shard_script(ts, std::path::Path::new(""))
.map_err(|e| anyhow!("task {}: {e}", task.id))?;
}
let argv = shell_argv(plan::resolved_shell(w, job, s).as_deref())?;
let cwd = workspace_dir("the working directory", &plan::step_dir(w, job, s))?;
let dynamic_label = label.contains("${{");
let step_id = format!("{id}#{n}");
nodes.push(DemandNode {
depends_on: nodes
.last()
.map(|p| p.step_id.clone())
.into_iter()
.collect(),
step_id,
job: id.clone(),
step: n,
cwd,
argv,
key: (!dynamic_label)
.then(|| history_key(&fp.config.default_workflows_dir, &w.file, id, &label)),
label,
weight: WeightHint {
exclusive,
services: job.services.len(),
timeout_minutes: s.timeout_minutes,
tests: shard.map(|t| t.tests.len()),
},
conditional: s.cond.is_some()
|| job.cond.is_some()
|| task.dynamic_matrix
|| prepared.contains(&(id.as_str(), n))
|| crate::script::global_install(run, &|_| false)
== crate::script::Install::Needed,
});
}
}
if let Some(ts) = &task.shard {
if !shard_step {
bail!(
"task {} is a shard of a split job, but step {} of its job runs no command",
task.id,
ts.step
);
}
}
Ok(TaskDemand {
schema_version: wire_version(),
task_id: task.id.clone(),
nodes,
})
}