Skip to content
920 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 self.log.line("Getting action download info");
373 let mut ready = true;
374 for (owner, repo, git_ref) in &wanted {
375 if self.fetch_remote_action(owner, repo, git_ref).is_none() {
376 ready = false;
377 }
378 }
379 if !ready {
380 self.log.line("##[error]Not every action this job uses could be downloaded, so no step was run.");
381 }
382 ready
383 }
384
385 /// Runs a JavaScript file of an action with Node: the one its
386 /// `runs.using` names where the machine has it (`node_program`).
387 pub(crate) fn run_node(&mut self, action_dir: &Path, script: &str, env: &BTreeMap<String, String>, using: &str) -> bool {
388 let id = format!("node{}", super::rand_id());
389 let Ok(files) = StepFiles::new(&self.temp, &id) else { return false };
390 let full = self.process_env(env, &files);
391 let script_path = action_dir.join(script);
392 // In a job container whose image runs the runner's Node, the action
393 // runs there, as on GitHub.
394 let in_container = self.container.as_ref().filter(|c| c.node).map(|c| c.path.clone()).and_then(|image_path| {
395 let inside = self.container_env(env, full.clone(), &image_path);
396 self.in_container(containers::CONTAINER_NODE, &[script_path.display().to_string()], &self.workspace, inside)
397 });
398 let command = match in_container {
399 Some(command) => command,
400 None => {
401 let node = node_program(using, |name| std::env::var(name).ok(), |path| path.is_file());
402 let mut command = Command::new(node);
403 command.arg(&script_path).current_dir(&self.workspace).env_clear().envs(full);
404 command
405 }
406 };
407 let mut commands = Commands {
408 debug: self.debug,
409 ..Commands::default()
410 };
411 let ended = process::run(command, Duration::from_secs(6 * 3600).min(self.deadline_left()), &mut self.log, &mut commands);
412 let ok = matches!(ended, Ok(Ended::Exited(0)));
413 match ended {
414 Ok(Ended::Exited(code)) if code != 0 => self.log.line(&format!("##[error]The action exited with code {code}.")),
415 Ok(Ended::TimedOut) => self.log.line("##[error]The action ran past its time limit and was stopped."),
416 _ => {}
417 }
418 let (outputs, state) = self.absorb(&files, &commands);
419 self.last_node_outputs = outputs;
420 self.last_node_state = state;
421 ok
422 }
423
424 fn log_header(&mut self, uses: &str, with: &BTreeMap<String, String>, env: &BTreeMap<String, String>) {
425 for line in super::uses_header(uses, with, env) {
426 self.log.line(&line);
427 }
428 }
429
430 fn deadline_left(&self) -> Duration {
431 self.remaining_time()
432 }
433
434 /// Runs a `uses:` step. Returns whether it succeeded, and its outputs.
435 #[allow(clippy::too_many_arguments)]
436 pub(crate) fn uses(
437 &mut self,
438 uses: &str,
439 with: &BTreeMap<String, String>,
440 env: &BTreeMap<String, String>,
441 frame: &Frame,
442 title: &str,
443 action_name: &str,
444 _timeout: Duration,
445 ) -> (bool, BTreeMap<String, String>) {
446 let uses = uses.trim();
447 let (name, git_ref) = uses.split_once('@').unwrap_or((uses, ""));
448 let lower = name.to_ascii_lowercase();
449 // The step opens as GitHub's do: `Run` and the action, its inputs
450 // and variables, folded. An action fetched from a repository lists
451 // its inputs as they are read, its defaults among them.
452 let fetched = !uses.starts_with("docker://") && !native(&lower, self.docker_hosted);
453 if !fetched {
454 self.log_header(uses, with, env);
455 }
456 if let Some(image) = uses.strip_prefix("docker://") {
457 // `with.args` and `with.entrypoint` are the container's; every
458 // input is also an `INPUT_` variable, as on GitHub.
459 let mut step_env = env.clone();
460 step_env.insert("GITHUB_ACTION".into(), action_name.to_owned());
461 for (input, value) in with {
462 step_env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone());
463 }
464 let run = DockerRun {
465 image: image.to_owned(),
466 entrypoint: with.get("entrypoint").filter(|e| !e.is_empty()).cloned(),
467 args: with.get("args").map(|a| containers::split_words(a)).unwrap_or_default(),
468 env: step_env,
469 };
470 let (ok, outputs, _) = self.run_docker(&run);
471 return (ok, outputs);
472 }
473 if lower == "docker/setup-buildx-action" && native(&lower, self.docker_hosted) {
474 return self.setup_buildx(with);
475 }
476 match lower.as_str() {
477 "actions/checkout" => return self.checkout(with),
478 "actions/upload-artifact" => return self.upload_artifact(with),
479 "actions/upload-artifact/merge" => return self.merge_artifacts(with),
480 "actions/download-artifact" => return self.download_artifact(with),
481 "actions/cache" => return self.cache(with, true, title),
482 "actions/cache/restore" => return self.cache(with, false, title),
483 "actions/cache/save" => return self.cache_save_now(with),
484 _ => {}
485 }
486 let Some(found) = self.resolve_action(uses) else {
487 self.log_header(uses, with, env);
488 return (false, BTreeMap::new());
489 };
490 let Action { dir, local, manifest: action, .. } = &found;
491
492 // Inputs: what the step gives, else the action's defaults.
493 let env_context = env.clone();
494 let contexts = self.contexts_for(frame, &env_context);
495 let inputs = self.action_inputs(action, with, &contexts, true);
496 self.log_header(uses, &inputs, env);
497
498 let runs = action.get("runs").cloned().unwrap_or(Value::Null);
499 let using = runs.get("using").map(expr::to_text).unwrap_or_default().to_ascii_lowercase();
500 let mut step_env = action_env(env, action_name, &found, git_ref);
501
502 if using.starts_with("node") {
503 for (input, value) in &inputs {
504 step_env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone());
505 }
506 let condition_of = |key: &str| runs.get(key).map(expr::to_text).unwrap_or_else(|| "always()".into());
507 // State an action saves, `STATE_<name>` for its later stages.
508 let mut state = BTreeMap::new();
509 if let Some(pre) = runs.get("pre").map(expr::to_text) {
510 if frame.action_path.is_some() {
511 // An action inside a composite action: its `pre` right
512 // before its `main`.
513 let run_pre = self.with_scope(&contexts, |scope| expr::condition(&condition_of("pre-if"), scope)).unwrap_or(true);
514 if run_pre {
515 if !self.run_node(dir, &pre, &step_env, &using) {
516 return (false, BTreeMap::new());
517 }
518 state = std::mem::take(&mut self.last_node_state);
519 }
520 } else if *local {
521 self.log.line(&format!("##[warning]`pre` execution is not supported for local action from '{uses}'"));
522 } else {
523 // Run before the job's first step (`pre_steps`).
524 state = self.pre_state.remove(action_name).unwrap_or_default();
525 }
526 }
527 let Some(main) = runs.get("main").map(expr::to_text) else {
528 self.log.line(&format!("##[error]`{uses}` has no `runs.main`."));
529 return (false, BTreeMap::new());
530 };
531 let mut main_env = step_env.clone();
532 for (name, value) in &state {
533 main_env.insert(format!("STATE_{name}"), value.clone());
534 }
535 let ok = self.run_node(dir, &main, &main_env, &using);
536 let outputs = std::mem::take(&mut self.last_node_outputs);
537 state.extend(std::mem::take(&mut self.last_node_state));
538 if let Some(post) = runs.get("post").map(expr::to_text) {
539 let mut post_env = step_env.clone();
540 for (name, value) in state {
541 post_env.insert(format!("STATE_{name}"), value);
542 }
543 self.posts.push(Post {
544 name: format!("Post {title}"),
545 condition: condition_of("post-if"),
546 env: post_env,
547 run: PostRun::Node { action_dir: dir.clone(), script: post, using: using.clone() },
548 });
549 }
550 return (ok, outputs);
551 }
552 if using == "composite" {
553 let mut inner = Frame {
554 steps: Map::new(),
555 inputs: Some(Value::Object(inputs.iter().map(|(k, v)| (k.clone(), json!(v))).collect())),
556 action_path: Some(dir.display().to_string()),
557 env: env.clone(),
558 };
559 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();
560 super::name_steps(&mut steps);
561 let was_failed = self.failed;
562 // A composite's steps see their own success, not the job's.
563 self.failed = false;
564 let mut ok = true;
565 for step in &steps {
566 if !self.step(&mut inner, step, 0, false, &Map::new()) {
567 ok = false;
568 }
569 }
570 let contexts = self.contexts_for(&inner, &inner.env.clone());
571 let mut outputs = BTreeMap::new();
572 if let Some(Value::Object(declared)) = action.get("outputs") {
573 for (name, spec) in declared {
574 if let Some(value) = spec.get("value") {
575 let value = self.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
576 outputs.insert(name.clone(), expr::to_text(&value));
577 }
578 }
579 }
580 self.failed = was_failed;
581 return (ok, outputs);
582 }
583 if using == "docker" {
584 return self.docker_action(uses, dir, &runs, &inputs, &step_env, frame, title);
585 }
586 self.log.line(&format!("##[error]`{uses}` runs with `{using}`, which g1t does not know."));
587 (false, BTreeMap::new())
588 }
589
590 /// A Docker action: its image built from its Dockerfile (or pulled,
591 /// for `docker://`), then run with its `args`, `entrypoint` and `env`,
592 /// its inputs as `INPUT_` variables, and `pre-entrypoint` and
593 /// `post-entrypoint` around it.
594 #[allow(clippy::too_many_arguments)]
595 fn docker_action(
596 &mut self,
597 uses: &str,
598 dir: &Path,
599 runs: &Value,
600 inputs: &BTreeMap<String, String>,
601 step_env: &BTreeMap<String, String>,
602 frame: &Frame,
603 title: &str,
604 ) -> (bool, BTreeMap<String, String>) {
605 let image = runs.get("image").map(expr::to_text).unwrap_or_default();
606 let image = if let Some(pulled) = image.strip_prefix("docker://") {
607 pulled.to_owned()
608 } else if image.is_empty() {
609 self.log.line(&format!("##[error]`{uses}` has no `runs.image`."));
610 return (false, BTreeMap::new());
611 } else {
612 match self.build_action_image(dir, &image, uses) {
613 Some(tag) => tag,
614 None => return (false, BTreeMap::new()),
615 }
616 };
617 // `args` and `env` read with the action's own inputs.
618 let mut env = step_env.clone();
619 for (input, value) in inputs {
620 env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone());
621 }
622 let mut scope_frame = frame.clone();
623 scope_frame.inputs = Some(Value::Object(inputs.iter().map(|(k, v)| (k.clone(), json!(v))).collect()));
624 let contexts = self.contexts_for(&scope_frame, &env);
625 if let Some(Value::Object(own)) = runs.get("env") {
626 for (name, value) in own {
627 let value = self.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null);
628 env.insert(name.clone(), expr::to_text(&value));
629 }
630 }
631 let args: Vec<String> = match runs.get("args") {
632 Some(Value::Array(items)) => items
633 .iter()
634 .map(|item| {
635 let value = self.with_scope(&contexts, |scope| expr::interpolate_value(item, scope)).unwrap_or(Value::Null);
636 expr::to_text(&value)
637 })
638 .collect(),
639 _ => Vec::new(),
640 };
641 let entry = |key: &str| runs.get(key).map(expr::to_text).filter(|e| !e.is_empty());
642 if let Some(pre) = entry("pre-entrypoint") {
643 let run = DockerRun { image: image.clone(), entrypoint: Some(pre), args: Vec::new(), env: env.clone() };
644 if !self.run_docker(&run).0 {
645 return (false, BTreeMap::new());
646 }
647 }
648 let run = DockerRun { image: image.clone(), entrypoint: entry("entrypoint"), args, env: env.clone() };
649 let (ok, outputs, state) = self.run_docker(&run);
650 if let Some(post) = entry("post-entrypoint") {
651 let mut post_env = env;
652 for (name, value) in state {
653 post_env.insert(format!("STATE_{name}"), value);
654 }
655 self.posts.push(Post {
656 name: format!("Post {title}"),
657 condition: runs.get("post-if").map(expr::to_text).unwrap_or_else(|| "always()".into()),
658 env: BTreeMap::new(),
659 run: PostRun::Docker(DockerRun { image, entrypoint: Some(post), args: Vec::new(), env: post_env }),
660 });
661 }
662 (ok, outputs)
663 }
664}
665
666/// An action, read from its action.yml.
667pub(crate) struct Action {
668 pub(crate) dir: PathBuf,
669 /// `owner/repo`, or empty for one in the repository.
670 pub(crate) repository: String,
671 pub(crate) local: bool,
672 pub(crate) manifest: Value,
673}
674
675/// An action's `pre`, run before the job's first step.
676pub(crate) struct PreStep {
677 /// Its step's `GITHUB_ACTION`, by which the step finds the state it saved.
678 pub(crate) key: String,
679 /// `pre-if`, `always()` when it has none.
680 pub(crate) condition: String,
681 pub(crate) action_dir: PathBuf,
682 pub(crate) script: String,
683 pub(crate) using: String,
684 /// The `env` context its condition reads.
685 pub(crate) context_env: BTreeMap<String, String>,
686 /// What its process is given: the step's variables and inputs.
687 pub(crate) env: BTreeMap<String, String>,
688}
689
690impl Job {
691 /// Finds `uses` (fetching it when it is another repository's) and reads
692 /// its action.yml. A problem is told in the log.
693 fn resolve_action(&mut self, uses: &str) -> Option<Action> {
694 let (name, git_ref) = uses.split_once('@').unwrap_or((uses, ""));
695 let source = if let Some(local) = name.strip_prefix("./") {
696 // A repository moved from GitHub renamed `.github` to `.g1t`, but
697 // its workflows still say `./.github/actions/…`.
698 let mut dir = self.workspace.join(local);
699 if let Some(rest) = local.strip_prefix(".github/")
700 && !dir.exists()
701 {
702 dir = self.workspace.join(".g1t").join(rest);
703 }
704 Source::Local(dir)
705 } else {
706 let mut parts = name.splitn(3, '/');
707 let (Some(owner), Some(repo)) = (parts.next(), parts.next()) else {
708 self.log.line(&format!("##[error]`{uses}` is not an action: use owner/repo@ref, owner/repo/path@ref, or ./path."));
709 return None;
710 };
711 if git_ref.is_empty() {
712 self.log.line(&format!("##[error]`{uses}` needs a version, such as @v4."));
713 return None;
714 }
715 Source::GitHub {
716 owner: owner.to_owned(),
717 repo: repo.to_owned(),
718 path: parts.next().unwrap_or_default().to_owned(),
719 git_ref: git_ref.to_owned(),
720 }
721 };
722 let (dir, repository) = match &source {
723 Source::Local(dir) => (dir.clone(), String::new()),
724 Source::GitHub { owner, repo, path, git_ref } => {
725 let root = self.fetch_remote_action(owner, repo, git_ref)?;
726 (if path.is_empty() { root } else { root.join(path) }, format!("{owner}/{repo}"))
727 }
728 };
729 let Some(manifest) = ["action.yml", "action.yaml"].iter().map(|f| dir.join(f)).find(|p| p.exists()) else {
730 self.log.line(&format!("##[error]`{uses}` has no action.yml."));
731 return None;
732 };
733 let Some(yaml) = std::fs::read_to_string(&manifest).ok().and_then(|text| serde_yaml::from_str::<serde_yaml::Value>(&text).ok()) else {
734 self.log.line(&format!("##[error]`{uses}`: its action.yml does not read."));
735 return None;
736 };
737 Some(Action { dir, repository, local: matches!(source, Source::Local(_)), manifest: yaml_to_json(&yaml) })
738 }
739
740 /// An action's inputs: what the step gives, else the action's defaults,
741 /// read with `contexts`. With `warn`, inputs the action does not declare
742 /// are warned of, as GitHub's runner does.
743 fn action_inputs(&mut self, action: &Value, with: &BTreeMap<String, String>, contexts: &Map<String, Value>, warn: bool) -> BTreeMap<String, String> {
744 let mut inputs: BTreeMap<String, String> = BTreeMap::new();
745 let mut declared_names = Vec::new();
746 if let Some(Value::Object(declared)) = action.get("inputs") {
747 for (input, spec) in declared {
748 declared_names.push(input.clone());
749 let given = with.iter().find(|(k, _)| k.eq_ignore_ascii_case(input)).map(|(_, v)| v.clone());
750 let value = match given {
751 Some(value) => value,
752 None => match spec.get("default") {
753 Some(default) => {
754 let default = self.with_scope(contexts, |scope| expr::interpolate_value(default, scope)).unwrap_or(Value::Null);
755 expr::to_text(&default)
756 }
757 None => String::new(),
758 },
759 };
760 inputs.insert(input.clone(), value);
761 }
762 }
763 for (key, value) in with {
764 if !inputs.keys().any(|k| k.eq_ignore_ascii_case(key)) {
765 inputs.insert(key.clone(), value.clone());
766 }
767 }
768 let docker = action["runs"]["using"].as_str().is_some_and(|u| u.eq_ignore_ascii_case("docker"));
769 if warn && let Some(warning) = unexpected_inputs(&declared_names, &with.keys().cloned().collect::<Vec<_>>(), docker) {
770 self.log.line(&format!("##[warning]{warning}"));
771 }
772 inputs
773 }
774
775 /// The `pre`s of the job's steps, in step order, each with its step's
776 /// index: those of JavaScript actions from other repositories, fetched
777 /// now, as GitHub's runner fetches every action while it sets up the
778 /// job. An action in the repository is not there yet, so its `pre` is
779 /// not run, as on GitHub.
780 pub(crate) fn pre_steps(&mut self, steps: &[Map<String, Value>]) -> Vec<(usize, PreStep)> {
781 let frame = Frame::default();
782 let mut pres = Vec::new();
783 for (index, step) in steps.iter().enumerate() {
784 let Some(uses) = step.get("uses").map(|u| expr::to_text(u).trim().to_owned()) else { continue };
785 // Only another repository's action, which `prepare_actions` has
786 // already downloaded.
787 if remote_action(&uses, self.docker_hosted).is_none() {
788 continue;
789 }
790 let Some(found) = self.resolve_action(&uses) else { continue };
791 let runs = found.manifest.get("runs").cloned().unwrap_or(Value::Null);
792 let using = runs.get("using").map(expr::to_text).unwrap_or_default().to_ascii_lowercase();
793 let Some(script) = runs.get("pre").map(expr::to_text).filter(|_| using.starts_with("node")) else { continue };
794 let env_before = self.env_context(&frame);
795 let contexts = self.contexts_for(&frame, &env_before);
796 let with = self.step_with(step, &contexts);
797 let context_env = self.step_env(step, &contexts, env_before);
798 let contexts = self.contexts_for(&frame, &context_env);
799 let inputs = self.action_inputs(&found.manifest, &with, &contexts, false);
800 let key = step.get(super::ACTION_NAME).map(expr::to_text).unwrap_or_default();
801 let git_ref = uses.split_once('@').map_or("", |(_, r)| r);
802 let mut env = action_env(&context_env, &key, &found, git_ref);
803 for (input, value) in &inputs {
804 env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone());
805 }
806 let condition = runs.get("pre-if").map(expr::to_text).unwrap_or_else(|| "always()".into());
807 pres.push((index, PreStep { key, condition, action_dir: found.dir, script, using, context_env, env }));
808 }
809 pres
810 }
811
812 /// Whether a `pre`'s `pre-if` holds, read against the job's status.
813 pub(crate) fn pre_runs(&self, pre: &PreStep) -> bool {
814 let contexts = self.contexts_for(&Frame::default(), &pre.context_env);
815 self.with_scope(&contexts, |scope| expr::condition(&pre.condition, scope)).unwrap_or(true)
816 }
817
818 /// Runs a `pre`, keeping the state it saves for its step's main and post.
819 pub(crate) fn run_pre(&mut self, pre: &PreStep) -> bool {
820 let ok = self.run_node(&pre.action_dir, &pre.script, &pre.env, &pre.using);
821 let state = std::mem::take(&mut self.last_node_state);
822 self.last_node_outputs.clear();
823 self.pre_state.insert(pre.key.clone(), state);
824 ok
825 }
826}
827
828/// The variables a step running an action gets over its own: which
829/// action it is and where.
830fn action_env(env: &BTreeMap<String, String>, action_name: &str, action: &Action, git_ref: &str) -> BTreeMap<String, String> {
831 let mut step_env = env.clone();
832 step_env.insert("GITHUB_ACTION".into(), action_name.to_owned());
833 step_env.insert("GITHUB_ACTION_REPOSITORY".into(), action.repository.clone());
834 step_env.insert("GITHUB_ACTION_REF".into(), git_ref.to_owned());
835 step_env.insert("GITHUB_ACTION_PATH".into(), action.dir.display().to_string());
836 step_env
837}
838
839/// GitHub's warning for inputs a step gives that its action does not
840/// declare (a Docker action also takes `entryPoint` and `args`), if any.
841fn unexpected_inputs(declared: &[String], given: &[String], docker: bool) -> Option<String> {
842 let mut valid: Vec<String> = declared.to_vec();
843 if docker {
844 valid.extend(["entryPoint".to_owned(), "args".to_owned()]);
845 }
846 let unexpected: Vec<&str> = given.iter().filter(|g| !valid.iter().any(|v| v.eq_ignore_ascii_case(g))).map(String::as_str).collect();
847 if unexpected.is_empty() {
848 return None;
849 }
850 Some(format!("Unexpected input(s) '{}', valid inputs are ['{}']", unexpected.join("', '"), valid.join("', '")))
851}
852
853/// The Node an action's `runs.using` asks for: for `node20` (or any
854/// `nodeNN`), the binary `G1T_NODE20` names or `/opt/node20/bin/node`,
855/// when there is one; otherwise, and for anything else, the `node` on
856/// `PATH`, the runner's own (Node 24). Nothing is logged either way.
857pub(crate) fn node_program(using: &str, var: impl Fn(&str) -> Option<String>, exists: impl Fn(&Path) -> bool) -> String {
858 let using = using.trim().to_ascii_lowercase();
859 let versioned = using.strip_prefix("node").is_some_and(|v| !v.is_empty() && v.chars().all(|c| c.is_ascii_digit()));
860 if versioned {
861 let named = var(&format!("G1T_{}", using.to_ascii_uppercase())).filter(|p| !p.is_empty() && exists(Path::new(p)));
862 if let Some(path) = named {
863 return path;
864 }
865 let standard = format!("/opt/{using}/bin/node");
866 if exists(Path::new(&standard)) {
867 return standard;
868 }
869 }
870 "node".into()
871}
872
873#[cfg(test)]
874mod tests {
875 use super::*;
876
877 #[test]
878 fn the_actions_fetched_before_the_first_step_are_other_repositories() {
879 let found = |uses: &str| remote_action(uses, true);
880 assert_eq!(found("actions/setup-node@v4"), Some(("actions".into(), "setup-node".into(), "v4".into())));
881 assert_eq!(found(" github/codeql-action/init@v3 "), Some(("github".into(), "codeql-action".into(), "v3".into())));
882 // Done by the runner itself, local, an image, or no version.
883 assert_eq!(found("actions/checkout@v4"), None);
884 assert_eq!(found("Actions/Cache/Restore@v4"), None);
885 assert_eq!(found("docker/setup-buildx-action@v3"), None);
886 assert!(remote_action("docker/setup-buildx-action@v3", false).is_some());
887 assert_eq!(found("./.g1t/actions/setup"), None);
888 assert_eq!(found("docker://alpine:3"), None);
889 assert_eq!(found("actions/setup-node"), None);
890 assert_eq!(found("setup-node@v4"), None);
891 }
892
893 #[test]
894 fn unexpected_inputs_are_named_with_the_valid_ones() {
895 let declared = vec!["token".to_owned(), "path".to_owned()];
896 assert_eq!(unexpected_inputs(&declared, &["Token".into()], false), None);
897 assert_eq!(
898 unexpected_inputs(&declared, &["token".into(), "foo".into(), "bar".into()], false).as_deref(),
899 Some("Unexpected input(s) 'foo', 'bar', valid inputs are ['token', 'path']")
900 );
901 assert_eq!(unexpected_inputs(&[], &["x".into()], false).as_deref(), Some("Unexpected input(s) 'x', valid inputs are ['']"));
902 // A Docker action takes `entrypoint` and `args` too.
903 assert_eq!(unexpected_inputs(&declared, &["entrypoint".into(), "args".into()], true), None);
904 assert!(unexpected_inputs(&declared, &["args".into()], false).is_some());
905 }
906
907 #[test]
908 fn node20_runs_with_a_node20_where_there_is_one() {
909 let none = |_: &str| None;
910 assert_eq!(node_program("node20", none, |_| false), "node");
911 assert_eq!(node_program("node20", none, |p| p == Path::new("/opt/node20/bin/node")), "/opt/node20/bin/node");
912 let named = |name: &str| (name == "G1T_NODE20").then(|| "/usr/local/n20/bin/node".to_owned());
913 assert_eq!(node_program("Node20", named, |_| true), "/usr/local/n20/bin/node");
914 // A named Node that is not there is passed over.
915 assert_eq!(node_program("node20", named, |p| p == Path::new("/opt/node20/bin/node")), "/opt/node20/bin/node");
916 assert_eq!(node_program("node24", none, |_| false), "node");
917 assert_eq!(node_program("composite", none, |_| true), "node");
918 assert_eq!(node_program("node", none, |_| true), "node");
919 }
920}