Skip to content
1,150 linesCodeBlameRaw
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 containers;
13mod files;
14mod glob;
15mod matchers;
16mod paths;
17mod process;
18mod report;
19mod uses;
20mod zip;
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::path::{Path, PathBuf};
24use std::process::Command;
25use std::time::{Duration, Instant};
26
27use anyhow::{Context, Result};
28use g1t_actions::events::WORKSPACE;
29use g1t_actions::expr::{self, Scope, Status};
30use serde_json::{Map, Value, json};
31
32use files::StepFiles;
33use process::{Commands, Ended};
34use report::{Api, Log};
35
36const TEMP: &str = "/home/runner/_temp";
37
38/// Who is running steps: the job itself, or a composite action inside it.
39#[derive(Clone, Default)]
40pub(crate) struct Frame {
41 /// The `steps` context.
42 pub(crate) steps: Map<String, Value>,
43 /// A composite action's `inputs`, in place of the workflow's.
44 pub(crate) inputs: Option<Value>,
45 /// A composite action's folder, for `github.action_path`.
46 pub(crate) action_path: Option<String>,
47 /// Variables a composite action's caller set for its steps.
48 pub(crate) env: BTreeMap<String, String>,
49}
50
51/// A step run when the job's steps are done: an action's `post`, or
52/// saving the cache.
53pub(crate) struct Post {
54 pub(crate) name: String,
55 pub(crate) condition: String,
56 pub(crate) env: BTreeMap<String, String>,
57 pub(crate) run: PostRun,
58}
59
60pub(crate) enum PostRun {
61 Node { action_dir: PathBuf, script: String, using: String },
62 CacheSave { key: String, paths: Vec<String>, version: String },
63 /// A Docker action's `post-entrypoint`.
64 Docker(containers::DockerRun),
65}
66
67pub(crate) struct Job {
68 pub(crate) log: Log,
69 pub(crate) spec: Value,
70 pub(crate) workspace: PathBuf,
71 pub(crate) temp: PathBuf,
72 /// This process's own variables, less its credentials, and GitHub's.
73 base_env: BTreeMap<String, String>,
74 /// Written to `GITHUB_ENV` by earlier steps.
75 added_env: BTreeMap<String, String>,
76 /// Written to `GITHUB_PATH` by earlier steps, newest first.
77 path_prepend: Vec<String>,
78 workflow_env: BTreeMap<String, String>,
79 job_env: BTreeMap<String, String>,
80 /// github, vars, secrets, inputs, matrix, needs, strategy, runner.
81 pub(crate) contexts: Map<String, Value>,
82 pub(crate) failed: bool,
83 pub(crate) posts: Vec<Post>,
84 step_names: Vec<String>,
85 deadline: Instant,
86 /// The running step's `timeout-minutes`, as an instant: the nearest of
87 /// the step's own and those of the steps around it (a composite
88 /// action's step inside a `uses:` step). Every process a step starts
89 /// stops by it, as every one stops by the job's deadline.
90 step_deadline: Option<Instant>,
91 debug: bool,
92 /// What the last Node process left, for the step that ran it.
93 pub(crate) last_node_outputs: BTreeMap<String, String>,
94 pub(crate) last_node_state: BTreeMap<String, String>,
95 /// What each action's `pre` saved, by its step's `GITHUB_ACTION`, for
96 /// the step's main and post.
97 pub(crate) pre_state: BTreeMap<String, BTreeMap<String, String>>,
98 /// The names of the sandbox's own variables, which a container does
99 /// not get.
100 host_env: BTreeSet<String>,
101 /// Whether this job has a Docker Engine of its own (g1t's machines).
102 pub(crate) docker_hosted: bool,
103 /// The job's network, once its containers have one.
104 pub(crate) network: Option<String>,
105 /// `services:`, by their names, and their containers' names.
106 pub(crate) services: Vec<(String, String)>,
107 /// `container:`, once started.
108 pub(crate) container: Option<containers::JobContainer>,
109 /// The `job` context's `container` and `services`.
110 pub(crate) job_context: Map<String, Value>,
111 /// Docker actions' images built in this job.
112 pub(crate) built_actions: containers::Built,
113}
114
115fn text_map(value: Option<&Value>) -> BTreeMap<String, String> {
116 value
117 .and_then(Value::as_object)
118 .map(|map| map.iter().map(|(k, v)| (k.clone(), expr::to_text(v))).collect())
119 .unwrap_or_default()
120}
121
122/// Where `name_steps` puts a step's `GITHUB_ACTION`.
123const ACTION_NAME: &str = "__g1t_action";
124
125/// Gives each step its `GITHUB_ACTION`, as GitHub's runner names them: its
126/// `id`, else `__run` for a script and `__owner_repo` for an action
127/// (`__self` for one in the repository), the second of a name `_2`, the
128/// third `_3`.
129pub(crate) fn name_steps(steps: &mut [Map<String, Value>]) {
130 let mut taken: BTreeSet<String> = steps.iter().filter_map(|step| step.get("id").map(expr::to_text)).collect();
131 for step in steps.iter_mut() {
132 let name = match step.get("id").map(expr::to_text) {
133 Some(id) => id,
134 None => {
135 let base = match step.get("uses").map(expr::to_text) {
136 None => "run".to_owned(),
137 Some(uses) if uses.starts_with("./") => "self".to_owned(),
138 Some(uses) => {
139 let name = uses.split('@').next().unwrap_or_default();
140 let name = name.strip_prefix("docker://").unwrap_or(name);
141 let repository: Vec<&str> = name.splitn(3, '/').take(2).collect();
142 repository.join("_").chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect()
143 }
144 };
145 let base = format!("__{base}");
146 let mut name = base.clone();
147 let mut n = 2;
148 while taken.contains(&name) {
149 name = format!("{base}_{n}");
150 n += 1;
151 }
152 taken.insert(name.clone());
153 name
154 }
155 };
156 step.insert(ACTION_NAME.into(), Value::String(name));
157 }
158}
159
160/// A step's title when it has no name, as GitHub shows it.
161fn default_title(step: &Map<String, Value>) -> String {
162 if let Some(uses) = step.get("uses").and_then(Value::as_str) {
163 return format!("Run {uses}");
164 }
165 let run = step.get("run").map(expr::to_text).unwrap_or_default();
166 let first = run.lines().find(|line| !line.trim().is_empty()).unwrap_or_default().trim();
167 format!("Run {first}")
168}
169
170impl Job {
171 pub(crate) fn base_env_value(&self, name: &str) -> Option<String> {
172 self.base_env.get(name).cloned()
173 }
174
175 /// What earlier steps added to `PATH`, newest first.
176 pub(crate) fn path_prepend_entries(&self) -> &[String] {
177 &self.path_prepend
178 }
179
180 /// How the job is going, for `success()`, `failure()`, `cancelled()`
181 /// and `always()`: once the run is cancelled, only steps that ask for
182 /// `always()` or `cancelled()` run.
183 fn status(&self) -> Status {
184 if report::cancelled() {
185 Status::Cancelled
186 } else if self.failed {
187 Status::Failure
188 } else {
189 Status::Success
190 }
191 }
192
193 /// `job.status`.
194 fn status_word(&self) -> &'static str {
195 if report::cancelled() {
196 "cancelled"
197 } else if self.failed {
198 "failure"
199 } else {
200 "success"
201 }
202 }
203
204 /// The contexts an expression in a step can use.
205 pub(crate) fn contexts_for(&self, frame: &Frame, env: &BTreeMap<String, String>) -> Map<String, Value> {
206 let mut contexts = self.contexts.clone();
207 contexts.insert("env".into(), Value::Object(env.iter().map(|(k, v)| (k.clone(), Value::String(v.clone()))).collect()));
208 contexts.insert("steps".into(), Value::Object(frame.steps.clone()));
209 contexts.insert("job".into(), containers::job_context(self.status_word(), &self.job_context));
210 if let Some(inputs) = &frame.inputs {
211 contexts.insert("inputs".into(), inputs.clone());
212 }
213 if let Some(path) = &frame.action_path
214 && let Some(github) = contexts.get_mut("github")
215 {
216 github["action_path"] = Value::String(path.clone());
217 }
218 contexts
219 }
220
221 /// Runs `f` with a scope over these contexts.
222 pub(crate) fn with_scope<T>(&self, contexts: &Map<String, Value>, f: impl FnOnce(&Scope) -> T) -> T {
223 let workspace = self.workspace.clone();
224 let hash = move |patterns: &[String]| files::hash_files(&workspace, patterns);
225 let scope = Scope {
226 contexts,
227 status: self.status(),
228 hash_files: Some(&hash),
229 };
230 f(&scope)
231 }
232
233 /// The `env` context for a step: the workflow's, the job's, what earlier
234 /// steps wrote to `GITHUB_ENV`, and the frame's.
235 pub(crate) fn env_context(&self, frame: &Frame) -> BTreeMap<String, String> {
236 let mut env = self.added_env.clone();
237 env.extend(self.workflow_env.clone());
238 env.extend(self.job_env.clone());
239 env.extend(frame.env.clone());
240 env
241 }
242
243 /// What a process for a step is given.
244 pub(crate) fn process_env(&self, env: &BTreeMap<String, String>, files: &StepFiles) -> BTreeMap<String, String> {
245 let mut out = self.base_env.clone();
246 out.extend(env.clone());
247 for (name, value) in files.variables() {
248 out.insert(name.to_owned(), value);
249 }
250 if !self.path_prepend.is_empty() {
251 let current = out.get("PATH").cloned().unwrap_or_default();
252 let separator = paths::PATH_SEPARATOR;
253 out.insert("PATH".into(), format!("{}{separator}{current}", self.path_prepend.join(separator)));
254 }
255 out
256 }
257
258 /// Takes in what a step wrote to its files. Returns its outputs.
259 pub(crate) fn absorb(&mut self, files: &StepFiles, commands: &Commands) -> (BTreeMap<String, String>, BTreeMap<String, String>) {
260 let mut outputs: BTreeMap<String, String> = commands.outputs.clone();
261 match files::key_values(&StepFiles::read(&files.output)) {
262 Ok(values) => outputs.extend(values),
263 Err(problem) => self.log.line(&format!("##[error]$GITHUB_OUTPUT: {problem}")),
264 }
265 match files::key_values(&StepFiles::read(&files.env)) {
266 Ok(values) => {
267 for (name, value) in values {
268 if name.starts_with("GITHUB_") || name == "NODE_OPTIONS" {
269 self.log.line(&format!("##[warning]{name} cannot be set through $GITHUB_ENV."));
270 continue;
271 }
272 self.added_env.insert(name, value);
273 }
274 }
275 Err(problem) => self.log.line(&format!("##[error]$GITHUB_ENV: {problem}")),
276 }
277 for line in StepFiles::read(&files.path).lines().map(str::trim).filter(|l| !l.is_empty()) {
278 self.path_prepend.insert(0, line.to_owned());
279 }
280 let mut state = commands.state.clone();
281 if let Ok(values) = files::key_values(&StepFiles::read(&files.state)) {
282 state.extend(values);
283 }
284 // The step's job summary, for the run's page (report.rs).
285 self.log.summary(&StepFiles::read(&files.summary));
286 (outputs, state)
287 }
288
289 pub(crate) fn remaining_time(&self) -> Duration {
290 self.remaining()
291 }
292
293 /// What is left for the running step: its `timeout-minutes`, within
294 /// the job's.
295 fn remaining(&self) -> Duration {
296 let until = self.step_deadline.map_or(self.deadline, |step| step.min(self.deadline));
297 until.saturating_duration_since(Instant::now())
298 }
299
300 /// What is left of the job's own time, whatever the step's.
301 fn job_remaining(&self) -> Duration {
302 self.deadline.saturating_duration_since(Instant::now())
303 }
304
305 /// Runs a shell script for a `run` step.
306 pub(crate) fn run_script(
307 &mut self,
308 script: &str,
309 shell: Option<&str>,
310 working_directory: Option<&str>,
311 env: &BTreeMap<String, String>,
312 timeout: Duration,
313 ) -> (bool, BTreeMap<String, String>, BTreeMap<String, String>) {
314 crate::abuse::touch();
315 // Mining is never a workflow's job (abuse.rs).
316 if let Some(miner) = crate::abuse::miner_in(script) {
317 self.log.line(&format!("##[error]g1t does not run cryptocurrency miners ({miner}). This step was not run."));
318 return (false, BTreeMap::new(), BTreeMap::new());
319 }
320 let id = format!("{:x}", rand_id());
321 let shell = shell.map(str::trim).filter(|s| !s.is_empty());
322 let (program, args, extension): (String, Vec<String>, &str) = match shell {
323 // A self-hosted Windows runner, as GitHub's: PowerShell.
324 None if cfg!(windows) => (windows_powershell(), powershell_args(), "ps1"),
325 // A job container without bash, as GitHub's runner does.
326 None if self.container.as_ref().is_some_and(|c| c.shell == "sh") => ("sh".into(), vec!["-e".into(), "{0}".into()], "sh"),
327 None => ("bash".into(), vec!["-e".into(), "{0}".into()], "sh"),
328 Some("bash") => ("bash".into(), vec!["--noprofile".into(), "--norc".into(), "-eo".into(), "pipefail".into(), "{0}".into()], "sh"),
329 Some("sh") => ("sh".into(), vec!["-e".into(), "{0}".into()], "sh"),
330 Some("python") => (self.python_program(), vec!["{0}".into()], "py"),
331 Some("pwsh") if cfg!(windows) || program_exists("pwsh") => ("pwsh".into(), powershell_args(), "ps1"),
332 Some("powershell") if cfg!(windows) => ("powershell".into(), powershell_args(), "ps1"),
333 Some("cmd") if cfg!(windows) => (
334 "cmd".into(),
335 vec!["/D".into(), "/E:ON".into(), "/V:OFF".into(), "/S".into(), "/C".into(), "CALL \"{0}\"".into()],
336 "cmd",
337 ),
338 Some(other @ ("pwsh" | "powershell" | "cmd")) => {
339 self.log.line(&format!(
340 "##[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]`."
341 ));
342 return (false, BTreeMap::new(), BTreeMap::new());
343 }
344 Some(custom) => {
345 let mut parts = custom.split_whitespace().map(str::to_owned);
346 let program = parts.next().unwrap_or_default();
347 let mut args: Vec<String> = parts.collect();
348 if !args.iter().any(|a| a.contains("{0}")) {
349 args.push("{0}".into());
350 }
351 let extension = script_extension(&program);
352 (program, args, extension)
353 }
354 };
355 let script_path = self.temp.join(if extension.is_empty() { id.clone() } else { format!("{id}.{extension}") });
356 if let Err(error) = std::fs::write(&script_path, script_contents(&program, script)) {
357 self.log.line(&format!("##[error]Could not write the script: {error}"));
358 return (false, BTreeMap::new(), BTreeMap::new());
359 }
360 let files = match StepFiles::new(&self.temp, &id) {
361 Ok(files) => files,
362 Err(error) => {
363 self.log.line(&format!("##[error]Could not make the step's files: {error}"));
364 return (false, BTreeMap::new(), BTreeMap::new());
365 }
366 };
367 let args: Vec<String> = args.iter().map(|a| a.replace("{0}", &paths::shown(&script_path))).collect();
368 self.log.line(&format!("shell: {program} {}", args.join(" ")));
369 let dir = match working_directory {
370 Some(dir) if Path::new(dir).is_absolute() => PathBuf::from(dir),
371 Some(dir) => self.workspace.join(dir),
372 None => self.workspace.clone(),
373 };
374 let full = self.process_env(env, &files);
375 let in_container = self.container.as_ref().map(|c| c.path.clone()).and_then(|image_path| {
376 let inside = self.container_env(env, full.clone(), &image_path);
377 self.in_container(&program, &args, &dir, inside)
378 });
379 let command = match in_container {
380 Some(command) => command,
381 None => {
382 let mut command = Command::new(&program);
383 command.args(&args).current_dir(&dir).env_clear().envs(full);
384 command
385 }
386 };
387 let mut commands = Commands {
388 debug: self.debug,
389 ..Commands::default()
390 };
391 let ended = process::run(command, timeout.min(self.remaining()), &mut self.log, &mut commands);
392 let ok = match ended {
393 Ok(Ended::Exited(0)) => true,
394 Ok(Ended::Exited(code)) => {
395 self.log.line(&format!("##[error]Process completed with exit code {code}."));
396 false
397 }
398 Ok(Ended::TimedOut) => {
399 self.log.line("##[error]The step ran past its time limit and was stopped.");
400 false
401 }
402 Ok(Ended::Cancelled) => false,
403 Err(error) => {
404 self.log.line(&format!("##[error]{program} could not be started: {error}"));
405 false
406 }
407 };
408 let (outputs, state) = self.absorb(&files, &commands);
409 (ok, outputs, state)
410 }
411
412 /// Runs one step of a frame. Returns whether it succeeded (its
413 /// conclusion). `number` is the step the log belongs to.
414 pub(crate) fn step(&mut self, frame: &mut Frame, step: &Map<String, Value>, number: u32, report: bool, defaults: &Map<String, Value>) -> bool {
415 // A cancellation heard during an earlier step (which it stopped) or
416 // since: from here on, only cleanup steps run, and none is stopped
417 // for it again.
418 if report::cancelled() {
419 report::take_cancel();
420 }
421 let env_before = self.env_context(frame);
422 let contexts = self.contexts_for(frame, &env_before);
423 let title = match step.get("name").map(expr::to_text) {
424 Some(name) => self.with_scope(&contexts, |scope| expr::interpolate(&name, scope)).unwrap_or(name),
425 None => default_title(step),
426 };
427 let condition = step.get("if").map(expr::to_text).unwrap_or_default();
428 let read = self.with_scope(&contexts, |scope| expr::condition(&condition, scope));
429 // Debug logging: how the step's `if` read, as GitHub's runner says.
430 if self.debug {
431 let shown = if condition.trim().is_empty() { "success()" } else { condition.trim() };
432 self.log.line(&format!("##[debug]Evaluating condition for step: '{title}'"));
433 self.log.line(&format!("##[debug]Evaluating: {shown}"));
434 match &read {
435 Ok(result) => self.log.line(&format!("##[debug]Result: {result}")),
436 Err(problem) => self.log.line(&format!("##[debug]Failed: {problem}")),
437 }
438 }
439 let run_it = match read {
440 Ok(run_it) => run_it,
441 Err(problem) => {
442 self.log.line(&format!("##[error]The step's `if` does not read: {problem}"));
443 self.failed = true;
444 if report {
445 self.log.step_state(number, &title, "completed", Some("failure"));
446 }
447 return false;
448 }
449 };
450 let id = step.get("id").map(expr::to_text);
451 if !run_it {
452 if let Some(id) = &id {
453 frame.steps.insert(id.clone(), json!({ "outputs": {}, "outcome": "skipped", "conclusion": "skipped" }));
454 }
455 if report {
456 self.log.step_state(number, &title, "completed", Some("skipped"));
457 }
458 return true;
459 }
460 if report {
461 self.log.step(number);
462 self.log.step_state(number, &title, "in_progress", None);
463 }
464
465 // The step's own env, read with the contexts before it.
466 let env = self.step_env(step, &contexts, env_before.clone());
467 let action_name = step.get(ACTION_NAME).map(expr::to_text).or_else(|| id.clone()).unwrap_or_else(|| "__run".into());
468 let minutes = step
469 .get("timeout-minutes")
470 .and_then(|v| self.with_scope(&contexts, |scope| expr::interpolate_value(v, scope)).ok())
471 .and_then(|v| v.as_f64().or_else(|| expr::to_text(&v).parse().ok()));
472 let timeout = step_timeout(minutes);
473 // Every step stops at its own `timeout-minutes`, `run` or `uses`: a
474 // `uses:` step's action, and every process it starts, included.
475 let outer_deadline = self.step_deadline;
476 self.step_deadline = step_deadline(outer_deadline, Instant::now(), minutes);
477 let continue_on_error = step
478 .get("continue-on-error")
479 .and_then(|v| self.with_scope(&contexts, |scope| expr::interpolate_value(v, scope)).ok())
480 .is_some_and(|v| expr::truthy(&v));
481
482 let (ok, outputs) = if let Some(run) = step.get("run").map(expr::to_text) {
483 let script = match self.with_scope(&contexts, |scope| expr::interpolate(&run, scope)) {
484 Ok(script) => script,
485 Err(problem) => {
486 self.log.line(&format!("##[error]The script does not read: {problem}"));
487 String::new()
488 }
489 };
490 self.log.line(&format!("##[group]{title}"));
491 for line in script.lines() {
492 self.log.line(line);
493 }
494 self.log.line("##[endgroup]");
495 let shell = step
496 .get("shell")
497 .map(expr::to_text)
498 .or_else(|| defaults.get("shell").map(expr::to_text));
499 if frame.action_path.is_some() && shell.is_none() {
500 self.log.line("##[error]A composite action's `run` steps need a `shell`.");
501 (false, BTreeMap::new())
502 } else {
503 let working_directory = step
504 .get("working-directory")
505 .or_else(|| defaults.get("working-directory"))
506 .map(|v| self.with_scope(&contexts, |scope| expr::interpolate(&expr::to_text(v), scope)).unwrap_or_else(|_| expr::to_text(v)));
507 let mut env = env;
508 if let Some(path) = &frame.action_path {
509 env.insert("GITHUB_ACTION_PATH".into(), path.clone());
510 }
511 env.insert("GITHUB_ACTION".into(), action_name.clone());
512 let (ok, outputs, _) = self.run_script(&script, shell.as_deref(), working_directory.as_deref(), &env, timeout);
513 (ok, outputs)
514 }
515 } else if let Some(uses) = step.get("uses").map(expr::to_text) {
516 let with = self.step_with(step, &contexts);
517 self.uses(&uses, &with, &env, frame, &title, &action_name, timeout)
518 } else {
519 self.log.line("##[error]A step needs `run` or `uses`.");
520 (false, BTreeMap::new())
521 };
522 let own_deadline = self.step_deadline.filter(|_| self.step_deadline != outer_deadline);
523 self.step_deadline = outer_deadline;
524 let ok = if own_deadline.is_some_and(|until| Instant::now() >= until) {
525 self.log.line(&format!(
526 "##[error]The step ran past its timeout-minutes ({}) and was stopped.",
527 minutes.unwrap_or_default()
528 ));
529 false
530 } else {
531 ok
532 };
533
534 // A step the cancellation stopped ends cancelled, not failed.
535 let stopped = !ok && report::cancelled();
536 let outcome = if ok {
537 "success"
538 } else if stopped {
539 "cancelled"
540 } else {
541 "failure"
542 };
543 let conclusion = if ok || continue_on_error {
544 "success"
545 } else {
546 outcome
547 };
548 if !ok && continue_on_error && !stopped {
549 self.log.line("##[warning]The step failed, and `continue-on-error` lets the job go on.");
550 }
551 if let Some(id) = &id {
552 let outputs: Map<String, Value> = outputs.iter().map(|(k, v)| (k.clone(), Value::String(v.clone()))).collect();
553 frame.steps.insert(id.clone(), json!({ "outputs": outputs, "outcome": outcome, "conclusion": conclusion }));
554 }
555 if conclusion == "failure" {
556 self.failed = true;
557 }
558 if report {
559 self.log.step_state(number, &title, "completed", Some(conclusion));
560 }
561 conclusion == "success"
562 }
563
564 /// A step's own `env` over `base`, read with `contexts`.
565 fn step_env(&self, step: &Map<String, Value>, contexts: &Map<String, Value>, mut base: BTreeMap<String, String>) -> BTreeMap<String, String> {
566 if let Some(Value::Object(step_env)) = step.get("env") {
567 for (name, value) in step_env {
568 let value = self.with_scope(contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
569 base.insert(name.clone(), expr::to_text(&value));
570 }
571 }
572 base
573 }
574
575 /// A `uses:` step's `with`, read with `contexts`.
576 fn step_with(&self, step: &Map<String, Value>, contexts: &Map<String, Value>) -> BTreeMap<String, String> {
577 match step.get("with") {
578 Some(Value::Object(with)) => with
579 .iter()
580 .map(|(k, v)| {
581 let value = self.with_scope(contexts, |scope| expr::interpolate_value(v, scope)).unwrap_or(Value::Null);
582 (k.clone(), expr::to_text(&value))
583 })
584 .collect(),
585 _ => BTreeMap::new(),
586 }
587 }
588
589 fn report_steps(&self) {
590 self.log.steps(&self.step_names);
591 }
592}
593
594/// How long a step's processes may run: its `timeout-minutes`, or six
595/// hours (the job's own limit still applies).
596fn step_timeout(minutes: Option<f64>) -> Duration {
597 match minutes {
598 Some(minutes) if minutes.is_finite() && minutes > 0.0 => Duration::from_secs_f64(minutes * 60.0),
599 Some(_) => Duration::ZERO,
600 None => Duration::from_secs(6 * 3600),
601 }
602}
603
604/// When a step must end by: its `timeout-minutes` from `now`, or `outer`
605/// (the deadline of the `uses:` step it runs inside, for a composite
606/// action's step), whichever is nearer. None when neither sets one.
607fn step_deadline(outer: Option<Instant>, now: Instant, minutes: Option<f64>) -> Option<Instant> {
608 let own = minutes.map(|minutes| now + step_timeout(Some(minutes)));
609 match (outer, own) {
610 (Some(outer), Some(own)) => Some(outer.min(own)),
611 (outer, own) => outer.or(own),
612 }
613}
614
615/// PowerShell on Windows: `pwsh` (PowerShell 7) if it is installed, as on
616/// GitHub's Windows runners, else Windows PowerShell.
617fn windows_powershell() -> String {
618 if program_exists("pwsh") { "pwsh".into() } else { "powershell".into() }
619}
620
621/// How GitHub runs a PowerShell step: the script, stopping at the first error.
622fn powershell_args() -> Vec<String> {
623 vec!["-NoLogo".into(), "-NoProfile".into(), "-NonInteractive".into(), "-Command".into(), ". '{0}'".into()]
624}
625
626/// The name of a shell's program, without its folder or `.exe`.
627fn program_name(program: &str) -> &str {
628 let name = program.rsplit(['/', '\\']).next().unwrap_or(program);
629 name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name)
630}
631
632/// The extension GitHub's runner gives a script, by its shell's program:
633/// none for a program it does not know.
634fn script_extension(program: &str) -> &'static str {
635 match program_name(program) {
636 "bash" | "sh" => "sh",
637 "pwsh" | "powershell" => "ps1",
638 "cmd" => "cmd",
639 "python" => "py",
640 _ => "",
641 }
642}
643
644/// A script as GitHub's runner writes it: for PowerShell, stopping at the
645/// first error and exiting with the last program's exit code.
646fn script_contents(program: &str, script: &str) -> String {
647 let newline = if cfg!(windows) { "\r\n" } else { "\n" };
648 match program_name(program) {
649 "pwsh" | "powershell" => format!(
650 "$ErrorActionPreference = 'stop'{newline}{script}{newline}if ((Test-Path -LiteralPath variable:\\LASTEXITCODE)) {{ exit $LASTEXITCODE }}"
651 ),
652 _ => script.to_owned(),
653 }
654}
655
656/// Whether `program` is a file in one of `path`'s folders (or, on
657/// Windows, `program.exe`), without running it.
658fn on_path(program: &str, path: &str) -> bool {
659 let names = if cfg!(windows) { vec![program.to_owned(), format!("{program}.exe")] } else { vec![program.to_owned()] };
660 path.split(paths::PATH_SEPARATOR).filter(|dir| !dir.is_empty()).any(|dir| names.iter().any(|name| Path::new(dir).join(name).is_file()))
661}
662
663impl Job {
664 /// `shell: python`'s program: `python`, as on GitHub, where there is
665 /// one, else `python3` (Debian has no `python`).
666 fn python_program(&self) -> String {
667 if let Some(container) = &self.container {
668 return container.python.into();
669 }
670 let path = std::iter::once(self.base_env.get("PATH").cloned().unwrap_or_default());
671 let path: Vec<String> = self.path_prepend.iter().cloned().chain(path).collect();
672 if on_path("python", &path.join(paths::PATH_SEPARATOR)) { "python".into() } else { "python3".into() }
673 }
674}
675
676/// Whether `program` is on `PATH`.
677fn program_exists(program: &str) -> bool {
678 Command::new(program)
679 .arg(if program == "cmd" { "/C" } else { "-Version" })
680 .stdout(std::process::Stdio::null())
681 .stderr(std::process::Stdio::null())
682 .status()
683 .is_ok()
684}
685
686/// An id for files, unique enough within one job.
687fn rand_id() -> u64 {
688 use std::sync::atomic::{AtomicU64, Ordering};
689 static NEXT: AtomicU64 = AtomicU64::new(1);
690 let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0);
691 nanos ^ (NEXT.fetch_add(1, Ordering::Relaxed) << 48)
692}
693
694fn interpolated_map(job: &Job, value: Option<&Value>, contexts: &Map<String, Value>) -> BTreeMap<String, String> {
695 let mut out = BTreeMap::new();
696 if let Some(Value::Object(map)) = value {
697 for (name, value) in map {
698 let value = job.with_scope(contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
699 out.insert(name.clone(), expr::to_text(&value));
700 }
701 }
702 out
703}
704
705/// Whether `::debug::` lines are shown and steps' conditions explained:
706/// `ACTIONS_STEP_DEBUG` as a secret or a variable set to `true`, or a
707/// re-run with debug logging, which sets it and `RUNNER_DEBUG=1` among the
708/// job's variables.
709fn step_debug(contexts: &Map<String, Value>, variables: &Value) -> bool {
710 let named = |name: &str| {
711 contexts
712 .get("secrets")
713 .and_then(|s| s.get(name))
714 .or_else(|| contexts.get("vars").and_then(|v| v.get(name)))
715 .or_else(|| variables.get(name))
716 .is_some_and(|v| expr::to_text(v).eq_ignore_ascii_case("true"))
717 };
718 named("ACTIONS_STEP_DEBUG") || variables.get("RUNNER_DEBUG").is_some_and(|v| expr::to_text(v) == "1")
719}
720
721fn setup(mut spec: Value, api: Api) -> Result<Job> {
722 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();
723 let mut log = Log::new(api, masks);
724 // Variables GitHub sets that a g1t from before them does not send.
725 default_variables(&mut spec);
726 // On a self-hosted runner's own machine, GitHub's layout lives in a
727 // folder of the runner's (paths.rs).
728 for part in ["variables", "github"] {
729 paths::relocate(&mut spec[part]);
730 }
731 paths::relocate(&mut spec["contexts"]["runner"]);
732 let workspace = paths::under_home(WORKSPACE);
733 let temp = paths::under_home(TEMP);
734 log.matchers.workspace = workspace.clone();
735 std::fs::create_dir_all(&workspace).context("could not make the workspace")?;
736 std::fs::create_dir_all(&temp).context("could not make the temporary folder")?;
737 std::fs::write(temp.join("event.json"), serde_json::to_string_pretty(&spec["event"])?)?;
738
739 let host_env: BTreeSet<String> = std::env::vars().map(|(name, _)| name).collect();
740 // Docker of the job's own, on g1t's machines (crate::docker).
741 let docker_hosted = cfg!(target_os = "linux")
742 && std::env::var("G1T_DOCKER").as_deref() == Ok("on")
743 && spec["variables"]["RUNNER_ENVIRONMENT"].as_str() != Some("self-hosted");
744 // This process's environment, less what only it should see. `ImageOS`
745 // and `ImageVersion` come with it when the machine's image sets them,
746 // as GitHub's images do; nothing makes them up otherwise.
747 let mut base_env: BTreeMap<String, String> =
748 std::env::vars().filter(|(name, _)| !matches!(name.as_str(), "ACTIONS_TOKEN" | "ACTIONS_JOB" | "MODE") && !name.starts_with("G1T_")).collect();
749 base_env.insert("HOME".into(), std::env::var("HOME").unwrap_or_else(|_| "/home/node".into()));
750 base_env.extend(text_map(spec.get("variables")));
751 base_env.insert("GITHUB_EVENT_PATH".into(), paths::shown(&temp.join("event.json")));
752
753 let mut contexts: Map<String, Value> = spec["contexts"].as_object().cloned().unwrap_or_default();
754 contexts.insert("github".into(), spec["github"].clone());
755 let debug = step_debug(&contexts, &spec["variables"]);
756
757 // `timeoutMinutes` is how the API spelled it before its bodies were
758 // `snake_case`.
759 let timeout = spec["timeout_minutes"]
760 .as_u64()
761 .or_else(|| spec["timeoutMinutes"].as_u64())
762 .unwrap_or(60);
763 let mut job = Job {
764 log,
765 spec,
766 workspace,
767 temp,
768 base_env,
769 added_env: BTreeMap::new(),
770 path_prepend: Vec::new(),
771 workflow_env: BTreeMap::new(),
772 job_env: BTreeMap::new(),
773 contexts,
774 failed: false,
775 posts: Vec::new(),
776 step_names: Vec::new(),
777 deadline: Instant::now() + Duration::from_secs(timeout * 60),
778 step_deadline: None,
779 debug,
780 last_node_outputs: BTreeMap::new(),
781 last_node_state: BTreeMap::new(),
782 pre_state: BTreeMap::new(),
783 host_env,
784 docker_hosted,
785 network: None,
786 services: Vec::new(),
787 container: None,
788 job_context: Map::new(),
789 built_actions: containers::Built::new(),
790 };
791
792 // The workflow's env reads github, secrets, inputs and vars; the job's
793 // also its matrix, needs and strategy.
794 let mut contexts = job.contexts.clone();
795 contexts.insert("env".into(), json!({}));
796 job.workflow_env = interpolated_map(&job, job.spec["workflow"].get("env"), &contexts);
797 contexts.insert("env".into(), Value::Object(job.workflow_env.iter().map(|(k, v)| (k.clone(), json!(v))).collect()));
798 job.job_env = interpolated_map(&job, job.spec["spec"].get("env"), &contexts);
799 Ok(job)
800}
801
802/// `RUNNER_WORKSPACE` and `GITHUB_REPOSITORY_OWNER_ID` (with
803/// `github.repository_owner_id`), when the spec does not have them: the
804/// folder the workspace is in, and the owner's id from the event.
805fn default_variables(spec: &mut Value) {
806 if spec["variables"].is_object() && spec["variables"].get("RUNNER_WORKSPACE").is_none() {
807 spec["variables"]["RUNNER_WORKSPACE"] = json!(g1t_actions::events::RUNNER_WORKSPACE);
808 }
809 let owner_id = g1t_actions::events::owner_id(&spec["event"]);
810 if let Some(owner_id) = owner_id.filter(|id| !id.is_empty()) {
811 if spec["variables"].is_object() && spec["variables"].get("GITHUB_REPOSITORY_OWNER_ID").and_then(Value::as_str).is_none_or(str::is_empty) {
812 spec["variables"]["GITHUB_REPOSITORY_OWNER_ID"] = json!(owner_id);
813 }
814 if spec["github"].is_object() && spec["github"].get("repository_owner_id").and_then(Value::as_str).is_none_or(str::is_empty) {
815 spec["github"]["repository_owner_id"] = json!(owner_id);
816 }
817 }
818}
819
820/// The job's `defaults.run`, its own over the workflow's.
821fn run_defaults(spec: &Value) -> Map<String, Value> {
822 let mut defaults = spec["workflow"]["defaults"]["run"].as_object().cloned().unwrap_or_default();
823 if let Some(own) = spec["spec"]["defaults"]["run"].as_object() {
824 defaults.extend(own.clone());
825 }
826 defaults
827}
828
829fn run_job(job: &mut Job) {
830 let mut steps: Vec<Map<String, Value>> = job.spec["spec"]["steps"]
831 .as_array()
832 .map(|steps| steps.iter().filter_map(|s| s.as_object().cloned()).collect())
833 .unwrap_or_default();
834 name_steps(&mut steps);
835 let defaults = run_defaults(&job.spec);
836
837 // Step names as they read before anything has run.
838 let frame = Frame::default();
839 let env = job.env_context(&frame);
840 let contexts = job.contexts_for(&frame, &env);
841 job.step_names = steps
842 .iter()
843 .map(|step| match step.get("name").map(expr::to_text) {
844 Some(name) => job.with_scope(&contexts, |scope| expr::interpolate(&name, scope)).unwrap_or(name),
845 None => default_title(step),
846 })
847 .collect();
848 job.report_steps();
849
850 job.log.step(0);
851 job.log.line(&format!("Job: {}", job.spec["name"].as_str().unwrap_or_default()));
852 let variables = &job.spec["variables"];
853 if variables["RUNNER_ENVIRONMENT"] == "self-hosted" {
854 let text = |name: &str| variables[name].as_str().unwrap_or_default().to_owned();
855 job.log.line(&format!("Runner: {}, self-hosted, {} {}", text("RUNNER_NAME"), text("RUNNER_OS"), text("RUNNER_ARCH")));
856 } else {
857 job.log.line("Runner: g1t, Linux X64 (Debian bookworm, Node 24, Python 3, Go, Rust)");
858 }
859 if let Some(Value::Object(matrix)) = job.contexts.get("matrix")
860 && !matrix.is_empty()
861 {
862 job.log.line(&format!("Matrix: {}", serde_json::to_string(matrix).unwrap_or_default()));
863 }
864 // What its G1T_TOKEN may do, as its `permissions:` gave it.
865 if let Some(Value::Object(permissions)) = job.spec.get("permissions").cloned() {
866 job.log.line("##[group]G1T_TOKEN permissions");
867 for (name, access) in &permissions {
868 if access.as_str() != Some("none") {
869 job.log.line(&format!("{name}: {}", access.as_str().unwrap_or_default()));
870 }
871 }
872 job.log.line("##[endgroup]");
873 }
874 if job.docker_hosted {
875 let registry = job.contexts["github"]["server_url"].as_str().and_then(crate::docker::engine::registry_host);
876 let token = job.contexts.get("secrets").and_then(|s| s.get("G1T_TOKEN")).map(expr::to_text).filter(|t| !t.is_empty());
877 let options = crate::docker::engine::Options { registry: registry.zip(token) };
878 if let Err(problem) = crate::docker::engine::enable(options) {
879 job.log.line(&format!("##[warning]Docker is not available in this job: {problem}"));
880 job.docker_hosted = false;
881 }
882 }
883 // A self-hosted runner's word on how this job was run (selfhosted/exec.rs).
884 if let Ok(notice) = std::env::var("G1T_JOB_NOTICE") {
885 job.log.line(&format!("##[warning]{notice}"));
886 }
887 // Actions first, then containers, as GitHub's "Set up job" and
888 // "Initialize containers". Each action's `pre` (read from the actions
889 // just downloaded) is a step of its own, "Pre <step>", before the
890 // job's first step.
891 let prepared = job.prepare_actions(&steps);
892 let pres = if prepared { job.pre_steps(&steps) } else { Vec::new() };
893 if !pres.is_empty() {
894 let mut names: Vec<String> = pres.iter().map(|(index, _)| format!("Pre {}", job.step_names[*index])).collect();
895 names.extend(job.step_names.iter().cloned());
896 job.step_names = names;
897 job.report_steps();
898 }
899 let containers_started = prepared && job.start_containers();
900 job.log.flush();
901
902 let mut frame = Frame::default();
903 if !containers_started {
904 job.failed = true;
905 for (index, name) in job.step_names.clone().iter().enumerate() {
906 job.log.step_state(index as u32 + 1, name, "completed", Some("skipped"));
907 }
908 }
909 for (index, (_, pre)) in pres.iter().enumerate().filter(|_| containers_started) {
910 let number = index as u32 + 1;
911 let name = job.step_names[index].clone();
912 if report::cancelled() {
913 report::take_cancel();
914 }
915 if !job.pre_runs(pre) {
916 job.log.step_state(number, &name, "completed", Some("skipped"));
917 continue;
918 }
919 job.log.step(number);
920 job.log.step_state(number, &name, "in_progress", None);
921 let ok = job.run_pre(pre);
922 if !ok {
923 job.failed = true;
924 }
925 let conclusion = if ok {
926 "success"
927 } else if report::cancelled() {
928 "cancelled"
929 } else {
930 "failure"
931 };
932 job.log.step_state(number, &name, "completed", Some(conclusion));
933 }
934 let offset = pres.len() as u32;
935 for (index, step) in steps.iter().enumerate().filter(|_| containers_started) {
936 job.step(&mut frame, step, offset + index as u32 + 1, true, &defaults);
937 job.log_docker_notes();
938 if job.job_remaining().is_zero() {
939 job.log.line("##[error]The job ran past its time limit.");
940 job.failed = true;
941 break;
942 }
943 }
944
945 // Post steps, last registered first.
946 let posts: Vec<Post> = std::mem::take(&mut job.posts);
947 for post in posts.into_iter().rev() {
948 let number = job.step_names.len() as u32 + 1;
949 job.step_names.push(post.name.clone());
950 job.report_steps();
951 let contexts = job.contexts_for(&frame, &job.env_context(&frame));
952 let run_it = job.with_scope(&contexts, |scope| expr::condition(&post.condition, scope)).unwrap_or(true);
953 if !run_it {
954 job.log.step_state(number, &post.name, "completed", Some("skipped"));
955 continue;
956 }
957 job.log.step(number);
958 job.log.step_state(number, &post.name, "in_progress", None);
959 let ok = match &post.run {
960 PostRun::Node { action_dir, script, using } => job.run_node(action_dir, script, &post.env, using),
961 PostRun::CacheSave { key, paths, version } => job.cache_save(key, paths, version),
962 PostRun::Docker(run) => job.run_docker(run).0,
963 };
964 job.log.step_state(number, &post.name, "completed", Some(if ok { "success" } else { "failure" }));
965 if !ok {
966 job.failed = true;
967 }
968 }
969
970 // GitHub's "Stop containers": services' logs, and everything removed.
971 if job.has_containers() {
972 let number = job.step_names.len() as u32 + 1;
973 job.step_names.push("Stop containers".into());
974 job.report_steps();
975 job.log.step(number);
976 job.log.step_state(number, "Stop containers", "in_progress", None);
977 job.stop_containers();
978 job.log.step_state(number, "Stop containers", "completed", Some("success"));
979 }
980
981 // The job's outputs, read now that every step has run.
982 let env = job.env_context(&frame);
983 let contexts = job.contexts_for(&frame, &env);
984 let mut outputs = Map::new();
985 if let Some(Value::Object(declared)) = job.spec["spec"].get("outputs") {
986 for (name, value) in declared {
987 let value = job.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
988 outputs.insert(name.clone(), Value::String(expr::to_text(&value)));
989 }
990 }
991 // Cancelled, the job ends so however its cleanup went (and g1t holds
992 // to that whatever it is told).
993 let conclusion = if report::cancelled() {
994 "cancelled"
995 } else if job.failed {
996 "failure"
997 } else {
998 "success"
999 };
1000 job.log.done(conclusion, &outputs, None);
1001}
1002
1003pub(crate) fn main() -> i32 {
1004 let api = match (crate::env("G1T_API"), crate::env("ACTIONS_JOB"), crate::env("ACTIONS_TOKEN")) {
1005 (Ok(base), Ok(job), Ok(token)) => Api { base, job, token },
1006 _ => {
1007 eprintln!("g1t-runner: G1T_API, ACTIONS_JOB and ACTIONS_TOKEN are needed");
1008 return 2;
1009 }
1010 };
1011 let spec = match api.spec() {
1012 Ok(spec) => spec,
1013 Err(error) => {
1014 eprintln!("g1t-runner: could not fetch the job: {error:#}");
1015 api.report(json!({ "kind": "done", "conclusion": "failure", "reason": format!("The runner could not fetch the job: {error}") }));
1016 return 1;
1017 }
1018 };
1019 let reporter = Api {
1020 base: api.base.clone(),
1021 job: api.job.clone(),
1022 token: api.token.clone(),
1023 };
1024 let mut job = match setup(spec, reporter) {
1025 Ok(job) => job,
1026 Err(error) => {
1027 api.report(json!({ "kind": "done", "conclusion": "failure", "reason": format!("The runner could not set up: {error:#}") }));
1028 return 1;
1029 }
1030 };
1031 run_job(&mut job);
1032 if job.failed || report::cancelled() { 1 } else { 0 }
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037 use serde_json::{Map, Value, json};
1038
1039 use super::*;
1040
1041 #[test]
1042 fn debug_logging_comes_from_a_secret_a_variable_or_a_debug_rerun() {
1043 let contexts = |value: Value| -> Map<String, Value> { serde_json::from_value(value).unwrap() };
1044 let none = json!({});
1045 assert!(!step_debug(&contexts(json!({ "secrets": {}, "vars": {} })), &none));
1046 assert!(step_debug(&contexts(json!({ "secrets": { "ACTIONS_STEP_DEBUG": "true" } })), &none));
1047 assert!(step_debug(&contexts(json!({ "vars": { "ACTIONS_STEP_DEBUG": "TRUE" } })), &none));
1048 assert!(!step_debug(&contexts(json!({ "vars": { "ACTIONS_STEP_DEBUG": "false" } })), &none));
1049 // A re-run with debug logging sets these among the job's variables.
1050 assert!(step_debug(&contexts(json!({})), &json!({ "RUNNER_DEBUG": "1" })));
1051 assert!(step_debug(&contexts(json!({})), &json!({ "ACTIONS_STEP_DEBUG": "true" })));
1052 assert!(!step_debug(&contexts(json!({})), &json!({ "RUNNER_DEBUG": "0" })));
1053 }
1054
1055 #[test]
1056 fn scripts_get_githubs_extension_for_their_shell() {
1057 assert_eq!(script_extension("bash"), "sh");
1058 assert_eq!(script_extension("/usr/bin/sh"), "sh");
1059 assert_eq!(script_extension("pwsh"), "ps1");
1060 assert_eq!(script_extension("C:\\Windows\\powershell.exe"), "ps1");
1061 assert_eq!(script_extension("cmd"), "cmd");
1062 assert_eq!(script_extension("python"), "py");
1063 // A program GitHub does not know: no extension.
1064 assert_eq!(script_extension("perl"), "");
1065 assert_eq!(script_extension("python3"), "");
1066 }
1067
1068 #[test]
1069 fn powershell_scripts_stop_at_errors_and_keep_the_exit_code() {
1070 let newline = if cfg!(windows) { "\r\n" } else { "\n" };
1071 assert_eq!(
1072 script_contents("pwsh", "Write-Output hi"),
1073 format!("$ErrorActionPreference = 'stop'{newline}Write-Output hi{newline}if ((Test-Path -LiteralPath variable:\\LASTEXITCODE)) {{ exit $LASTEXITCODE }}")
1074 );
1075 assert!(script_contents("powershell.exe", "x").starts_with("$ErrorActionPreference = 'stop'"));
1076 assert_eq!(script_contents("bash", "echo hi"), "echo hi");
1077 }
1078
1079 #[test]
1080 fn programs_are_found_on_path_without_running_them() {
1081 let dir = std::env::temp_dir().join(format!("g1t-on-path-{}", std::process::id()));
1082 std::fs::create_dir_all(&dir).unwrap();
1083 std::fs::write(dir.join("python"), "").unwrap();
1084 let path = format!("/nowhere{}{}", paths::PATH_SEPARATOR, dir.display());
1085 assert!(on_path("python", &path));
1086 assert!(!on_path("python9", &path));
1087 assert!(!on_path("python", ""));
1088 let _ = std::fs::remove_dir_all(&dir);
1089 }
1090
1091 #[test]
1092 fn steps_are_named_for_github_action_as_github_names_them() {
1093 let mut steps: Vec<Map<String, Value>> = serde_json::from_value(json!([
1094 { "run": "a" },
1095 { "run": "b" },
1096 { "id": "build", "run": "c" },
1097 { "uses": "actions/setup-node@v4" },
1098 { "uses": "actions/cache/restore@v4" },
1099 { "uses": "actions/setup-node@v4" },
1100 { "uses": "./.github/actions/x" },
1101 { "run": "d" },
1102 { "id": "__run_4", "run": "e" },
1103 { "run": "f" },
1104 ]))
1105 .unwrap();
1106 name_steps(&mut steps);
1107 let names: Vec<String> = steps.iter().map(|s| expr::to_text(&s[ACTION_NAME])).collect();
1108 assert_eq!(
1109 names,
1110 ["__run", "__run_2", "build", "__actions_setup-node", "__actions_cache", "__actions_setup-node_2", "__self", "__run_3", "__run_4", "__run_5"]
1111 );
1112 }
1113
1114 #[test]
1115 fn variables_a_spec_lacks_are_filled_in() {
1116 let mut spec = json!({
1117 "variables": { "CI": "true" },
1118 "github": { "repository_owner_id": "" },
1119 "event": { "repository": { "owner": { "id": 7 } } },
1120 });
1121 default_variables(&mut spec);
1122 assert_eq!(spec["variables"]["RUNNER_WORKSPACE"], "/home/runner/work");
1123 assert_eq!(spec["variables"]["GITHUB_REPOSITORY_OWNER_ID"], "7");
1124 assert_eq!(spec["github"]["repository_owner_id"], "7");
1125 // What g1t sent stands.
1126 let mut spec = json!({ "variables": { "RUNNER_WORKSPACE": "/w", "GITHUB_REPOSITORY_OWNER_ID": "9" }, "github": {}, "event": {} });
1127 default_variables(&mut spec);
1128 assert_eq!(spec["variables"]["RUNNER_WORKSPACE"], "/w");
1129 assert_eq!(spec["variables"]["GITHUB_REPOSITORY_OWNER_ID"], "9");
1130 }
1131
1132 #[test]
1133 fn a_steps_timeout_is_its_own_or_the_nearer_one_around_it() {
1134 let now = Instant::now();
1135 // No timeout-minutes anywhere: only the job's deadline applies.
1136 assert_eq!(step_deadline(None, now, None), None);
1137 // A step's own, in minutes, fractions included.
1138 assert_eq!(step_deadline(None, now, Some(1.5)), Some(now + Duration::from_secs(90)));
1139 // A composite action's step inside a `uses:` step with its own:
1140 // the nearer of the two.
1141 let outer = now + Duration::from_secs(60);
1142 assert_eq!(step_deadline(Some(outer), now, Some(10.0)), Some(outer));
1143 assert_eq!(step_deadline(Some(outer), now, Some(0.5)), Some(now + Duration::from_secs(30)));
1144 assert_eq!(step_deadline(Some(outer), now, None), Some(outer));
1145 // Zero or less is a time already up.
1146 assert_eq!(step_deadline(None, now, Some(0.0)), Some(now));
1147 assert_eq!(step_timeout(None), Duration::from_secs(6 * 3600));
1148 assert_eq!(step_timeout(Some(-1.0)), Duration::ZERO);
1149 }
1150}