Skip to content
904 linesCodeBlameRaw
1//! `uses:` steps: `actions/checkout` done natively against g1t, actions
2//! fetched from another repository on g1t (or else GitHub, at the commit
3//! g1t resolved its ref to, from the archive g1t keeps of it when it has
4//! one) and run as they are (JavaScript, composite and Docker),
5//! `docker://` images, and a few of GitHub's own whose services g1t does
6//! not have yet. Every action a job's steps name is downloaded before the
7//! first step runs, as GitHub's runner does.
8
9use std::collections::BTreeMap;
10use std::path::{Path, PathBuf};
11use std::process::Command;
12use std::time::Duration;
13
14use base64::Engine;
15use base64::engine::general_purpose::STANDARD;
16use g1t_actions::expr;
17use g1t_actions::workflow::yaml_to_json;
18use serde_json::{Map, Value, json};
19
20use super::containers::{self, DockerRun};
21use super::files::StepFiles;
22use super::process::{self, Commands, Ended};
23use super::{Frame, Job, Post, PostRun};
24
25const ACTIONS_DIR: &str = "/home/runner/_actions";
26
27/// Where an action comes from.
28enum Source {
29 Local(PathBuf),
30 /// Another repository: on g1t when g1t has it and this one may use
31 /// it, otherwise on GitHub.
32 GitHub { owner: String, repo: String, path: String, git_ref: String },
33}
34
35fn safe(part: &str) -> bool {
36 !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/')) && !part.contains("..")
37}
38
39fn is_sha(text: &str) -> bool {
40 text.len() == 40 && text.chars().all(|c| c.is_ascii_hexdigit())
41}
42
43/// Whether the runner does `name` (lowercased, without its ref) itself
44/// rather than fetching it.
45fn native(name: &str, docker_hosted: bool) -> bool {
46 matches!(
47 name,
48 "actions/checkout"
49 | "actions/upload-artifact"
50 | "actions/upload-artifact/merge"
51 | "actions/download-artifact"
52 | "actions/cache"
53 | "actions/cache/restore"
54 | "actions/cache/save"
55 ) || (docker_hosted && name == "docker/setup-buildx-action")
56}
57
58/// The repository and ref of an action `uses` fetches from another
59/// repository: (owner, repo, ref). None for one that is local, a Docker
60/// image, done natively, or not a name at all.
61fn remote_action(uses: &str, docker_hosted: bool) -> Option<(String, String, String)> {
62 let uses = uses.trim();
63 if uses.starts_with("./") || uses.starts_with("docker://") {
64 return None;
65 }
66 let (name, git_ref) = uses.split_once('@')?;
67 if git_ref.is_empty() || native(&name.to_ascii_lowercase(), docker_hosted) {
68 return None;
69 }
70 let mut parts = name.splitn(3, '/');
71 let (owner, repo) = (parts.next()?, parts.next()?);
72 (!owner.is_empty() && !repo.is_empty()).then(|| (owner.to_owned(), repo.to_owned(), git_ref.to_owned()))
73}
74
75impl Job {
76 /// Runs a git command, logging it; the credential header is never logged.
77 fn git(&mut self, dir: &Path, args: &[&str], auth: Option<&str>) -> bool {
78 let shown: Vec<&str> = args.to_vec();
79 self.log.line(&format!("[command]git {}", shown.join(" ")));
80 let mut command = Command::new("git");
81 command.current_dir(dir);
82 if let Some(header) = auth {
83 command.args(["-c", &format!("http.extraheader={header}")]);
84 }
85 command.args(args).env("GIT_TERMINAL_PROMPT", "0");
86 let mut commands = Commands::default();
87 matches!(process::run(command, Duration::from_secs(600).min(self.remaining_time()), &mut self.log, &mut commands), Ok(Ended::Exited(0)))
88 }
89
90 /// A fetch, tried again after a short wait when it fails: a transfer
91 /// cut short on the way ("transfer closed with N bytes remaining") is
92 /// over by the next try. Three tries in all, as actions/checkout does.
93 fn fetch_retrying(&mut self, dir: &Path, args: &[&str], auth: Option<&str>) -> bool {
94 for (attempt, wait) in [0u64, 2, 5].into_iter().enumerate() {
95 if attempt > 0 {
96 self.log.line(&format!("The fetch failed; trying again in {wait} s ({} of 3).", attempt + 1));
97 std::thread::sleep(Duration::from_secs(wait));
98 }
99 if self.git(dir, args, auth) {
100 return true;
101 }
102 }
103 false
104 }
105
106 /// `actions/checkout`, against g1t.
107 fn checkout(&mut self, with: &BTreeMap<String, String>) -> (bool, BTreeMap<String, String>) {
108 let checkout = self.spec["checkout"].clone();
109 let own = checkout["repository"].as_str().unwrap_or_default().to_owned();
110 let server = self.contexts["github"]["server_url"].as_str().unwrap_or("https://g1t.sh").to_owned();
111 let repository = with.get("repository").filter(|r| !r.is_empty()).cloned().unwrap_or(own.clone());
112 let same = repository.eq_ignore_ascii_case(&own);
113 let token = with.get("token").filter(|t| !t.is_empty()).cloned().or_else(|| checkout["token"].as_str().map(str::to_owned)).unwrap_or_default();
114 let url = if same { checkout["url"].as_str().unwrap_or_default().to_owned() } else { format!("{server}/{repository}.git") };
115 let path = with.get("path").filter(|p| !p.is_empty()).map_or(self.workspace.clone(), |p| self.workspace.join(p));
116 let depth: u32 = with.get("fetch-depth").and_then(|d| d.parse().ok()).unwrap_or(1);
117 let wanted_ref = with.get("ref").filter(|r| !r.is_empty()).cloned();
118 let auth = (!token.is_empty()).then(|| format!("AUTHORIZATION: basic {}", STANDARD.encode(format!("x-access-token:{token}"))));
119
120 self.log.line(&format!("Checking out {repository} into {}", path.display()));
121 if path.exists() {
122 let _ = std::fs::remove_dir_all(&path);
123 }
124 if let Err(error) = std::fs::create_dir_all(&path) {
125 self.log.line(&format!("##[error]Could not make {}: {error}", path.display()));
126 return (false, BTreeMap::new());
127 }
128 let _ = Command::new("git").args(["config", "--global", "--add", "safe.directory", "*"]).status();
129 if !self.git(&path, &["init", "--quiet"], None) || !self.git(&path, &["remote", "add", "origin", &url], None) {
130 return (false, BTreeMap::new());
131 }
132
133 // What to fetch, and which commit to end up on.
134 let run_ref = checkout["ref"].as_str().unwrap_or_default().to_owned();
135 let run_sha = checkout["sha"].as_str().unwrap_or_default().to_owned();
136 let is_sha = |r: &str| r.len() == 40 && r.chars().all(|c| c.is_ascii_hexdigit());
137 let (fetch, sha, branch): (String, Option<String>, Option<String>) = match &wanted_ref {
138 Some(r) if is_sha(r) => ("HEAD".into(), Some(r.clone()), None),
139 Some(r) if r.starts_with("refs/") => (r.clone(), None, r.strip_prefix("refs/heads/").map(str::to_owned)),
140 Some(r) => (r.clone(), None, Some(r.clone())),
141 // A pull request's merge ref, or no ref at all (a deployment of
142 // a bare commit): the commit itself.
143 None if same && (run_ref.starts_with("refs/pull/") || run_ref.is_empty()) => ("HEAD".into(), Some(run_sha.clone()), None),
144 None if same => (run_ref.clone(), Some(run_sha.clone()), run_ref.strip_prefix("refs/heads/").map(str::to_owned)),
145 None => ("HEAD".into(), None, None),
146 };
147 let depth_arg = format!("--depth={depth}");
148 let mut args = vec!["fetch", "--no-tags", "--prune", "--quiet"];
149 if depth > 0 {
150 args.push(&depth_arg);
151 }
152 if with.get("fetch-tags").is_some_and(|t| t == "true") {
153 args.retain(|a| *a != "--no-tags");
154 }
155 args.push("origin");
156 args.push(&fetch);
157 if !self.fetch_retrying(&path, &args, auth.as_deref()) {
158 self.log.line(&format!("##[error]Could not fetch {fetch} from {repository}."));
159 return (false, BTreeMap::new());
160 }
161 let target = sha.clone().unwrap_or_else(|| "FETCH_HEAD".into());
162 // The commit may be further back than a shallow fetch reaches: the
163 // branch moved on after the run began, say. Ask for the commit
164 // itself, and failing that the whole history; a plain fetch never
165 // reaches past a shallow boundary.
166 let has = |target: &str| Command::new("git").current_dir(&path).args(["cat-file", "-e", &format!("{target}^{{commit}}")]).status().is_ok_and(|s| s.success());
167 if !has(&target) {
168 let by_sha = sha.as_deref().is_some_and(|sha| {
169 let mut args = vec!["fetch", "--no-tags", "--quiet"];
170 if depth > 0 {
171 args.push(&depth_arg);
172 }
173 args.extend(["origin", sha]);
174 self.git(&path, &args, auth.as_deref()) && has(sha)
175 });
176 let shallow = path.join(".git").join("shallow").exists();
177 let deepen: &[&str] = if shallow { &["fetch", "--no-tags", "--quiet", "--unshallow", "origin"] } else { &["fetch", "--no-tags", "--quiet", "origin"] };
178 if !by_sha && !self.fetch_retrying(&path, deepen, auth.as_deref()) {
179 return (false, BTreeMap::new());
180 }
181 }
182 let checked_out = match &branch {
183 Some(branch) => self.git(&path, &["checkout", "--quiet", "--force", "-B", branch, &target], None),
184 None => self.git(&path, &["checkout", "--quiet", "--force", "--detach", &target], None),
185 };
186 if !checked_out {
187 return (false, BTreeMap::new());
188 }
189 if with.get("persist-credentials").is_none_or(|p| p != "false")
190 && let Some(header) = &auth
191 {
192 let key = format!("http.{server}/.extraheader");
193 let _ = Command::new("git").current_dir(&path).args(["config", "--local", &key, header]).status();
194 }
195 if let Some(submodules) = with.get("submodules").filter(|s| *s == "true" || *s == "recursive") {
196 let mut args = vec!["submodule", "update", "--init", "--quiet"];
197 if submodules == "recursive" {
198 args.push("--recursive");
199 }
200 if !self.git(&path, &args, auth.as_deref()) {
201 self.log.line("##[warning]Submodules could not all be checked out; only those hosted on g1t can be.");
202 }
203 }
204 if with.get("lfs").is_some_and(|l| l == "true") {
205 self.log.line("##[warning]Git LFS files are not fetched on g1t yet.");
206 }
207 let commit = Command::new("git").current_dir(&path).args(["rev-parse", "HEAD"]).output().ok().map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()).unwrap_or_default();
208 self.log.line(&format!("Checked out {commit}"));
209 let mut outputs = BTreeMap::new();
210 outputs.insert("ref".into(), wanted_ref.unwrap_or(run_ref));
211 outputs.insert("commit".into(), commit);
212 (true, outputs)
213 }
214
215 /// Fetches another repository's action, once per job: from g1t when
216 /// g1t has the repository and this one may use it, otherwise from
217 /// GitHub. A private repository on g1t that may not be used here fails
218 /// the step, saying why, rather than fetching something else by its
219 /// name.
220 fn fetch_remote_action(&mut self, owner: &str, repo: &str, git_ref: &str) -> Option<PathBuf> {
221 let on_g1t = super::paths::under_home(ACTIONS_DIR).join("_g1t").join(owner).join(repo).join(git_ref);
222 let on_github = super::paths::under_home(ACTIONS_DIR).join(owner).join(repo).join(git_ref);
223 for dir in [&on_g1t, &on_github] {
224 if dir.join(".g1t-fetched").exists() {
225 return Some(dir.clone());
226 }
227 }
228 if !(safe(owner) && safe(repo) && safe(git_ref)) {
229 self.log.line(&format!("##[error]`{owner}/{repo}@{git_ref}` is not a name g1t can fetch."));
230 return None;
231 }
232 match self.log.api.action(&format!("{owner}/{repo}"), git_ref) {
233 Ok(found) if found["source"] == "g1t" => self.fetch_g1t_action(&on_g1t, owner, repo, git_ref, &found),
234 Ok(found) => {
235 if let Some(note) = found["note"].as_str() {
236 self.log.line(&format!("##[warning]{note}"));
237 }
238 let sha = found["sha"].as_str().filter(|sha| is_sha(sha)).map(str::to_owned);
239 if let Some(sha) = &sha
240 && found["archive"] == true
241 && let Some(dir) = self.fetch_archived_action(owner, repo, git_ref, sha)
242 {
243 return Some(dir);
244 }
245 self.fetch_action(owner, repo, git_ref, sha.as_deref())
246 }
247 Err((true, why)) => {
248 self.log.line(&format!("##[error]{why}"));
249 None
250 }
251 Err((false, why)) => {
252 self.log.line(&format!("##[warning]g1t could not say where {owner}/{repo} is ({why}); fetching it from GitHub."));
253 self.fetch_action(owner, repo, git_ref, None)
254 }
255 }
256 }
257
258 /// Fetches an action from a repository on g1t, at its ref, with the
259 /// read-only token g1t gave for it when it is private.
260 fn fetch_g1t_action(&mut self, dir: &Path, owner: &str, repo: &str, git_ref: &str, found: &Value) -> Option<PathBuf> {
261 let url = found["url"].as_str().unwrap_or_default().to_owned();
262 let token = found["token"].as_str().filter(|token| !token.is_empty()).map(str::to_owned);
263 if let Some(token) = &token {
264 self.log.add_mask(token);
265 }
266 let auth = token.map(|token| format!("AUTHORIZATION: basic {}", STANDARD.encode(format!("x-access-token:{token}"))));
267 self.log.line(&format!("Download action repository '{owner}/{repo}@{git_ref}' from g1t"));
268 let _ = std::fs::remove_dir_all(dir);
269 if std::fs::create_dir_all(dir).is_err() || !self.git(dir, &["init", "--quiet"], None) || !self.git(dir, &["remote", "add", "origin", &url], None) {
270 return None;
271 }
272 // A branch or tag at its tip; a commit may need the history.
273 let shallow = self.fetch_retrying(dir, &["fetch", "--depth=1", "--no-tags", "--quiet", "origin", git_ref], auth.as_deref());
274 let checked_out = if shallow {
275 self.git(dir, &["checkout", "--quiet", "--force", "--detach", "FETCH_HEAD"], None)
276 } else {
277 self.fetch_retrying(dir, &["fetch", "--quiet", "--tags", "origin", "+refs/heads/*:refs/remotes/origin/*"], auth.as_deref())
278 && self.git(dir, &["checkout", "--quiet", "--force", "--detach", git_ref], None)
279 };
280 if !checked_out {
281 self.log.line(&format!("##[error]Could not fetch {owner}/{repo}@{git_ref} from g1t: is {git_ref} a branch, tag or commit there?"));
282 let _ = std::fs::remove_dir_all(dir);
283 return None;
284 }
285 let _ = std::fs::write(dir.join(".g1t-fetched"), "");
286 Some(dir.to_path_buf())
287 }
288
289 /// Downloads a GitHub action's archive that g1t keeps, at the commit
290 /// g1t resolved its ref to. None when it could not, and the job fetches
291 /// it from GitHub instead.
292 fn fetch_archived_action(&mut self, owner: &str, repo: &str, git_ref: &str, sha: &str) -> Option<PathBuf> {
293 let dir = super::paths::under_home(ACTIONS_DIR).join(owner).join(repo).join(git_ref);
294 self.log.line(&format!("Download action repository '{owner}/{repo}@{git_ref}' (SHA:{sha}) from g1t"));
295 let archive = self.temp.join(format!("action{}.tar.gz", super::rand_id()));
296 let downloaded = self.log.api.action_archive(&format!("{owner}/{repo}"), sha, &archive);
297 let unpacked = match downloaded {
298 Ok(_) => {
299 let _ = std::fs::remove_dir_all(&dir);
300 let _ = std::fs::create_dir_all(&dir);
301 let mut command = Command::new("tar");
302 command.arg("-xzf").arg(&archive).arg("-C").arg(&dir).arg("--strip-components=1");
303 let mut commands = Commands::default();
304 matches!(process::run(command, Duration::from_secs(300).min(self.remaining_time()), &mut self.log, &mut commands), Ok(Ended::Exited(0)))
305 }
306 Err(why) => {
307 self.log.line(&format!("g1t could not send it ({why}); fetching it from GitHub."));
308 false
309 }
310 };
311 let _ = std::fs::remove_file(&archive);
312 if !unpacked {
313 let _ = std::fs::remove_dir_all(&dir);
314 return None;
315 }
316 let _ = std::fs::write(dir.join(".g1t-fetched"), "");
317 Some(dir)
318 }
319
320 /// Fetches an action from GitHub, once per job: at `sha` when g1t
321 /// resolved its ref to one, so it is the commit g1t named.
322 fn fetch_action(&mut self, owner: &str, repo: &str, git_ref: &str, sha: Option<&str>) -> Option<PathBuf> {
323 let dir = super::paths::under_home(ACTIONS_DIR).join(owner).join(repo).join(git_ref);
324 if dir.join(".g1t-fetched").exists() {
325 return Some(dir);
326 }
327 if !(safe(owner) && safe(repo) && safe(git_ref)) {
328 self.log.line(&format!("##[error]`{owner}/{repo}@{git_ref}` is not a name g1t can fetch."));
329 return None;
330 }
331 match sha {
332 Some(sha) => self.log.line(&format!("Download action repository '{owner}/{repo}@{git_ref}' (SHA:{sha})")),
333 None => self.log.line(&format!("Download action repository '{owner}/{repo}@{git_ref}'")),
334 }
335 let _ = std::fs::create_dir_all(&dir);
336 let url = format!("https://codeload.github.com/{owner}/{repo}/tar.gz/{}", sha.unwrap_or(git_ref));
337 let script = format!("set -o pipefail; curl -fsSL --retry 3 '{url}' | tar -xz -C '{}' --strip-components=1", dir.display());
338 let mut command = Command::new("bash");
339 command.args(["-c", &script]);
340 let mut commands = Commands::default();
341 match process::run(command, Duration::from_secs(300).min(self.remaining_time()), &mut self.log, &mut commands) {
342 Ok(Ended::Exited(0)) => {
343 let _ = std::fs::write(dir.join(".g1t-fetched"), "");
344 Some(dir)
345 }
346 _ => {
347 self.log.line(&format!("##[error]Could not download {owner}/{repo}@{git_ref} from GitHub."));
348 let _ = std::fs::remove_dir_all(&dir);
349 None
350 }
351 }
352 }
353
354 /// Downloads every action the job's steps fetch from other
355 /// repositories, before the first step runs, as GitHub's runner does in
356 /// "Set up job". False when one could not be: the job fails before
357 /// anything runs. Actions a composite action uses are fetched as it
358 /// runs.
359 pub(crate) fn prepare_actions(&mut self, steps: &[Map<String, Value>]) -> bool {
360 let mut wanted: Vec<(String, String, String)> = Vec::new();
361 for step in steps {
362 if let Some(found) = step.get("uses").and_then(Value::as_str).and_then(|uses| remote_action(uses, self.docker_hosted))
363 && !wanted.contains(&found)
364 {
365 wanted.push(found);
366 }
367 }
368 if wanted.is_empty() {
369 return true;
370 }
371 self.log.line("Prepare all required actions");
372 let mut ready = true;
373 for (owner, repo, git_ref) in &wanted {
374 if self.fetch_remote_action(owner, repo, git_ref).is_none() {
375 ready = false;
376 }
377 }
378 if !ready {
379 self.log.line("##[error]Not every action this job uses could be downloaded, so no step was run.");
380 }
381 ready
382 }
383
384 /// Runs a JavaScript file of an action with Node: the one its
385 /// `runs.using` names where the machine has it (`node_program`).
386 pub(crate) fn run_node(&mut self, action_dir: &Path, script: &str, env: &BTreeMap<String, String>, using: &str) -> bool {
387 let id = format!("node{}", super::rand_id());
388 let Ok(files) = StepFiles::new(&self.temp, &id) else { return false };
389 let full = self.process_env(env, &files);
390 let script_path = action_dir.join(script);
391 // In a job container whose image runs the runner's Node, the action
392 // runs there, as on GitHub.
393 let in_container = self.container.as_ref().filter(|c| c.node).map(|c| c.path.clone()).and_then(|image_path| {
394 let inside = self.container_env(env, full.clone(), &image_path);
395 self.in_container(containers::CONTAINER_NODE, &[script_path.display().to_string()], &self.workspace, inside)
396 });
397 let command = match in_container {
398 Some(command) => command,
399 None => {
400 let node = node_program(using, |name| std::env::var(name).ok(), |path| path.is_file());
401 let mut command = Command::new(node);
402 command.arg(&script_path).current_dir(&self.workspace).env_clear().envs(full);
403 command
404 }
405 };
406 let mut commands = Commands {
407 debug: self.debug,
408 ..Commands::default()
409 };
410 let ended = process::run(command, Duration::from_secs(6 * 3600).min(self.deadline_left()), &mut self.log, &mut commands);
411 let ok = matches!(ended, Ok(Ended::Exited(0)));
412 match ended {
413 Ok(Ended::Exited(code)) if code != 0 => self.log.line(&format!("##[error]The action exited with code {code}.")),
414 Ok(Ended::TimedOut) => self.log.line("##[error]The action ran past its time limit and was stopped."),
415 _ => {}
416 }
417 let (outputs, state) = self.absorb(&files, &commands);
418 self.last_node_outputs = outputs;
419 self.last_node_state = state;
420 ok
421 }
422
423 fn deadline_left(&self) -> Duration {
424 self.remaining_time()
425 }
426
427 /// Runs a `uses:` step. Returns whether it succeeded, and its outputs.
428 #[allow(clippy::too_many_arguments)]
429 pub(crate) fn uses(
430 &mut self,
431 uses: &str,
432 with: &BTreeMap<String, String>,
433 env: &BTreeMap<String, String>,
434 frame: &Frame,
435 title: &str,
436 action_name: &str,
437 _timeout: Duration,
438 ) -> (bool, BTreeMap<String, String>) {
439 let uses = uses.trim();
440 if let Some(image) = uses.strip_prefix("docker://") {
441 // `with.args` and `with.entrypoint` are the container's; every
442 // input is also an `INPUT_` variable, as on GitHub.
443 let mut step_env = env.clone();
444 step_env.insert("GITHUB_ACTION".into(), action_name.to_owned());
445 for (input, value) in with {
446 step_env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone());
447 }
448 let run = DockerRun {
449 image: image.to_owned(),
450 entrypoint: with.get("entrypoint").filter(|e| !e.is_empty()).cloned(),
451 args: with.get("args").map(|a| containers::split_words(a)).unwrap_or_default(),
452 env: step_env,
453 };
454 let (ok, outputs, _) = self.run_docker(&run);
455 return (ok, outputs);
456 }
457 let (name, git_ref) = uses.split_once('@').unwrap_or((uses, ""));
458 let lower = name.to_ascii_lowercase();
459 if lower == "docker/setup-buildx-action" && native(&lower, self.docker_hosted) {
460 return self.setup_buildx(with);
461 }
462 match lower.as_str() {
463 "actions/checkout" => return self.checkout(with),
464 "actions/upload-artifact" => return self.upload_artifact(with),
465 "actions/upload-artifact/merge" => return self.merge_artifacts(with),
466 "actions/download-artifact" => return self.download_artifact(with),
467 "actions/cache" => return self.cache(with, true, title),
468 "actions/cache/restore" => return self.cache(with, false, title),
469 "actions/cache/save" => return self.cache_save_now(with),
470 _ => {}
471 }
472 let Some(found) = self.resolve_action(uses) else {
473 return (false, BTreeMap::new());
474 };
475 let Action { dir, local, manifest: action, .. } = &found;
476
477 // Inputs: what the step gives, else the action's defaults.
478 let env_context = env.clone();
479 let contexts = self.contexts_for(frame, &env_context);
480 let inputs = self.action_inputs(action, with, &contexts, true);
481
482 let runs = action.get("runs").cloned().unwrap_or(Value::Null);
483 let using = runs.get("using").map(expr::to_text).unwrap_or_default().to_ascii_lowercase();
484 let mut step_env = action_env(env, action_name, &found, git_ref);
485
486 if using.starts_with("node") {
487 for (input, value) in &inputs {
488 step_env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone());
489 }
490 let condition_of = |key: &str| runs.get(key).map(expr::to_text).unwrap_or_else(|| "always()".into());
491 // State an action saves, `STATE_<name>` for its later stages.
492 let mut state = BTreeMap::new();
493 if let Some(pre) = runs.get("pre").map(expr::to_text) {
494 if frame.action_path.is_some() {
495 // An action inside a composite action: its `pre` right
496 // before its `main`.
497 let run_pre = self.with_scope(&contexts, |scope| expr::condition(&condition_of("pre-if"), scope)).unwrap_or(true);
498 if run_pre {
499 if !self.run_node(dir, &pre, &step_env, &using) {
500 return (false, BTreeMap::new());
501 }
502 state = std::mem::take(&mut self.last_node_state);
503 }
504 } else if *local {
505 self.log.line(&format!("##[warning]`pre` execution is not supported for local action from '{uses}'"));
506 } else {
507 // Run before the job's first step (`pre_steps`).
508 state = self.pre_state.remove(action_name).unwrap_or_default();
509 }
510 }
511 let Some(main) = runs.get("main").map(expr::to_text) else {
512 self.log.line(&format!("##[error]`{uses}` has no `runs.main`."));
513 return (false, BTreeMap::new());
514 };
515 let mut main_env = step_env.clone();
516 for (name, value) in &state {
517 main_env.insert(format!("STATE_{name}"), value.clone());
518 }
519 let ok = self.run_node(dir, &main, &main_env, &using);
520 let outputs = std::mem::take(&mut self.last_node_outputs);
521 state.extend(std::mem::take(&mut self.last_node_state));
522 if let Some(post) = runs.get("post").map(expr::to_text) {
523 let mut post_env = step_env.clone();
524 for (name, value) in state {
525 post_env.insert(format!("STATE_{name}"), value);
526 }
527 self.posts.push(Post {
528 name: format!("Post {title}"),
529 condition: condition_of("post-if"),
530 env: post_env,
531 run: PostRun::Node { action_dir: dir.clone(), script: post, using: using.clone() },
532 });
533 }
534 return (ok, outputs);
535 }
536 if using == "composite" {
537 let mut inner = Frame {
538 steps: Map::new(),
539 inputs: Some(Value::Object(inputs.iter().map(|(k, v)| (k.clone(), json!(v))).collect())),
540 action_path: Some(dir.display().to_string()),
541 env: env.clone(),
542 };
543 let mut steps: Vec<Map<String, Value>> = runs.get("steps").and_then(Value::as_array).map(|s| s.iter().filter_map(|s| s.as_object().cloned()).collect()).unwrap_or_default();
544 super::name_steps(&mut steps);
545 let was_failed = self.failed;
546 // A composite's steps see their own success, not the job's.
547 self.failed = false;
548 let mut ok = true;
549 for step in &steps {
550 if !self.step(&mut inner, step, 0, false, &Map::new()) {
551 ok = false;
552 }
553 }
554 let contexts = self.contexts_for(&inner, &inner.env.clone());
555 let mut outputs = BTreeMap::new();
556 if let Some(Value::Object(declared)) = action.get("outputs") {
557 for (name, spec) in declared {
558 if let Some(value) = spec.get("value") {
559 let value = self.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
560 outputs.insert(name.clone(), expr::to_text(&value));
561 }
562 }
563 }
564 self.failed = was_failed;
565 return (ok, outputs);
566 }
567 if using == "docker" {
568 return self.docker_action(uses, dir, &runs, &inputs, &step_env, frame, title);
569 }
570 self.log.line(&format!("##[error]`{uses}` runs with `{using}`, which g1t does not know."));
571 (false, BTreeMap::new())
572 }
573
574 /// A Docker action: its image built from its Dockerfile (or pulled,
575 /// for `docker://`), then run with its `args`, `entrypoint` and `env`,
576 /// its inputs as `INPUT_` variables, and `pre-entrypoint` and
577 /// `post-entrypoint` around it.
578 #[allow(clippy::too_many_arguments)]
579 fn docker_action(
580 &mut self,
581 uses: &str,
582 dir: &Path,
583 runs: &Value,
584 inputs: &BTreeMap<String, String>,
585 step_env: &BTreeMap<String, String>,
586 frame: &Frame,
587 title: &str,
588 ) -> (bool, BTreeMap<String, String>) {
589 let image = runs.get("image").map(expr::to_text).unwrap_or_default();
590 let image = if let Some(pulled) = image.strip_prefix("docker://") {
591 pulled.to_owned()
592 } else if image.is_empty() {
593 self.log.line(&format!("##[error]`{uses}` has no `runs.image`."));
594 return (false, BTreeMap::new());
595 } else {
596 match self.build_action_image(dir, &image, uses) {
597 Some(tag) => tag,
598 None => return (false, BTreeMap::new()),
599 }
600 };
601 // `args` and `env` read with the action's own inputs.
602 let mut env = step_env.clone();
603 for (input, value) in inputs {
604 env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone());
605 }
606 let mut scope_frame = frame.clone();
607 scope_frame.inputs = Some(Value::Object(inputs.iter().map(|(k, v)| (k.clone(), json!(v))).collect()));
608 let contexts = self.contexts_for(&scope_frame, &env);
609 if let Some(Value::Object(own)) = runs.get("env") {
610 for (name, value) in own {
611 let value = self.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
612 env.insert(name.clone(), expr::to_text(&value));
613 }
614 }
615 let args: Vec<String> = match runs.get("args") {
616 Some(Value::Array(items)) => items
617 .iter()
618 .map(|item| {
619 let value = self.with_scope(&contexts, |scope| expr::interpolate_value(item, scope)).unwrap_or(Value::Null);
620 expr::to_text(&value)
621 })
622 .collect(),
623 _ => Vec::new(),
624 };
625 let entry = |key: &str| runs.get(key).map(expr::to_text).filter(|e| !e.is_empty());
626 if let Some(pre) = entry("pre-entrypoint") {
627 let run = DockerRun { image: image.clone(), entrypoint: Some(pre), args: Vec::new(), env: env.clone() };
628 if !self.run_docker(&run).0 {
629 return (false, BTreeMap::new());
630 }
631 }
632 let run = DockerRun { image: image.clone(), entrypoint: entry("entrypoint"), args, env: env.clone() };
633 let (ok, outputs, state) = self.run_docker(&run);
634 if let Some(post) = entry("post-entrypoint") {
635 let mut post_env = env;
636 for (name, value) in state {
637 post_env.insert(format!("STATE_{name}"), value);
638 }
639 self.posts.push(Post {
640 name: format!("Post {title}"),
641 condition: runs.get("post-if").map(expr::to_text).unwrap_or_else(|| "always()".into()),
642 env: BTreeMap::new(),
643 run: PostRun::Docker(DockerRun { image, entrypoint: Some(post), args: Vec::new(), env: post_env }),
644 });
645 }
646 (ok, outputs)
647 }
648}
649
650/// An action, read from its action.yml.
651pub(crate) struct Action {
652 pub(crate) dir: PathBuf,
653 /// `owner/repo`, or empty for one in the repository.
654 pub(crate) repository: String,
655 pub(crate) local: bool,
656 pub(crate) manifest: Value,
657}
658
659/// An action's `pre`, run before the job's first step.
660pub(crate) struct PreStep {
661 /// Its step's `GITHUB_ACTION`, by which the step finds the state it saved.
662 pub(crate) key: String,
663 /// `pre-if`, `always()` when it has none.
664 pub(crate) condition: String,
665 pub(crate) action_dir: PathBuf,
666 pub(crate) script: String,
667 pub(crate) using: String,
668 /// The `env` context its condition reads.
669 pub(crate) context_env: BTreeMap<String, String>,
670 /// What its process is given: the step's variables and inputs.
671 pub(crate) env: BTreeMap<String, String>,
672}
673
674impl Job {
675 /// Finds `uses` (fetching it when it is another repository's) and reads
676 /// its action.yml. A problem is told in the log.
677 fn resolve_action(&mut self, uses: &str) -> Option<Action> {
678 let (name, git_ref) = uses.split_once('@').unwrap_or((uses, ""));
679 let source = if let Some(local) = name.strip_prefix("./") {
680 // A repository moved from GitHub renamed `.github` to `.g1t`, but
681 // its workflows still say `./.github/actions/…`.
682 let mut dir = self.workspace.join(local);
683 if let Some(rest) = local.strip_prefix(".github/")
684 && !dir.exists()
685 {
686 dir = self.workspace.join(".g1t").join(rest);
687 }
688 Source::Local(dir)
689 } else {
690 let mut parts = name.splitn(3, '/');
691 let (Some(owner), Some(repo)) = (parts.next(), parts.next()) else {
692 self.log.line(&format!("##[error]`{uses}` is not an action: use owner/repo@ref, owner/repo/path@ref, or ./path."));
693 return None;
694 };
695 if git_ref.is_empty() {
696 self.log.line(&format!("##[error]`{uses}` needs a version, such as @v4."));
697 return None;
698 }
699 Source::GitHub {
700 owner: owner.to_owned(),
701 repo: repo.to_owned(),
702 path: parts.next().unwrap_or_default().to_owned(),
703 git_ref: git_ref.to_owned(),
704 }
705 };
706 let (dir, repository) = match &source {
707 Source::Local(dir) => (dir.clone(), String::new()),
708 Source::GitHub { owner, repo, path, git_ref } => {
709 let root = self.fetch_remote_action(owner, repo, git_ref)?;
710 (if path.is_empty() { root } else { root.join(path) }, format!("{owner}/{repo}"))
711 }
712 };
713 let Some(manifest) = ["action.yml", "action.yaml"].iter().map(|f| dir.join(f)).find(|p| p.exists()) else {
714 self.log.line(&format!("##[error]`{uses}` has no action.yml."));
715 return None;
716 };
717 let Some(yaml) = std::fs::read_to_string(&manifest).ok().and_then(|text| serde_yaml::from_str::<serde_yaml::Value>(&text).ok()) else {
718 self.log.line(&format!("##[error]`{uses}`: its action.yml does not read."));
719 return None;
720 };
721 Some(Action { dir, repository, local: matches!(source, Source::Local(_)), manifest: yaml_to_json(&yaml) })
722 }
723
724 /// An action's inputs: what the step gives, else the action's defaults,
725 /// read with `contexts`. With `warn`, inputs the action does not declare
726 /// are warned of, as GitHub's runner does.
727 fn action_inputs(&mut self, action: &Value, with: &BTreeMap<String, String>, contexts: &Map<String, Value>, warn: bool) -> BTreeMap<String, String> {
728 let mut inputs: BTreeMap<String, String> = BTreeMap::new();
729 let mut declared_names = Vec::new();
730 if let Some(Value::Object(declared)) = action.get("inputs") {
731 for (input, spec) in declared {
732 declared_names.push(input.clone());
733 let given = with.iter().find(|(k, _)| k.eq_ignore_ascii_case(input)).map(|(_, v)| v.clone());
734 let value = match given {
735 Some(value) => value,
736 None => match spec.get("default") {
737 Some(default) => {
738 let default = self.with_scope(contexts, |scope| expr::interpolate_value(default, scope)).unwrap_or(Value::Null);
739 expr::to_text(&default)
740 }
741 None => String::new(),
742 },
743 };
744 inputs.insert(input.clone(), value);
745 }
746 }
747 for (key, value) in with {
748 if !inputs.keys().any(|k| k.eq_ignore_ascii_case(key)) {
749 inputs.insert(key.clone(), value.clone());
750 }
751 }
752 let docker = action["runs"]["using"].as_str().is_some_and(|u| u.eq_ignore_ascii_case("docker"));
753 if warn && let Some(warning) = unexpected_inputs(&declared_names, &with.keys().cloned().collect::<Vec<_>>(), docker) {
754 self.log.line(&format!("##[warning]{warning}"));
755 }
756 inputs
757 }
758
759 /// The `pre`s of the job's steps, in step order, each with its step's
760 /// index: those of JavaScript actions from other repositories, fetched
761 /// now, as GitHub's runner fetches every action while it sets up the
762 /// job. An action in the repository is not there yet, so its `pre` is
763 /// not run, as on GitHub.
764 pub(crate) fn pre_steps(&mut self, steps: &[Map<String, Value>]) -> Vec<(usize, PreStep)> {
765 let frame = Frame::default();
766 let mut pres = Vec::new();
767 for (index, step) in steps.iter().enumerate() {
768 let Some(uses) = step.get("uses").map(|u| expr::to_text(u).trim().to_owned()) else { continue };
769 // Only another repository's action, which `prepare_actions` has
770 // already downloaded.
771 if remote_action(&uses, self.docker_hosted).is_none() {
772 continue;
773 }
774 let Some(found) = self.resolve_action(&uses) else { continue };
775 let runs = found.manifest.get("runs").cloned().unwrap_or(Value::Null);
776 let using = runs.get("using").map(expr::to_text).unwrap_or_default().to_ascii_lowercase();
777 let Some(script) = runs.get("pre").map(expr::to_text).filter(|_| using.starts_with("node")) else { continue };
778 let env_before = self.env_context(&frame);
779 let contexts = self.contexts_for(&frame, &env_before);
780 let with = self.step_with(step, &contexts);
781 let context_env = self.step_env(step, &contexts, env_before);
782 let contexts = self.contexts_for(&frame, &context_env);
783 let inputs = self.action_inputs(&found.manifest, &with, &contexts, false);
784 let key = step.get(super::ACTION_NAME).map(expr::to_text).unwrap_or_default();
785 let git_ref = uses.split_once('@').map_or("", |(_, r)| r);
786 let mut env = action_env(&context_env, &key, &found, git_ref);
787 for (input, value) in &inputs {
788 env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone());
789 }
790 let condition = runs.get("pre-if").map(expr::to_text).unwrap_or_else(|| "always()".into());
791 pres.push((index, PreStep { key, condition, action_dir: found.dir, script, using, context_env, env }));
792 }
793 pres
794 }
795
796 /// Whether a `pre`'s `pre-if` holds, read against the job's status.
797 pub(crate) fn pre_runs(&self, pre: &PreStep) -> bool {
798 let contexts = self.contexts_for(&Frame::default(), &pre.context_env);
799 self.with_scope(&contexts, |scope| expr::condition(&pre.condition, scope)).unwrap_or(true)
800 }
801
802 /// Runs a `pre`, keeping the state it saves for its step's main and post.
803 pub(crate) fn run_pre(&mut self, pre: &PreStep) -> bool {
804 let ok = self.run_node(&pre.action_dir, &pre.script, &pre.env, &pre.using);
805 let state = std::mem::take(&mut self.last_node_state);
806 self.last_node_outputs.clear();
807 self.pre_state.insert(pre.key.clone(), state);
808 ok
809 }
810}
811
812/// The variables a step running an action gets over its own: which
813/// action it is and where.
814fn action_env(env: &BTreeMap<String, String>, action_name: &str, action: &Action, git_ref: &str) -> BTreeMap<String, String> {
815 let mut step_env = env.clone();
816 step_env.insert("GITHUB_ACTION".into(), action_name.to_owned());
817 step_env.insert("GITHUB_ACTION_REPOSITORY".into(), action.repository.clone());
818 step_env.insert("GITHUB_ACTION_REF".into(), git_ref.to_owned());
819 step_env.insert("GITHUB_ACTION_PATH".into(), action.dir.display().to_string());
820 step_env
821}
822
823/// GitHub's warning for inputs a step gives that its action does not
824/// declare (a Docker action also takes `entryPoint` and `args`), if any.
825fn unexpected_inputs(declared: &[String], given: &[String], docker: bool) -> Option<String> {
826 let mut valid: Vec<String> = declared.to_vec();
827 if docker {
828 valid.extend(["entryPoint".to_owned(), "args".to_owned()]);
829 }
830 let unexpected: Vec<&str> = given.iter().filter(|g| !valid.iter().any(|v| v.eq_ignore_ascii_case(g))).map(String::as_str).collect();
831 if unexpected.is_empty() {
832 return None;
833 }
834 Some(format!("Unexpected input(s) '{}', valid inputs are ['{}']", unexpected.join("', '"), valid.join("', '")))
835}
836
837/// The Node an action's `runs.using` asks for: for `node20` (or any
838/// `nodeNN`), the binary `G1T_NODE20` names or `/opt/node20/bin/node`,
839/// when there is one; otherwise, and for anything else, the `node` on
840/// `PATH`, the runner's own (Node 24). Nothing is logged either way.
841pub(crate) fn node_program(using: &str, var: impl Fn(&str) -> Option<String>, exists: impl Fn(&Path) -> bool) -> String {
842 let using = using.trim().to_ascii_lowercase();
843 let versioned = using.strip_prefix("node").is_some_and(|v| !v.is_empty() && v.chars().all(|c| c.is_ascii_digit()));
844 if versioned {
845 let named = var(&format!("G1T_{}", using.to_ascii_uppercase())).filter(|p| !p.is_empty() && exists(Path::new(p)));
846 if let Some(path) = named {
847 return path;
848 }
849 let standard = format!("/opt/{using}/bin/node");
850 if exists(Path::new(&standard)) {
851 return standard;
852 }
853 }
854 "node".into()
855}
856
857#[cfg(test)]
858mod tests {
859 use super::*;
860
861 #[test]
862 fn the_actions_fetched_before_the_first_step_are_other_repositories() {
863 let found = |uses: &str| remote_action(uses, true);
864 assert_eq!(found("actions/setup-node@v4"), Some(("actions".into(), "setup-node".into(), "v4".into())));
865 assert_eq!(found(" github/codeql-action/init@v3 "), Some(("github".into(), "codeql-action".into(), "v3".into())));
866 // Done by the runner itself, local, an image, or no version.
867 assert_eq!(found("actions/checkout@v4"), None);
868 assert_eq!(found("Actions/Cache/Restore@v4"), None);
869 assert_eq!(found("docker/setup-buildx-action@v3"), None);
870 assert!(remote_action("docker/setup-buildx-action@v3", false).is_some());
871 assert_eq!(found("./.g1t/actions/setup"), None);
872 assert_eq!(found("docker://alpine:3"), None);
873 assert_eq!(found("actions/setup-node"), None);
874 assert_eq!(found("setup-node@v4"), None);
875 }
876
877 #[test]
878 fn unexpected_inputs_are_named_with_the_valid_ones() {
879 let declared = vec!["token".to_owned(), "path".to_owned()];
880 assert_eq!(unexpected_inputs(&declared, &["Token".into()], false), None);
881 assert_eq!(
882 unexpected_inputs(&declared, &["token".into(), "foo".into(), "bar".into()], false).as_deref(),
883 Some("Unexpected input(s) 'foo', 'bar', valid inputs are ['token', 'path']")
884 );
885 assert_eq!(unexpected_inputs(&[], &["x".into()], false).as_deref(), Some("Unexpected input(s) 'x', valid inputs are ['']"));
886 // A Docker action takes `entrypoint` and `args` too.
887 assert_eq!(unexpected_inputs(&declared, &["entrypoint".into(), "args".into()], true), None);
888 assert!(unexpected_inputs(&declared, &["args".into()], false).is_some());
889 }
890
891 #[test]
892 fn node20_runs_with_a_node20_where_there_is_one() {
893 let none = |_: &str| None;
894 assert_eq!(node_program("node20", none, |_| false), "node");
895 assert_eq!(node_program("node20", none, |p| p == Path::new("/opt/node20/bin/node")), "/opt/node20/bin/node");
896 let named = |name: &str| (name == "G1T_NODE20").then(|| "/usr/local/n20/bin/node".to_owned());
897 assert_eq!(node_program("Node20", named, |_| true), "/usr/local/n20/bin/node");
898 // A named Node that is not there is passed over.
899 assert_eq!(node_program("node20", named, |p| p == Path::new("/opt/node20/bin/node")), "/opt/node20/bin/node");
900 assert_eq!(node_program("node24", none, |_| false), "node");
901 assert_eq!(node_program("composite", none, |_| true), "node");
902 assert_eq!(node_program("node", none, |_| true), "node");
903 }
904}