| 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 | |
| 9 | use std::collections::BTreeMap; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::process::Command; |
| 12 | use std::time::Duration; |
| 13 | |
| 14 | use base64::Engine; |
| 15 | use base64::engine::general_purpose::STANDARD; |
| 16 | use g1t_actions::expr; |
| 17 | use g1t_actions::workflow::yaml_to_json; |
| 18 | use serde_json::{Map, Value, json}; |
| 19 | |
| 20 | use super::containers::{self, DockerRun}; |
| 21 | use super::files::StepFiles; |
| 22 | use super::process::{self, Commands, Ended}; |
| 23 | use super::{Frame, Job, Post, PostRun}; |
| 24 | |
| 25 | const ACTIONS_DIR: &str = "/home/runner/_actions"; |
| 26 | |
| 27 | /// Where an action comes from. |
| 28 | enum 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 | |
| 35 | fn safe(part: &str) -> bool { |
| 36 | !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/')) && !part.contains("..") |
| 37 | } |
| 38 | |
| 39 | fn 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. |
| 45 | fn 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. |
| 61 | fn 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 | |
| 75 | impl Job { |
| 76 | /// Runs a git command, logging it; the credential header is never logged. |
| 77 | fn git(&mut self, dir: &Path, args: &[&str], auth: Option<&str>) -> bool { |
| 78 | let shown: Vec<&str> = args.to_vec(); |
| 79 | self.log.line(&format!("[command]git {}", shown.join(" "))); |
| 80 | let mut command = Command::new("git"); |
| 81 | command.current_dir(dir); |
| 82 | if let Some(header) = auth { |
| 83 | command.args(["-c", &format!("http.extraheader={header}")]); |
| 84 | } |
| 85 | command.args(args).env("GIT_TERMINAL_PROMPT", "0"); |
| 86 | let mut commands = Commands::default(); |
| 87 | matches!(process::run(command, Duration::from_secs(600).min(self.remaining_time()), &mut self.log, &mut commands), Ok(Ended::Exited(0))) |
| 88 | } |
| 89 | |
| 90 | /// A fetch, tried again after a short wait when it fails: a transfer |
| 91 | /// cut short on the way ("transfer closed with N bytes remaining") is |
| 92 | /// over by the next try. Three tries in all, as actions/checkout does. |
| 93 | fn fetch_retrying(&mut self, dir: &Path, args: &[&str], auth: Option<&str>) -> bool { |
| 94 | for (attempt, wait) in [0u64, 2, 5].into_iter().enumerate() { |
| 95 | if attempt > 0 { |
| 96 | self.log.line(&format!("The fetch failed; trying again in {wait} s ({} of 3).", attempt + 1)); |
| 97 | std::thread::sleep(Duration::from_secs(wait)); |
| 98 | } |
| 99 | if self.git(dir, args, auth) { |
| 100 | return true; |
| 101 | } |
| 102 | } |
| 103 | false |
| 104 | } |
| 105 | |
| 106 | /// `actions/checkout`, against g1t. |
| 107 | fn checkout(&mut self, with: &BTreeMap<String, String>) -> (bool, BTreeMap<String, String>) { |
| 108 | let checkout = self.spec["checkout"].clone(); |
| 109 | let own = checkout["repository"].as_str().unwrap_or_default().to_owned(); |
| 110 | let server = self.contexts["github"]["server_url"].as_str().unwrap_or("https://g1t.sh").to_owned(); |
| 111 | let repository = with.get("repository").filter(|r| !r.is_empty()).cloned().unwrap_or(own.clone()); |
| 112 | let same = repository.eq_ignore_ascii_case(&own); |
| 113 | let token = with.get("token").filter(|t| !t.is_empty()).cloned().or_else(|| checkout["token"].as_str().map(str::to_owned)).unwrap_or_default(); |
| 114 | let url = if same { checkout["url"].as_str().unwrap_or_default().to_owned() } else { format!("{server}/{repository}.git") }; |
| 115 | let path = with.get("path").filter(|p| !p.is_empty()).map_or(self.workspace.clone(), |p| self.workspace.join(p)); |
| 116 | let depth: u32 = with.get("fetch-depth").and_then(|d| d.parse().ok()).unwrap_or(1); |
| 117 | let wanted_ref = with.get("ref").filter(|r| !r.is_empty()).cloned(); |
| 118 | let auth = (!token.is_empty()).then(|| format!("AUTHORIZATION: basic {}", STANDARD.encode(format!("x-access-token:{token}")))); |
| 119 | |
| 120 | self.log.line(&format!("Checking out {repository} into {}", path.display())); |
| 121 | if path.exists() { |
| 122 | let _ = std::fs::remove_dir_all(&path); |
| 123 | } |
| 124 | if let Err(error) = std::fs::create_dir_all(&path) { |
| 125 | self.log.line(&format!("##[error]Could not make {}: {error}", path.display())); |
| 126 | return (false, BTreeMap::new()); |
| 127 | } |
| 128 | let _ = Command::new("git").args(["config", "--global", "--add", "safe.directory", "*"]).status(); |
| 129 | if !self.git(&path, &["init", "--quiet"], None) || !self.git(&path, &["remote", "add", "origin", &url], None) { |
| 130 | return (false, BTreeMap::new()); |
| 131 | } |
| 132 | |
| 133 | // What to fetch, and which commit to end up on. |
| 134 | let run_ref = checkout["ref"].as_str().unwrap_or_default().to_owned(); |
| 135 | let run_sha = checkout["sha"].as_str().unwrap_or_default().to_owned(); |
| 136 | let is_sha = |r: &str| r.len() == 40 && r.chars().all(|c| c.is_ascii_hexdigit()); |
| 137 | let (fetch, sha, branch): (String, Option<String>, Option<String>) = match &wanted_ref { |
| 138 | Some(r) if is_sha(r) => ("HEAD".into(), Some(r.clone()), None), |
| 139 | Some(r) if r.starts_with("refs/") => (r.clone(), None, r.strip_prefix("refs/heads/").map(str::to_owned)), |
| 140 | Some(r) => (r.clone(), None, Some(r.clone())), |
| 141 | // A pull request's merge ref, or no ref at all (a deployment of |
| 142 | // a bare commit): the commit itself. |
| 143 | None if same && (run_ref.starts_with("refs/pull/") || run_ref.is_empty()) => ("HEAD".into(), Some(run_sha.clone()), None), |
| 144 | None if same => (run_ref.clone(), Some(run_sha.clone()), run_ref.strip_prefix("refs/heads/").map(str::to_owned)), |
| 145 | None => ("HEAD".into(), None, None), |
| 146 | }; |
| 147 | let depth_arg = format!("--depth={depth}"); |
| 148 | let mut args = vec!["fetch", "--no-tags", "--prune", "--quiet"]; |
| 149 | if depth > 0 { |
| 150 | args.push(&depth_arg); |
| 151 | } |
| 152 | if with.get("fetch-tags").is_some_and(|t| t == "true") { |
| 153 | args.retain(|a| *a != "--no-tags"); |
| 154 | } |
| 155 | args.push("origin"); |
| 156 | args.push(&fetch); |
| 157 | if !self.fetch_retrying(&path, &args, auth.as_deref()) { |
| 158 | self.log.line(&format!("##[error]Could not fetch {fetch} from {repository}.")); |
| 159 | return (false, BTreeMap::new()); |
| 160 | } |
| 161 | let target = sha.clone().unwrap_or_else(|| "FETCH_HEAD".into()); |
| 162 | // The commit may be further back than a shallow fetch reaches: the |
| 163 | // branch moved on after the run began, say. Ask for the commit |
| 164 | // itself, and failing that the whole history; a plain fetch never |
| 165 | // reaches past a shallow boundary. |
| 166 | let has = |target: &str| Command::new("git").current_dir(&path).args(["cat-file", "-e", &format!("{target}^{{commit}}")]).status().is_ok_and(|s| s.success()); |
| 167 | if !has(&target) { |
| 168 | let by_sha = sha.as_deref().is_some_and(|sha| { |
| 169 | let mut args = vec!["fetch", "--no-tags", "--quiet"]; |
| 170 | if depth > 0 { |
| 171 | args.push(&depth_arg); |
| 172 | } |
| 173 | args.extend(["origin", sha]); |
| 174 | self.git(&path, &args, auth.as_deref()) && has(sha) |
| 175 | }); |
| 176 | let shallow = path.join(".git").join("shallow").exists(); |
| 177 | let deepen: &[&str] = if shallow { &["fetch", "--no-tags", "--quiet", "--unshallow", "origin"] } else { &["fetch", "--no-tags", "--quiet", "origin"] }; |
| 178 | if !by_sha && !self.fetch_retrying(&path, deepen, auth.as_deref()) { |
| 179 | return (false, BTreeMap::new()); |
| 180 | } |
| 181 | } |
| 182 | let checked_out = match &branch { |
| 183 | Some(branch) => self.git(&path, &["checkout", "--quiet", "--force", "-B", branch, &target], None), |
| 184 | None => self.git(&path, &["checkout", "--quiet", "--force", "--detach", &target], None), |
| 185 | }; |
| 186 | if !checked_out { |
| 187 | return (false, BTreeMap::new()); |
| 188 | } |
| 189 | if with.get("persist-credentials").is_none_or(|p| p != "false") |
| 190 | && let Some(header) = &auth |
| 191 | { |
| 192 | let key = format!("http.{server}/.extraheader"); |
| 193 | let _ = Command::new("git").current_dir(&path).args(["config", "--local", &key, header]).status(); |
| 194 | } |
| 195 | if let Some(submodules) = with.get("submodules").filter(|s| *s == "true" || *s == "recursive") { |
| 196 | let mut args = vec!["submodule", "update", "--init", "--quiet"]; |
| 197 | if submodules == "recursive" { |
| 198 | args.push("--recursive"); |
| 199 | } |
| 200 | if !self.git(&path, &args, auth.as_deref()) { |
| 201 | self.log.line("##[warning]Submodules could not all be checked out; only those hosted on g1t can be."); |
| 202 | } |
| 203 | } |
| 204 | if with.get("lfs").is_some_and(|l| l == "true") { |
| 205 | self.log.line("##[warning]Git LFS files are not fetched on g1t yet."); |
| 206 | } |
| 207 | let commit = Command::new("git").current_dir(&path).args(["rev-parse", "HEAD"]).output().ok().map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()).unwrap_or_default(); |
| 208 | self.log.line(&format!("Checked out {commit}")); |
| 209 | let mut outputs = BTreeMap::new(); |
| 210 | outputs.insert("ref".into(), wanted_ref.unwrap_or(run_ref)); |
| 211 | outputs.insert("commit".into(), commit); |
| 212 | (true, outputs) |
| 213 | } |
| 214 | |
| 215 | /// Fetches another repository's action, once per job: from g1t when |
| 216 | /// g1t has the repository and this one may use it, otherwise from |
| 217 | /// GitHub. A private repository on g1t that may not be used here fails |
| 218 | /// the step, saying why, rather than fetching something else by its |
| 219 | /// name. |
| 220 | fn fetch_remote_action(&mut self, owner: &str, repo: &str, git_ref: &str) -> Option<PathBuf> { |
| 221 | let on_g1t = super::paths::under_home(ACTIONS_DIR).join("_g1t").join(owner).join(repo).join(git_ref); |
| 222 | let on_github = super::paths::under_home(ACTIONS_DIR).join(owner).join(repo).join(git_ref); |
| 223 | for dir in [&on_g1t, &on_github] { |
| 224 | if dir.join(".g1t-fetched").exists() { |
| 225 | return Some(dir.clone()); |
| 226 | } |
| 227 | } |
| 228 | if !(safe(owner) && safe(repo) && safe(git_ref)) { |
| 229 | self.log.line(&format!("##[error]`{owner}/{repo}@{git_ref}` is not a name g1t can fetch.")); |
| 230 | return None; |
| 231 | } |
| 232 | match self.log.api.action(&format!("{owner}/{repo}"), git_ref) { |
| 233 | Ok(found) if found["source"] == "g1t" => self.fetch_g1t_action(&on_g1t, owner, repo, git_ref, &found), |
| 234 | Ok(found) => { |
| 235 | if let Some(note) = found["note"].as_str() { |
| 236 | self.log.line(&format!("##[warning]{note}")); |
| 237 | } |
| 238 | let sha = found["sha"].as_str().filter(|sha| is_sha(sha)).map(str::to_owned); |
| 239 | if let Some(sha) = &sha |
| 240 | && found["archive"] == true |
| 241 | && let Some(dir) = self.fetch_archived_action(owner, repo, git_ref, sha) |
| 242 | { |
| 243 | return Some(dir); |
| 244 | } |
| 245 | self.fetch_action(owner, repo, git_ref, sha.as_deref()) |
| 246 | } |
| 247 | Err((true, why)) => { |
| 248 | self.log.line(&format!("##[error]{why}")); |
| 249 | None |
| 250 | } |
| 251 | Err((false, why)) => { |
| 252 | self.log.line(&format!("##[warning]g1t could not say where {owner}/{repo} is ({why}); fetching it from GitHub.")); |
| 253 | self.fetch_action(owner, repo, git_ref, None) |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// Fetches an action from a repository on g1t, at its ref, with the |
| 259 | /// read-only token g1t gave for it when it is private. |
| 260 | fn fetch_g1t_action(&mut self, dir: &Path, owner: &str, repo: &str, git_ref: &str, found: &Value) -> Option<PathBuf> { |
| 261 | let url = found["url"].as_str().unwrap_or_default().to_owned(); |
| 262 | let token = found["token"].as_str().filter(|token| !token.is_empty()).map(str::to_owned); |
| 263 | if let Some(token) = &token { |
| 264 | self.log.add_mask(token); |
| 265 | } |
| 266 | let auth = token.map(|token| format!("AUTHORIZATION: basic {}", STANDARD.encode(format!("x-access-token:{token}")))); |
| 267 | self.log.line(&format!("Download action repository '{owner}/{repo}@{git_ref}' from g1t")); |
| 268 | let _ = std::fs::remove_dir_all(dir); |
| 269 | if std::fs::create_dir_all(dir).is_err() || !self.git(dir, &["init", "--quiet"], None) || !self.git(dir, &["remote", "add", "origin", &url], None) { |
| 270 | return None; |
| 271 | } |
| 272 | // A branch or tag at its tip; a commit may need the history. |
| 273 | let shallow = self.fetch_retrying(dir, &["fetch", "--depth=1", "--no-tags", "--quiet", "origin", git_ref], auth.as_deref()); |
| 274 | let checked_out = if shallow { |
| 275 | self.git(dir, &["checkout", "--quiet", "--force", "--detach", "FETCH_HEAD"], None) |
| 276 | } else { |
| 277 | self.fetch_retrying(dir, &["fetch", "--quiet", "--tags", "origin", "+refs/heads/*:refs/remotes/origin/*"], auth.as_deref()) |
| 278 | && self.git(dir, &["checkout", "--quiet", "--force", "--detach", git_ref], None) |
| 279 | }; |
| 280 | if !checked_out { |
| 281 | self.log.line(&format!("##[error]Could not fetch {owner}/{repo}@{git_ref} from g1t: is {git_ref} a branch, tag or commit there?")); |
| 282 | let _ = std::fs::remove_dir_all(dir); |
| 283 | return None; |
| 284 | } |
| 285 | let _ = std::fs::write(dir.join(".g1t-fetched"), ""); |
| 286 | Some(dir.to_path_buf()) |
| 287 | } |
| 288 | |
| 289 | /// Downloads a GitHub action's archive that g1t keeps, at the commit |
| 290 | /// g1t resolved its ref to. None when it could not, and the job fetches |
| 291 | /// it from GitHub instead. |
| 292 | fn fetch_archived_action(&mut self, owner: &str, repo: &str, git_ref: &str, sha: &str) -> Option<PathBuf> { |
| 293 | let dir = super::paths::under_home(ACTIONS_DIR).join(owner).join(repo).join(git_ref); |
| 294 | self.log.line(&format!("Download action repository '{owner}/{repo}@{git_ref}' (SHA:{sha}) from g1t")); |
| 295 | let archive = self.temp.join(format!("action{}.tar.gz", super::rand_id())); |
| 296 | let downloaded = self.log.api.action_archive(&format!("{owner}/{repo}"), sha, &archive); |
| 297 | let unpacked = match downloaded { |
| 298 | Ok(_) => { |
| 299 | let _ = std::fs::remove_dir_all(&dir); |
| 300 | let _ = std::fs::create_dir_all(&dir); |
| 301 | let mut command = Command::new("tar"); |
| 302 | command.arg("-xzf").arg(&archive).arg("-C").arg(&dir).arg("--strip-components=1"); |
| 303 | let mut commands = Commands::default(); |
| 304 | matches!(process::run(command, Duration::from_secs(300).min(self.remaining_time()), &mut self.log, &mut commands), Ok(Ended::Exited(0))) |
| 305 | } |
| 306 | Err(why) => { |
| 307 | self.log.line(&format!("g1t could not send it ({why}); fetching it from GitHub.")); |
| 308 | false |
| 309 | } |
| 310 | }; |
| 311 | let _ = std::fs::remove_file(&archive); |
| 312 | if !unpacked { |
| 313 | let _ = std::fs::remove_dir_all(&dir); |
| 314 | return None; |
| 315 | } |
| 316 | let _ = std::fs::write(dir.join(".g1t-fetched"), ""); |
| 317 | Some(dir) |
| 318 | } |
| 319 | |
| 320 | /// Fetches an action from GitHub, once per job: at `sha` when g1t |
| 321 | /// resolved its ref to one, so it is the commit g1t named. |
| 322 | fn fetch_action(&mut self, owner: &str, repo: &str, git_ref: &str, sha: Option<&str>) -> Option<PathBuf> { |
| 323 | let dir = super::paths::under_home(ACTIONS_DIR).join(owner).join(repo).join(git_ref); |
| 324 | if dir.join(".g1t-fetched").exists() { |
| 325 | return Some(dir); |
| 326 | } |
| 327 | if !(safe(owner) && safe(repo) && safe(git_ref)) { |
| 328 | self.log.line(&format!("##[error]`{owner}/{repo}@{git_ref}` is not a name g1t can fetch.")); |
| 329 | return None; |
| 330 | } |
| 331 | match sha { |
| 332 | Some(sha) => self.log.line(&format!("Download action repository '{owner}/{repo}@{git_ref}' (SHA:{sha})")), |
| 333 | None => self.log.line(&format!("Download action repository '{owner}/{repo}@{git_ref}'")), |
| 334 | } |
| 335 | let _ = std::fs::create_dir_all(&dir); |
| 336 | let url = format!("https://codeload.github.com/{owner}/{repo}/tar.gz/{}", sha.unwrap_or(git_ref)); |
| 337 | let script = format!("set -o pipefail; curl -fsSL --retry 3 '{url}' | tar -xz -C '{}' --strip-components=1", dir.display()); |
| 338 | let mut command = Command::new("bash"); |
| 339 | command.args(["-c", &script]); |
| 340 | let mut commands = Commands::default(); |
| 341 | match process::run(command, Duration::from_secs(300).min(self.remaining_time()), &mut self.log, &mut commands) { |
| 342 | Ok(Ended::Exited(0)) => { |
| 343 | let _ = std::fs::write(dir.join(".g1t-fetched"), ""); |
| 344 | Some(dir) |
| 345 | } |
| 346 | _ => { |
| 347 | self.log.line(&format!("##[error]Could not download {owner}/{repo}@{git_ref} from GitHub.")); |
| 348 | let _ = std::fs::remove_dir_all(&dir); |
| 349 | None |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | /// Downloads every action the job's steps fetch from other |
| 355 | /// repositories, before the first step runs, as GitHub's runner does in |
| 356 | /// "Set up job". False when one could not be: the job fails before |
| 357 | /// anything runs. Actions a composite action uses are fetched as it |
| 358 | /// runs. |
| 359 | pub(crate) fn prepare_actions(&mut self, steps: &[Map<String, Value>]) -> bool { |
| 360 | let mut wanted: Vec<(String, String, String)> = Vec::new(); |
| 361 | for step in steps { |
| 362 | if let Some(found) = step.get("uses").and_then(Value::as_str).and_then(|uses| remote_action(uses, self.docker_hosted)) |
| 363 | && !wanted.contains(&found) |
| 364 | { |
| 365 | wanted.push(found); |
| 366 | } |
| 367 | } |
| 368 | if wanted.is_empty() { |
| 369 | return true; |
| 370 | } |
| 371 | self.log.line("Prepare all required actions"); |
| 372 | let mut ready = true; |
| 373 | for (owner, repo, git_ref) in &wanted { |
| 374 | if self.fetch_remote_action(owner, repo, git_ref).is_none() { |
| 375 | ready = false; |
| 376 | } |
| 377 | } |
| 378 | if !ready { |
| 379 | self.log.line("##[error]Not every action this job uses could be downloaded, so no step was run."); |
| 380 | } |
| 381 | ready |
| 382 | } |
| 383 | |
| 384 | /// Runs a JavaScript file of an action with Node. |
| 385 | pub(crate) fn run_node(&mut self, action_dir: &Path, script: &str, env: &BTreeMap<String, String>) -> bool { |
| 386 | let id = format!("node{}", super::rand_id()); |
| 387 | let Ok(files) = StepFiles::new(&self.temp, &id) else { return false }; |
| 388 | let full = self.process_env(env, &files); |
| 389 | let script_path = action_dir.join(script); |
| 390 | // In a job container whose image runs the runner's Node, the action |
| 391 | // runs there, as on GitHub. |
| 392 | let in_container = self.container.as_ref().filter(|c| c.node).map(|c| c.path.clone()).and_then(|image_path| { |
| 393 | let inside = self.container_env(env, full.clone(), &image_path); |
| 394 | self.in_container(containers::CONTAINER_NODE, &[script_path.display().to_string()], &self.workspace, inside) |
| 395 | }); |
| 396 | let command = match in_container { |
| 397 | Some(command) => command, |
| 398 | None => { |
| 399 | let mut command = Command::new("node"); |
| 400 | command.arg(&script_path).current_dir(&self.workspace).env_clear().envs(full); |
| 401 | command |
| 402 | } |
| 403 | }; |
| 404 | let mut commands = Commands { |
| 405 | debug: false, |
| 406 | ..Commands::default() |
| 407 | }; |
| 408 | let ended = process::run(command, Duration::from_secs(6 * 3600).min(self.deadline_left()), &mut self.log, &mut commands); |
| 409 | let ok = matches!(ended, Ok(Ended::Exited(0))); |
| 410 | match ended { |
| 411 | Ok(Ended::Exited(code)) if code != 0 => self.log.line(&format!("##[error]The action exited with code {code}.")), |
| 412 | Ok(Ended::TimedOut) => self.log.line("##[error]The action ran past its time limit and was stopped."), |
| 413 | _ => {} |
| 414 | } |
| 415 | let (outputs, state) = self.absorb(&files, &commands); |
| 416 | self.last_node_outputs = outputs; |
| 417 | self.last_node_state = state; |
| 418 | ok |
| 419 | } |
| 420 | |
| 421 | fn deadline_left(&self) -> Duration { |
| 422 | self.remaining_time() |
| 423 | } |
| 424 | |
| 425 | /// Runs a `uses:` step. Returns whether it succeeded, and its outputs. |
| 426 | #[allow(clippy::too_many_arguments)] |
| 427 | pub(crate) fn uses( |
| 428 | &mut self, |
| 429 | uses: &str, |
| 430 | with: &BTreeMap<String, String>, |
| 431 | env: &BTreeMap<String, String>, |
| 432 | frame: &Frame, |
| 433 | title: &str, |
| 434 | id: Option<&str>, |
| 435 | _timeout: Duration, |
| 436 | ) -> (bool, BTreeMap<String, String>) { |
| 437 | let uses = uses.trim(); |
| 438 | if let Some(image) = uses.strip_prefix("docker://") { |
| 439 | // `with.args` and `with.entrypoint` are the container's; every |
| 440 | // input is also an `INPUT_` variable, as on GitHub. |
| 441 | let mut step_env = env.clone(); |
| 442 | for (input, value) in with { |
| 443 | step_env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone()); |
| 444 | } |
| 445 | let run = DockerRun { |
| 446 | image: image.to_owned(), |
| 447 | entrypoint: with.get("entrypoint").filter(|e| !e.is_empty()).cloned(), |
| 448 | args: with.get("args").map(|a| containers::split_words(a)).unwrap_or_default(), |
| 449 | env: step_env, |
| 450 | }; |
| 451 | let (ok, outputs, _) = self.run_docker(&run); |
| 452 | return (ok, outputs); |
| 453 | } |
| 454 | let (name, git_ref) = uses.split_once('@').unwrap_or((uses, "")); |
| 455 | let lower = name.to_ascii_lowercase(); |
| 456 | if lower == "docker/setup-buildx-action" && native(&lower, self.docker_hosted) { |
| 457 | return self.setup_buildx(with); |
| 458 | } |
| 459 | match lower.as_str() { |
| 460 | "actions/checkout" => return self.checkout(with), |
| 461 | "actions/upload-artifact" => return self.upload_artifact(with), |
| 462 | "actions/upload-artifact/merge" => return self.merge_artifacts(with), |
| 463 | "actions/download-artifact" => return self.download_artifact(with), |
| 464 | "actions/cache" => return self.cache(with, true, title), |
| 465 | "actions/cache/restore" => return self.cache(with, false, title), |
| 466 | "actions/cache/save" => return self.cache_save_now(with), |
| 467 | _ => {} |
| 468 | } |
| 469 | let source = if let Some(local) = name.strip_prefix("./") { |
| 470 | // A repository moved from GitHub renamed `.github` to `.g1t`, but |
| 471 | // its workflows still say `./.github/actions/…`. |
| 472 | let mut dir = self.workspace.join(local); |
| 473 | if let Some(rest) = local.strip_prefix(".github/") |
| 474 | && !dir.exists() |
| 475 | { |
| 476 | dir = self.workspace.join(".g1t").join(rest); |
| 477 | } |
| 478 | Source::Local(dir) |
| 479 | } else { |
| 480 | let mut parts = name.splitn(3, '/'); |
| 481 | let (Some(owner), Some(repo)) = (parts.next(), parts.next()) else { |
| 482 | self.log.line(&format!("##[error]`{uses}` is not an action: use owner/repo@ref, owner/repo/path@ref, or ./path.")); |
| 483 | return (false, BTreeMap::new()); |
| 484 | }; |
| 485 | if git_ref.is_empty() { |
| 486 | self.log.line(&format!("##[error]`{uses}` needs a version, such as @v4.")); |
| 487 | return (false, BTreeMap::new()); |
| 488 | } |
| 489 | Source::GitHub { |
| 490 | owner: owner.to_owned(), |
| 491 | repo: repo.to_owned(), |
| 492 | path: parts.next().unwrap_or_default().to_owned(), |
| 493 | git_ref: git_ref.to_owned(), |
| 494 | } |
| 495 | }; |
| 496 | let (dir, repository) = match &source { |
| 497 | Source::Local(dir) => (dir.clone(), String::new()), |
| 498 | Source::GitHub { owner, repo, path, git_ref } => match self.fetch_remote_action(owner, repo, git_ref) { |
| 499 | Some(root) => (if path.is_empty() { root } else { root.join(path) }, format!("{owner}/{repo}")), |
| 500 | None => return (false, BTreeMap::new()), |
| 501 | }, |
| 502 | }; |
| 503 | let manifest = ["action.yml", "action.yaml"].iter().map(|f| dir.join(f)).find(|p| p.exists()); |
| 504 | let Some(manifest) = manifest else { |
| 505 | self.log.line(&format!("##[error]`{uses}` has no action.yml.")); |
| 506 | return (false, BTreeMap::new()); |
| 507 | }; |
| 508 | let action = match std::fs::read_to_string(&manifest).ok().and_then(|text| serde_yaml::from_str::<serde_yaml::Value>(&text).ok()) { |
| 509 | Some(yaml) => yaml_to_json(&yaml), |
| 510 | None => { |
| 511 | self.log.line(&format!("##[error]`{uses}`: its action.yml does not read.")); |
| 512 | return (false, BTreeMap::new()); |
| 513 | } |
| 514 | }; |
| 515 | |
| 516 | // Inputs: what the step gives, else the action's defaults. |
| 517 | let env_context = env.clone(); |
| 518 | let contexts = self.contexts_for(frame, &env_context); |
| 519 | let mut inputs: BTreeMap<String, String> = BTreeMap::new(); |
| 520 | if let Some(Value::Object(declared)) = action.get("inputs") { |
| 521 | for (input, spec) in declared { |
| 522 | let given = with.iter().find(|(k, _)| k.eq_ignore_ascii_case(input)).map(|(_, v)| v.clone()); |
| 523 | let value = match given { |
| 524 | Some(value) => value, |
| 525 | None => match spec.get("default") { |
| 526 | Some(default) => { |
| 527 | let default = self.with_scope(&contexts, |scope| expr::interpolate_value(default, scope)).unwrap_or(Value::Null); |
| 528 | expr::to_text(&default) |
| 529 | } |
| 530 | None => String::new(), |
| 531 | }, |
| 532 | }; |
| 533 | inputs.insert(input.clone(), value); |
| 534 | } |
| 535 | } |
| 536 | for (key, value) in with { |
| 537 | if !inputs.keys().any(|k| k.eq_ignore_ascii_case(key)) { |
| 538 | inputs.insert(key.clone(), value.clone()); |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | let runs = action.get("runs").cloned().unwrap_or(Value::Null); |
| 543 | let using = runs.get("using").map(expr::to_text).unwrap_or_default().to_ascii_lowercase(); |
| 544 | let mut step_env = env.clone(); |
| 545 | step_env.insert("GITHUB_ACTION".into(), id.map_or_else(|| format!("__{}", repository.replace('/', "_")), str::to_owned)); |
| 546 | step_env.insert("GITHUB_ACTION_REPOSITORY".into(), repository.clone()); |
| 547 | step_env.insert("GITHUB_ACTION_REF".into(), git_ref.to_owned()); |
| 548 | step_env.insert("GITHUB_ACTION_PATH".into(), dir.display().to_string()); |
| 549 | |
| 550 | if using.starts_with("node") { |
| 551 | for (input, value) in &inputs { |
| 552 | step_env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone()); |
| 553 | } |
| 554 | let condition_of = |key: &str| runs.get(key).map(expr::to_text).unwrap_or_else(|| "always()".into()); |
| 555 | if let Some(pre) = runs.get("pre").map(expr::to_text) { |
| 556 | let run_pre = self.with_scope(&contexts, |scope| expr::condition(&condition_of("pre-if"), scope)).unwrap_or(true); |
| 557 | if run_pre && !self.run_node(&dir, &pre, &step_env) { |
| 558 | return (false, BTreeMap::new()); |
| 559 | } |
| 560 | } |
| 561 | let Some(main) = runs.get("main").map(expr::to_text) else { |
| 562 | self.log.line(&format!("##[error]`{uses}` has no `runs.main`.")); |
| 563 | return (false, BTreeMap::new()); |
| 564 | }; |
| 565 | let ok = self.run_node(&dir, &main, &step_env); |
| 566 | let outputs = std::mem::take(&mut self.last_node_outputs); |
| 567 | let state = std::mem::take(&mut self.last_node_state); |
| 568 | if let Some(post) = runs.get("post").map(expr::to_text) { |
| 569 | let mut post_env = step_env.clone(); |
| 570 | for (name, value) in state { |
| 571 | post_env.insert(format!("STATE_{name}"), value); |
| 572 | } |
| 573 | self.posts.push(Post { |
| 574 | name: format!("Post {title}"), |
| 575 | condition: condition_of("post-if"), |
| 576 | env: post_env, |
| 577 | run: PostRun::Node { action_dir: dir.clone(), script: post }, |
| 578 | }); |
| 579 | } |
| 580 | return (ok, outputs); |
| 581 | } |
| 582 | if using == "composite" { |
| 583 | let mut inner = Frame { |
| 584 | steps: Map::new(), |
| 585 | inputs: Some(Value::Object(inputs.iter().map(|(k, v)| (k.clone(), json!(v))).collect())), |
| 586 | action_path: Some(dir.display().to_string()), |
| 587 | env: env.clone(), |
| 588 | }; |
| 589 | let 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(); |
| 590 | let was_failed = self.failed; |
| 591 | // A composite's steps see their own success, not the job's. |
| 592 | self.failed = false; |
| 593 | let mut ok = true; |
| 594 | for step in &steps { |
| 595 | if !self.step(&mut inner, step, 0, false, &Map::new()) { |
| 596 | ok = false; |
| 597 | } |
| 598 | } |
| 599 | let contexts = self.contexts_for(&inner, &inner.env.clone()); |
| 600 | let mut outputs = BTreeMap::new(); |
| 601 | if let Some(Value::Object(declared)) = action.get("outputs") { |
| 602 | for (name, spec) in declared { |
| 603 | if let Some(value) = spec.get("value") { |
| 604 | let value = self.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null); |
| 605 | outputs.insert(name.clone(), expr::to_text(&value)); |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | self.failed = was_failed; |
| 610 | return (ok, outputs); |
| 611 | } |
| 612 | if using == "docker" { |
| 613 | return self.docker_action(uses, &dir, &runs, &inputs, &step_env, frame, title); |
| 614 | } |
| 615 | self.log.line(&format!("##[error]`{uses}` runs with `{using}`, which g1t does not know.")); |
| 616 | (false, BTreeMap::new()) |
| 617 | } |
| 618 | |
| 619 | /// A Docker action: its image built from its Dockerfile (or pulled, |
| 620 | /// for `docker://`), then run with its `args`, `entrypoint` and `env`, |
| 621 | /// its inputs as `INPUT_` variables, and `pre-entrypoint` and |
| 622 | /// `post-entrypoint` around it. |
| 623 | #[allow(clippy::too_many_arguments)] |
| 624 | fn docker_action( |
| 625 | &mut self, |
| 626 | uses: &str, |
| 627 | dir: &Path, |
| 628 | runs: &Value, |
| 629 | inputs: &BTreeMap<String, String>, |
| 630 | step_env: &BTreeMap<String, String>, |
| 631 | frame: &Frame, |
| 632 | title: &str, |
| 633 | ) -> (bool, BTreeMap<String, String>) { |
| 634 | let image = runs.get("image").map(expr::to_text).unwrap_or_default(); |
| 635 | let image = if let Some(pulled) = image.strip_prefix("docker://") { |
| 636 | pulled.to_owned() |
| 637 | } else if image.is_empty() { |
| 638 | self.log.line(&format!("##[error]`{uses}` has no `runs.image`.")); |
| 639 | return (false, BTreeMap::new()); |
| 640 | } else { |
| 641 | match self.build_action_image(dir, &image, uses) { |
| 642 | Some(tag) => tag, |
| 643 | None => return (false, BTreeMap::new()), |
| 644 | } |
| 645 | }; |
| 646 | // `args` and `env` read with the action's own inputs. |
| 647 | let mut env = step_env.clone(); |
| 648 | for (input, value) in inputs { |
| 649 | env.insert(format!("INPUT_{}", input.replace(' ', "_").to_ascii_uppercase()), value.clone()); |
| 650 | } |
| 651 | let mut scope_frame = frame.clone(); |
| 652 | scope_frame.inputs = Some(Value::Object(inputs.iter().map(|(k, v)| (k.clone(), json!(v))).collect())); |
| 653 | let contexts = self.contexts_for(&scope_frame, &env); |
| 654 | if let Some(Value::Object(own)) = runs.get("env") { |
| 655 | for (name, value) in own { |
| 656 | let value = self.with_scope(&contexts, |scope| expr::interpolate_value(value, scope)).unwrap_or(Value::Null); |
| 657 | env.insert(name.clone(), expr::to_text(&value)); |
| 658 | } |
| 659 | } |
| 660 | let args: Vec<String> = match runs.get("args") { |
| 661 | Some(Value::Array(items)) => items |
| 662 | .iter() |
| 663 | .map(|item| { |
| 664 | let value = self.with_scope(&contexts, |scope| expr::interpolate_value(item, scope)).unwrap_or(Value::Null); |
| 665 | expr::to_text(&value) |
| 666 | }) |
| 667 | .collect(), |
| 668 | _ => Vec::new(), |
| 669 | }; |
| 670 | let entry = |key: &str| runs.get(key).map(expr::to_text).filter(|e| !e.is_empty()); |
| 671 | if let Some(pre) = entry("pre-entrypoint") { |
| 672 | let run = DockerRun { image: image.clone(), entrypoint: Some(pre), args: Vec::new(), env: env.clone() }; |
| 673 | if !self.run_docker(&run).0 { |
| 674 | return (false, BTreeMap::new()); |
| 675 | } |
| 676 | } |
| 677 | let run = DockerRun { image: image.clone(), entrypoint: entry("entrypoint"), args, env: env.clone() }; |
| 678 | let (ok, outputs, state) = self.run_docker(&run); |
| 679 | if let Some(post) = entry("post-entrypoint") { |
| 680 | let mut post_env = env; |
| 681 | for (name, value) in state { |
| 682 | post_env.insert(format!("STATE_{name}"), value); |
| 683 | } |
| 684 | self.posts.push(Post { |
| 685 | name: format!("Post {title}"), |
| 686 | condition: runs.get("post-if").map(expr::to_text).unwrap_or_else(|| "always()".into()), |
| 687 | env: BTreeMap::new(), |
| 688 | run: PostRun::Docker(DockerRun { image, entrypoint: Some(post), args: Vec::new(), env: post_env }), |
| 689 | }); |
| 690 | } |
| 691 | (ok, outputs) |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | #[cfg(test)] |
| 696 | mod tests { |
| 697 | use super::*; |
| 698 | |
| 699 | #[test] |
| 700 | fn the_actions_fetched_before_the_first_step_are_other_repositories() { |
| 701 | let found = |uses: &str| remote_action(uses, true); |
| 702 | assert_eq!(found("actions/setup-node@v4"), Some(("actions".into(), "setup-node".into(), "v4".into()))); |
| 703 | assert_eq!(found(" github/codeql-action/init@v3 "), Some(("github".into(), "codeql-action".into(), "v3".into()))); |
| 704 | // Done by the runner itself, local, an image, or no version. |
| 705 | assert_eq!(found("actions/checkout@v4"), None); |
| 706 | assert_eq!(found("Actions/Cache/Restore@v4"), None); |
| 707 | assert_eq!(found("docker/setup-buildx-action@v3"), None); |
| 708 | assert!(remote_action("docker/setup-buildx-action@v3", false).is_some()); |
| 709 | assert_eq!(found("./.g1t/actions/setup"), None); |
| 710 | assert_eq!(found("docker://alpine:3"), None); |
| 711 | assert_eq!(found("actions/setup-node"), None); |
| 712 | assert_eq!(found("setup-node@v4"), None); |
| 713 | } |
| 714 | } |