flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/crates/runner/src/actions/mod.rs

658 lines28,482 bytesCodeBlame
1//! Runs one GitHub Actions job, as GitHub's runner would: its steps in
2//! order, each `run` in a shell and each `uses` as the action it names,
3//! with the `${{ }}` contexts, the `GITHUB_*` variables and files, and the
4//! workflow commands steps print. It reports every step and the log to
5//! g1t as it goes.
6//!
7//! Configuration comes from the environment: `G1T_API`, and `ACTIONS_JOB`
8//! and `ACTIONS_TOKEN`, the job and its own token. Everything else, the
9//! job's definition, its contexts and its secrets, is fetched with them.
10
11mod blobs;
12mod files;
13mod paths;
14mod process;
15mod report;
16mod uses;
17
18use std::collections::BTreeMap;
19use std::path::{Path, PathBuf};
20use std::process::Command;
21use std::time::{Duration, Instant};
22
23use anyhow::{Context, Result};
24use g1t_actions::events::WORKSPACE;
25use g1t_actions::expr::{self, Scope, Status};
26use serde_json::{Map, Value, json};
27
28use files::StepFiles;
29use process::{Commands, Ended};
30use report::{Api, Log};
31
32const TEMP: &str = "/home/runner/_temp";
33
34/// Who is running steps: the job itself, or a composite action inside it.
35#[derive(Clone, Default)]
36pub(crate) struct Frame {
37 /// The `steps` context.
38 pub(crate) steps: Map<String, Value>,
39 /// A composite action's `inputs`, in place of the workflow's.
40 pub(crate) inputs: Option<Value>,
41 /// A composite action's folder, for `github.action_path`.
42 pub(crate) action_path: Option<String>,
43 /// Variables a composite action's caller set for its steps.
44 pub(crate) env: BTreeMap<String, String>,
45}
46
47/// A step run when the job's steps are done: an action's `post`, or
48/// saving the cache.
49pub(crate) struct Post {
50 pub(crate) name: String,
51 pub(crate) condition: String,
52 pub(crate) env: BTreeMap<String, String>,
53 pub(crate) run: PostRun,
54}
55
56pub(crate) enum PostRun {
57 Node { action_dir: PathBuf, script: String },
58 CacheSave { key: String, paths: Vec<String> },
59}
60
61pub(crate) struct Job {
62 pub(crate) log: Log,
63 pub(crate) spec: Value,
64 pub(crate) workspace: PathBuf,
65 pub(crate) temp: PathBuf,
66 /// This process's own variables, less its credentials, and GitHub's.
67 base_env: BTreeMap<String, String>,
68 /// Written to `GITHUB_ENV` by earlier steps.
69 added_env: BTreeMap<String, String>,
70 /// Written to `GITHUB_PATH` by earlier steps, newest first.
71 path_prepend: Vec<String>,
72 workflow_env: BTreeMap<String, String>,
73 job_env: BTreeMap<String, String>,
74 /// github, vars, secrets, inputs, matrix, needs, strategy, runner.
75 pub(crate) contexts: Map<String, Value>,
76 pub(crate) failed: bool,
77 pub(crate) posts: Vec<Post>,
78 step_names: Vec<String>,
79 deadline: Instant,
80 debug: bool,
81 /// What the last Node process left, for the step that ran it.
82 pub(crate) last_node_outputs: BTreeMap<String, String>,
83 pub(crate) last_node_state: BTreeMap<String, String>,
84}
85
86fn text_map(value: Option<&Value>) -> BTreeMap<String, String> {
87 value
88 .and_then(Value::as_object)
89 .map(|map| map.iter().map(|(k, v)| (k.clone(), expr::to_text(v))).collect())
90 .unwrap_or_default()
91}
92
93/// A step's title when it has no name, as GitHub shows it.
94fn default_title(step: &Map<String, Value>) -> String {
95 if let Some(uses) = step.get("uses").and_then(Value::as_str) {
96 return format!("Run {uses}");
97 }
98 let run = step.get("run").map(expr::to_text).unwrap_or_default();
99 let first = run.lines().find(|line| !line.trim().is_empty()).unwrap_or_default().trim();
100 format!("Run {first}")
101}
102
103impl Job {
104 pub(crate) fn base_env_value(&self, name: &str) -> Option<String> {
105 self.base_env.get(name).cloned()
106 }
107
108 fn status(&self) -> Status {
109 if self.failed { Status::Failure } else { Status::Success }
110 }
111
112 /// The contexts an expression in a step can use.
113 pub(crate) fn contexts_for(&self, frame: &Frame, env: &BTreeMap<String, String>) -> Map<String, Value> {
114 let mut contexts = self.contexts.clone();
115 contexts.insert("env".into(), Value::Object(env.iter().map(|(k, v)| (k.clone(), Value::String(v.clone()))).collect()));
116 contexts.insert("steps".into(), Value::Object(frame.steps.clone()));
117 contexts.insert("job".into(), json!({ "status": if self.failed { "failure" } else { "success" } }));
118 if let Some(inputs) = &frame.inputs {
119 contexts.insert("inputs".into(), inputs.clone());
120 }
121 if let Some(path) = &frame.action_path
122 && let Some(github) = contexts.get_mut("github")
123 {
124 github["action_path"] = Value::String(path.clone());
125 }
126 contexts
127 }
128
129 /// Runs `f` with a scope over these contexts.
130 pub(crate) fn with_scope<T>(&self, contexts: &Map<String, Value>, f: impl FnOnce(&Scope) -> T) -> T {
131 let workspace = self.workspace.clone();
132 let hash = move |patterns: &[String]| files::hash_files(&workspace, patterns);
133 let scope = Scope {
134 contexts,
135 status: self.status(),
136 hash_files: Some(&hash),
137 };
138 f(&scope)
139 }
140
141 /// The `env` context for a step: the workflow's, the job's, what earlier
142 /// steps wrote to `GITHUB_ENV`, and the frame's.
143 fn env_context(&self, frame: &Frame) -> BTreeMap<String, String> {
144 let mut env = self.added_env.clone();
145 env.extend(self.workflow_env.clone());
146 env.extend(self.job_env.clone());
147 env.extend(frame.env.clone());
148 env
149 }
150
151 /// What a process for a step is given.
152 pub(crate) fn process_env(&self, env: &BTreeMap<String, String>, files: &StepFiles) -> BTreeMap<String, String> {
153 let mut out = self.base_env.clone();
154 out.extend(env.clone());
155 for (name, value) in files.variables() {
156 out.insert(name.to_owned(), value);
157 }
158 if !self.path_prepend.is_empty() {
159 let current = out.get("PATH").cloned().unwrap_or_default();
160 let separator = paths::PATH_SEPARATOR;
161 out.insert("PATH".into(), format!("{}{separator}{current}", self.path_prepend.join(separator)));
162 }
163 out
164 }
165
166 /// Takes in what a step wrote to its files. Returns its outputs.
167 pub(crate) fn absorb(&mut self, files: &StepFiles, commands: &Commands) -> (BTreeMap<String, String>, BTreeMap<String, String>) {
168 let mut outputs: BTreeMap<String, String> = commands.outputs.clone();
169 match files::key_values(&StepFiles::read(&files.output)) {
170 Ok(values) => outputs.extend(values),
171 Err(problem) => self.log.line(&format!("##[error]$GITHUB_OUTPUT: {problem}")),
172 }
173 match files::key_values(&StepFiles::read(&files.env)) {
174 Ok(values) => {
175 for (name, value) in values {
176 if name.starts_with("GITHUB_") || name == "NODE_OPTIONS" {
177 self.log.line(&format!("##[warning]{name} cannot be set through $GITHUB_ENV."));
178 continue;
179 }
180 self.added_env.insert(name, value);
181 }
182 }
183 Err(problem) => self.log.line(&format!("##[error]$GITHUB_ENV: {problem}")),
184 }
185 for line in StepFiles::read(&files.path).lines().map(str::trim).filter(|l| !l.is_empty()) {
186 self.path_prepend.insert(0, line.to_owned());
187 }
188 let mut state = commands.state.clone();
189 if let Ok(values) = files::key_values(&StepFiles::read(&files.state)) {
190 state.extend(values);
191 }
192 let summary = StepFiles::read(&files.summary);
193 if !summary.trim().is_empty() {
194 self.log.line("##[group]Step summary");
195 for line in summary.lines() {
196 self.log.line(line);
197 }
198 self.log.line("##[endgroup]");
199 }
200 (outputs, state)
201 }
202
203 pub(crate) fn remaining_time(&self) -> Duration {
204 self.remaining()
205 }
206
207 fn remaining(&self) -> Duration {
208 self.deadline.saturating_duration_since(Instant::now())
209 }
210
211 /// Runs a shell script for a `run` step.
212 pub(crate) fn run_script(
213 &mut self,
214 script: &str,
215 shell: Option<&str>,
216 working_directory: Option<&str>,
217 env: &BTreeMap<String, String>,
218 timeout: Duration,
219 ) -> (bool, BTreeMap<String, String>, BTreeMap<String, String>) {
220 crate::abuse::touch();
221 // Mining is never a workflow's job (abuse.rs).
222 if let Some(miner) = crate::abuse::miner_in(script) {
223 self.log.line(&format!("##[error]g1t does not run cryptocurrency miners ({miner}). This step was not run."));
224 return (false, BTreeMap::new(), BTreeMap::new());
225 }
226 let id = format!("{:x}", rand_id());
227 let shell = shell.map(str::trim).filter(|s| !s.is_empty());
228 let (program, args, extension): (String, Vec<String>, &str) = match shell {
229 // A self-hosted Windows runner, as GitHub's: PowerShell.
230 None if cfg!(windows) => (windows_powershell(), powershell_args(), "ps1"),
231 None => ("bash".into(), vec!["-e".into(), "{0}".into()], "sh"),
232 Some("bash") => ("bash".into(), vec!["--noprofile".into(), "--norc".into(), "-eo".into(), "pipefail".into(), "{0}".into()], "sh"),
233 Some("sh") => ("sh".into(), vec!["-e".into(), "{0}".into()], "sh"),
234 Some("python") => ("python3".into(), vec!["{0}".into()], "py"),
235 Some("pwsh") if cfg!(windows) || program_exists("pwsh") => ("pwsh".into(), powershell_args(), "ps1"),
236 Some("powershell") if cfg!(windows) => ("powershell".into(), powershell_args(), "ps1"),
237 Some("cmd") if cfg!(windows) => (
238 "cmd".into(),
239 vec!["/D".into(), "/E:ON".into(), "/V:OFF".into(), "/S".into(), "/C".into(), "CALL \"{0}\"".into()],
240 "cmd",
241 ),
242 Some(other @ ("pwsh" | "powershell" | "cmd")) => {
243 self.log.line(&format!(
244 "##[error]`shell: {other}` needs Windows or PowerShell, which g1t's Linux runners do not have. A self-hosted Windows runner can run it: `runs-on: [self-hosted, windows]`."
245 ));
246 return (false, BTreeMap::new(), BTreeMap::new());
247 }
248 Some(custom) => {
249 let mut parts = custom.split_whitespace().map(str::to_owned);
250 let program = parts.next().unwrap_or_default();
251 let mut args: Vec<String> = parts.collect();
252 if !args.iter().any(|a| a.contains("{0}")) {
253 args.push("{0}".into());
254 }
255 (program, args, "sh")
256 }
257 };
258 let script_path = self.temp.join(format!("{id}.{extension}"));
259 if let Err(error) = std::fs::write(&script_path, script) {
260 self.log.line(&format!("##[error]Could not write the script: {error}"));
261 return (false, BTreeMap::new(), BTreeMap::new());
262 }
263 let files = match StepFiles::new(&self.temp, &id) {
264 Ok(files) => files,
265 Err(error) => {
266 self.log.line(&format!("##[error]Could not make the step's files: {error}"));
267 return (false, BTreeMap::new(), BTreeMap::new());
268 }
269 };
270 let args: Vec<String> = args.iter().map(|a| a.replace("{0}", &paths::shown(&script_path))).collect();
271 self.log.line(&format!("shell: {program} {}", args.join(" ")));
272 let dir = match working_directory {
273 Some(dir) if Path::new(dir).is_absolute() => PathBuf::from(dir),
274 Some(dir) => self.workspace.join(dir),
275 None => self.workspace.clone(),
276 };
277 let mut command = Command::new(&program);
278 command.args(&args).current_dir(&dir).env_clear().envs(self.process_env(env, &files));
279 let mut commands = Commands {
280 debug: self.debug,
281 ..Commands::default()
282 };
283 let ended = process::run(command, timeout.min(self.remaining()), &mut self.log, &mut commands);
284 let ok = match ended {
285 Ok(Ended::Exited(0)) => true,
286 Ok(Ended::Exited(code)) => {
287 self.log.line(&format!("##[error]Process completed with exit code {code}."));
288 false
289 }
290 Ok(Ended::TimedOut) => {
291 self.log.line("##[error]The step ran past its time limit and was stopped.");
292 false
293 }
294 Err(error) => {
295 self.log.line(&format!("##[error]{program} could not be started: {error}"));
296 false
297 }
298 };
299 let (outputs, state) = self.absorb(&files, &commands);
300 (ok, outputs, state)
301 }
302
303 /// Runs one step of a frame. Returns whether it succeeded (its
304 /// conclusion). `number` is the step the log belongs to.
305 pub(crate) fn step(&mut self, frame: &mut Frame, step: &Map<String, Value>, number: u32, report: bool, defaults: &Map<String, Value>) -> bool {
306 let env_before = self.env_context(frame);
307 let contexts = self.contexts_for(frame, &env_before);
308 let title = match step.get("name").map(expr::to_text) {
309 Some(name) => self.with_scope(&contexts, |scope| expr::interpolate(&name, scope)).unwrap_or(name),
310 None => default_title(step),
311 };
312 let condition = step.get("if").map(expr::to_text).unwrap_or_default();
313 let run_it = match self.with_scope(&contexts, |scope| expr::condition(&condition, scope)) {
314 Ok(run_it) => run_it,
315 Err(problem) => {
316 self.log.line(&format!("##[error]The step's `if` does not read: {problem}"));
317 self.failed = true;
318 if report {
319 self.log.step_state(number, &title, "completed", Some("failure"));
320 }
321 return false;
322 }
323 };
324 let id = step.get("id").map(expr::to_text);
325 if !run_it {
326 if let Some(id) = &id {
327 frame.steps.insert(id.clone(), json!({ "outputs": {}, "outcome": "skipped", "conclusion": "skipped" }));
328 }
329 if report {
330 self.log.step_state(number, &title, "completed", Some("skipped"));
331 }
332 return true;
333 }
334 if report {
335 self.log.step(number);
336 self.log.step_state(number, &title, "in_progress", None);
337 }
338
339 // The step's own env, read with the contexts before it.
340 let mut env = env_before.clone();
341 if let Some(Value::Object(step_env)) = step.get("env") {
342 for (name, value) in step_env {
343 let value = self.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
344 env.insert(name.clone(), expr::to_text(&value));
345 }
346 }
347 let timeout = step
348 .get("timeout-minutes")
349 .and_then(|v| self.with_scope(&contexts, |scope| expr::interpolate_value(v, scope)).ok())
350 .and_then(|v| v.as_f64().or_else(|| expr::to_text(&v).parse().ok()))
351 .map_or(Duration::from_secs(6 * 3600), |minutes| Duration::from_secs_f64(minutes * 60.0));
352 let continue_on_error = step
353 .get("continue-on-error")
354 .and_then(|v| self.with_scope(&contexts, |scope| expr::interpolate_value(v, scope)).ok())
355 .is_some_and(|v| expr::truthy(&v));
356
357 let (ok, outputs) = if let Some(run) = step.get("run").map(expr::to_text) {
358 let script = match self.with_scope(&contexts, |scope| expr::interpolate(&run, scope)) {
359 Ok(script) => script,
360 Err(problem) => {
361 self.log.line(&format!("##[error]The script does not read: {problem}"));
362 String::new()
363 }
364 };
365 self.log.line(&format!("##[group]{title}"));
366 for line in script.lines() {
367 self.log.line(line);
368 }
369 self.log.line("##[endgroup]");
370 let shell = step
371 .get("shell")
372 .map(expr::to_text)
373 .or_else(|| defaults.get("shell").map(expr::to_text));
374 if frame.action_path.is_some() && shell.is_none() {
375 self.log.line("##[error]A composite action's `run` steps need a `shell`.");
376 (false, BTreeMap::new())
377 } else {
378 let working_directory = step
379 .get("working-directory")
380 .or_else(|| defaults.get("working-directory"))
381 .map(|v| self.with_scope(&contexts, |scope| expr::interpolate(&expr::to_text(v), scope)).unwrap_or_else(|_| expr::to_text(v)));
382 let mut env = env;
383 if let Some(path) = &frame.action_path {
384 env.insert("GITHUB_ACTION_PATH".into(), path.clone());
385 }
386 let (ok, outputs, _) = self.run_script(&script, shell.as_deref(), working_directory.as_deref(), &env, timeout);
387 (ok, outputs)
388 }
389 } else if let Some(uses) = step.get("uses").map(expr::to_text) {
390 let with: BTreeMap<String, String> = match step.get("with") {
391 Some(Value::Object(with)) => with
392 .iter()
393 .map(|(k, v)| {
394 let value = self.with_scope(&contexts, |scope| expr::interpolate_value(v, scope)).unwrap_or(Value::Null);
395 (k.clone(), expr::to_text(&value))
396 })
397 .collect(),
398 _ => BTreeMap::new(),
399 };
400 self.uses(&uses, &with, &env, frame, &title, id.as_deref(), timeout)
401 } else {
402 self.log.line("##[error]A step needs `run` or `uses`.");
403 (false, BTreeMap::new())
404 };
405
406 let outcome = if ok { "success" } else { "failure" };
407 let conclusion = if ok || continue_on_error { "success" } else { "failure" };
408 if !ok && continue_on_error {
409 self.log.line("##[warning]The step failed, and `continue-on-error` lets the job go on.");
410 }
411 if let Some(id) = &id {
412 let outputs: Map<String, Value> = outputs.iter().map(|(k, v)| (k.clone(), Value::String(v.clone()))).collect();
413 frame.steps.insert(id.clone(), json!({ "outputs": outputs, "outcome": outcome, "conclusion": conclusion }));
414 }
415 if conclusion == "failure" {
416 self.failed = true;
417 }
418 if report {
419 self.log.step_state(number, &title, "completed", Some(conclusion));
420 }
421 conclusion == "success"
422 }
423
424 fn report_steps(&self) {
425 self.log.steps(&self.step_names);
426 }
427}
428
429/// PowerShell on Windows: `pwsh` (PowerShell 7) if it is installed, as on
430/// GitHub's Windows runners, else Windows PowerShell.
431fn windows_powershell() -> String {
432 if program_exists("pwsh") { "pwsh".into() } else { "powershell".into() }
433}
434
435/// How GitHub runs a PowerShell step: the script, stopping at the first error.
436fn powershell_args() -> Vec<String> {
437 vec!["-NoLogo".into(), "-NoProfile".into(), "-NonInteractive".into(), "-Command".into(), ". '{0}'".into()]
438}
439
440/// Whether `program` is on `PATH`.
441fn program_exists(program: &str) -> bool {
442 Command::new(program)
443 .arg(if program == "cmd" { "/C" } else { "-Version" })
444 .stdout(std::process::Stdio::null())
445 .stderr(std::process::Stdio::null())
446 .status()
447 .is_ok()
448}
449
450/// An id for files, unique enough within one job.
451fn rand_id() -> u64 {
452 use std::sync::atomic::{AtomicU64, Ordering};
453 static NEXT: AtomicU64 = AtomicU64::new(1);
454 let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0);
455 nanos ^ (NEXT.fetch_add(1, Ordering::Relaxed) << 48)
456}
457
458fn interpolated_map(job: &Job, value: Option<&Value>, contexts: &Map<String, Value>) -> BTreeMap<String, String> {
459 let mut out = BTreeMap::new();
460 if let Some(Value::Object(map)) = value {
461 for (name, value) in map {
462 let value = job.with_scope(contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
463 out.insert(name.clone(), expr::to_text(&value));
464 }
465 }
466 out
467}
468
469fn setup(mut spec: Value, api: Api) -> Result<Job> {
470 let masks: Vec<String> = spec["masks"].as_array().map(|m| m.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect()).unwrap_or_default();
471 let log = Log::new(api, masks);
472 // On a self-hosted runner's own machine, GitHub's layout lives in a
473 // folder of the runner's (paths.rs).
474 for part in ["variables", "github"] {
475 paths::relocate(&mut spec[part]);
476 }
477 paths::relocate(&mut spec["contexts"]["runner"]);
478 let workspace = paths::under_home(WORKSPACE);
479 let temp = paths::under_home(TEMP);
480 std::fs::create_dir_all(&workspace).context("could not make the workspace")?;
481 std::fs::create_dir_all(&temp).context("could not make the temporary folder")?;
482 std::fs::write(temp.join("event.json"), serde_json::to_string_pretty(&spec["event"])?)?;
483
484 // This process's environment, less what only it should see.
485 let mut base_env: BTreeMap<String, String> =
486 std::env::vars().filter(|(name, _)| !matches!(name.as_str(), "ACTIONS_TOKEN" | "ACTIONS_JOB" | "MODE") && !name.starts_with("G1T_")).collect();
487 base_env.insert("HOME".into(), std::env::var("HOME").unwrap_or_else(|_| "/home/node".into()));
488 base_env.extend(text_map(spec.get("variables")));
489 base_env.insert("GITHUB_EVENT_PATH".into(), paths::shown(&temp.join("event.json")));
490
491 let mut contexts: Map<String, Value> = spec["contexts"].as_object().cloned().unwrap_or_default();
492 contexts.insert("github".into(), spec["github"].clone());
493 let debug = contexts
494 .get("secrets")
495 .and_then(|s| s.get("ACTIONS_STEP_DEBUG"))
496 .or_else(|| contexts.get("vars").and_then(|v| v.get("ACTIONS_STEP_DEBUG")))
497 .is_some_and(|v| expr::to_text(v) == "true");
498
499 // `timeoutMinutes` is how the API spelled it before its bodies were
500 // `snake_case`.
501 let timeout = spec["timeout_minutes"]
502 .as_u64()
503 .or_else(|| spec["timeoutMinutes"].as_u64())
504 .unwrap_or(60);
505 let mut job = Job {
506 log,
507 spec,
508 workspace,
509 temp,
510 base_env,
511 added_env: BTreeMap::new(),
512 path_prepend: Vec::new(),
513 workflow_env: BTreeMap::new(),
514 job_env: BTreeMap::new(),
515 contexts,
516 failed: false,
517 posts: Vec::new(),
518 step_names: Vec::new(),
519 deadline: Instant::now() + Duration::from_secs(timeout * 60),
520 debug,
521 last_node_outputs: BTreeMap::new(),
522 last_node_state: BTreeMap::new(),
523 };
524
525 // The workflow's env reads github, secrets, inputs and vars; the job's
526 // also its matrix, needs and strategy.
527 let mut contexts = job.contexts.clone();
528 contexts.insert("env".into(), json!({}));
529 job.workflow_env = interpolated_map(&job, job.spec["workflow"].get("env"), &contexts);
530 contexts.insert("env".into(), Value::Object(job.workflow_env.iter().map(|(k, v)| (k.clone(), json!(v))).collect()));
531 job.job_env = interpolated_map(&job, job.spec["spec"].get("env"), &contexts);
532 Ok(job)
533}
534
535/// The job's `defaults.run`, its own over the workflow's.
536fn run_defaults(spec: &Value) -> Map<String, Value> {
537 let mut defaults = spec["workflow"]["defaults"]["run"].as_object().cloned().unwrap_or_default();
538 if let Some(own) = spec["spec"]["defaults"]["run"].as_object() {
539 defaults.extend(own.clone());
540 }
541 defaults
542}
543
544fn run_job(job: &mut Job) {
545 let steps: Vec<Map<String, Value>> = job.spec["spec"]["steps"]
546 .as_array()
547 .map(|steps| steps.iter().filter_map(|s| s.as_object().cloned()).collect())
548 .unwrap_or_default();
549 let defaults = run_defaults(&job.spec);
550
551 // Step names as they read before anything has run.
552 let frame = Frame::default();
553 let env = job.env_context(&frame);
554 let contexts = job.contexts_for(&frame, &env);
555 job.step_names = steps
556 .iter()
557 .map(|step| match step.get("name").map(expr::to_text) {
558 Some(name) => job.with_scope(&contexts, |scope| expr::interpolate(&name, scope)).unwrap_or(name),
559 None => default_title(step),
560 })
561 .collect();
562 job.report_steps();
563
564 job.log.step(0);
565 job.log.line(&format!("Job: {}", job.spec["name"].as_str().unwrap_or_default()));
566 let variables = &job.spec["variables"];
567 if variables["RUNNER_ENVIRONMENT"] == "self-hosted" {
568 let text = |name: &str| variables[name].as_str().unwrap_or_default().to_owned();
569 job.log.line(&format!("Runner: {}, self-hosted, {} {}", text("RUNNER_NAME"), text("RUNNER_OS"), text("RUNNER_ARCH")));
570 } else {
571 job.log.line("Runner: g1t, Linux X64 (Debian bookworm, Node 24, Python 3, Go, Rust)");
572 }
573 if let Some(Value::Object(matrix)) = job.contexts.get("matrix")
574 && !matrix.is_empty()
575 {
576 job.log.line(&format!("Matrix: {}", serde_json::to_string(matrix).unwrap_or_default()));
577 }
578 job.log.flush();
579
580 let mut frame = Frame::default();
581 for (index, step) in steps.iter().enumerate() {
582 job.step(&mut frame, step, index as u32 + 1, true, &defaults);
583 if job.remaining().is_zero() {
584 job.log.line("##[error]The job ran past its time limit.");
585 job.failed = true;
586 break;
587 }
588 }
589
590 // Post steps, last registered first.
591 let posts: Vec<Post> = std::mem::take(&mut job.posts);
592 for post in posts.into_iter().rev() {
593 let number = job.step_names.len() as u32 + 1;
594 job.step_names.push(post.name.clone());
595 job.report_steps();
596 let contexts = job.contexts_for(&frame, &job.env_context(&frame));
597 let run_it = job.with_scope(&contexts, |scope| expr::condition(&post.condition, scope)).unwrap_or(true);
598 if !run_it {
599 job.log.step_state(number, &post.name, "completed", Some("skipped"));
600 continue;
601 }
602 job.log.step(number);
603 job.log.step_state(number, &post.name, "in_progress", None);
604 let ok = match &post.run {
605 PostRun::Node { action_dir, script } => job.run_node(action_dir, script, &post.env),
606 PostRun::CacheSave { key, paths } => job.cache_save(key, paths),
607 };
608 job.log.step_state(number, &post.name, "completed", Some(if ok { "success" } else { "failure" }));
609 if !ok {
610 job.failed = true;
611 }
612 }
613
614 // The job's outputs, read now that every step has run.
615 let env = job.env_context(&frame);
616 let contexts = job.contexts_for(&frame, &env);
617 let mut outputs = Map::new();
618 if let Some(Value::Object(declared)) = job.spec["spec"].get("outputs") {
619 for (name, value) in declared {
620 let value = job.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
621 outputs.insert(name.clone(), Value::String(expr::to_text(&value)));
622 }
623 }
624 let conclusion = if job.failed { "failure" } else { "success" };
625 job.log.done(conclusion, &outputs, None);
626}
627
628pub(crate) fn main() -> i32 {
629 let api = match (crate::env("G1T_API"), crate::env("ACTIONS_JOB"), crate::env("ACTIONS_TOKEN")) {
630 (Ok(base), Ok(job), Ok(token)) => Api { base, job, token },
631 _ => {
632 eprintln!("g1t-runner: G1T_API, ACTIONS_JOB and ACTIONS_TOKEN are needed");
633 return 2;
634 }
635 };
636 let spec = match api.spec() {
637 Ok(spec) => spec,
638 Err(error) => {
639 eprintln!("g1t-runner: could not fetch the job: {error:#}");
640 api.report(json!({ "kind": "done", "conclusion": "failure", "reason": format!("The runner could not fetch the job: {error}") }));
641 return 1;
642 }
643 };
644 let reporter = Api {
645 base: api.base.clone(),
646 job: api.job.clone(),
647 token: api.token.clone(),
648 };
649 let mut job = match setup(spec, reporter) {
650 Ok(job) => job,
651 Err(error) => {
652 api.report(json!({ "kind": "done", "conclusion": "failure", "reason": format!("The runner could not set up: {error:#}") }));
653 return 1;
654 }
655 };
656 run_job(&mut job);
657 if job.failed { 1 } else { 0 }
658}