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