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