| 1 | //! What starts a run: an event on the bus, a schedule, or someone running a |
| 2 | //! workflow by hand. Each finds the workflows that want it, at the commit |
| 3 | //! the event is about, and checks their filters. |
| 4 | |
| 5 | use g1t_actions::events::{RunInfo, github_events}; |
| 6 | use g1t_actions::workflow::{self, Trigger, Workflow}; |
| 7 | use g1t_contracts::access::{self, Capability}; |
| 8 | use g1t_contracts::actions::{DispatchArgs, RepositoryDispatchArgs, WorkflowRun}; |
| 9 | use g1t_contracts::events::{Event, caused_by_job}; |
| 10 | use g1t_contracts::identity::{AGENT_ID, AGENT_NAME, UsernamesArgs}; |
| 11 | use g1t_contracts::repos::{Commit, CompareArgs, Comparison, FileStatus, LogArgs, PullMergeRef, PullMergeRefArgs, Repo, RepoPath}; |
| 12 | use g1t_contracts::work::{Label, PullDetail, ViewArgs, WorkItemDetail, WorkItemViewArgs, WorkspaceViewArgs}; |
| 13 | use g1t_contracts::{FailureCode, Outcome, User, new_id}; |
| 14 | use g1t_contracts::time::rfc3339; |
| 15 | use g1t_kit::now_ms; |
| 16 | use serde_json::{Map, Value, json}; |
| 17 | use worker::Result; |
| 18 | |
| 19 | use crate::plan::NewRun; |
| 20 | use crate::sync::{Read, WorkflowRow}; |
| 21 | use crate::{API, Actions, SITE, check, fail, payload}; |
| 22 | |
| 23 | /// How many commits a push's log reads: its `commits`, and how far back |
| 24 | /// `before` is looked for to tell a forced push. |
| 25 | const PUSH_LOG: u32 = 20; |
| 26 | |
| 27 | /// What an event is about, worked out once for every workflow it starts. |
| 28 | struct Subject { |
| 29 | /// Where the workflow files are read, and at which commit. |
| 30 | source: RepoPath, |
| 31 | source_ref: Option<String>, |
| 32 | git_ref: String, |
| 33 | sha: String, |
| 34 | head_ref: Option<String>, |
| 35 | base_ref: Option<String>, |
| 36 | pull: Option<u32>, |
| 37 | /// The branch or tag for `branches`/`tags` filters; for pull requests, |
| 38 | /// the branch they merge into. |
| 39 | filter_ref: String, |
| 40 | /// The files it changes, for `paths` filters; `None` until needed. |
| 41 | paths: Option<Vec<String>>, |
| 42 | /// For a push, what to compare to find the files. |
| 43 | compare: Option<(Option<String>, String)>, |
| 44 | payload: Value, |
| 45 | title: String, |
| 46 | trusted: bool, |
| 47 | /// Why its runs wait for approval first: a pull request from outside, |
| 48 | /// by the repository's approval policy (protection.rs). |
| 49 | approval: Option<String>, |
| 50 | /// What the run builds when it is not `sha`: a pull request's test |
| 51 | /// merge commit (`refs/pull/<n>/merge`), as on GitHub, which becomes |
| 52 | /// `github.sha` while statuses and checks stay on `sha`, its head. |
| 53 | merge: Option<String>, |
| 54 | } |
| 55 | |
| 56 | impl Subject { |
| 57 | /// What the event changes, once compared: the paths for `paths` |
| 58 | /// filters, and a push's commit's `added`, `removed` and `modified`. |
| 59 | fn changed(&mut self, changes: Vec<(String, FileStatus)>) { |
| 60 | payload::push_changes(&mut self.payload, &changes); |
| 61 | self.paths = Some(changes.into_iter().map(|(path, _)| path).collect()); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// Where repos keeps every pull request's working copy (`pulls/<pull id>`). |
| 66 | const WORKING_COPIES: &str = "pulls"; |
| 67 | |
| 68 | /// The address a push's `pusher.email` gives: g1t's for its agent and |
| 69 | /// itself, a person's noreply address (which needs no lookup) for them, |
| 70 | /// and none for anyone else. |
| 71 | fn pusher_email(actor: Option<&str>, username: &str) -> Option<String> { |
| 72 | match actor? { |
| 73 | id if id == AGENT_ID || id == g1t_contracts::system::ID => Some(g1t_contracts::system::EMAIL.to_owned()), |
| 74 | id if id.starts_with("usr_") => Some(g1t_contracts::accounts::noreply_address(id, username)), |
| 75 | _ => None, |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Whether a deployment's `ref` is a commit's full hash rather than a |
| 80 | /// branch or tag. |
| 81 | fn is_commit(name: &str) -> bool { |
| 82 | name.len() == 40 && name.chars().all(|c| c.is_ascii_hexdigit()) |
| 83 | } |
| 84 | |
| 85 | /// What a ref made or deleted is, as `create` and `delete` name it: |
| 86 | /// `branch` or `tag`, and its short name. `None` for any other ref, and |
| 87 | /// for the merge queue's own branches, which come and go with every |
| 88 | /// queued change. |
| 89 | fn branch_or_tag(git_ref: &str) -> Option<(&'static str, &str)> { |
| 90 | if git_ref.starts_with("refs/heads/g1t-queue/") { |
| 91 | return None; |
| 92 | } |
| 93 | match (git_ref.strip_prefix("refs/heads/"), git_ref.strip_prefix("refs/tags/")) { |
| 94 | (Some(branch), _) => Some(("branch", branch)), |
| 95 | (_, Some(tag)) => Some(("tag", tag)), |
| 96 | _ => None, |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /// Events GitHub takes no `branches`, `tags` or `paths` filters on. |
| 101 | fn unfiltered(event_name: &str) -> bool { |
| 102 | matches!(event_name, "create" | "delete") |
| 103 | } |
| 104 | |
| 105 | /// What a pull request's run builds, given its test merge commit. |
| 106 | #[derive(Debug, PartialEq, Eq)] |
| 107 | enum PullBuild { |
| 108 | /// The merge commit, as on GitHub. |
| 109 | Merge(String), |
| 110 | /// The head: g1t could not make the merge commit itself, or a |
| 111 | /// conflicting pull request's event that still runs without one. |
| 112 | Head, |
| 113 | /// No run: GitHub starts no `pull_request` workflow while the pull |
| 114 | /// request has conflicts, since there is no merge commit to build. The |
| 115 | /// pull request's checks say so (apps/web `pull.tsx`). |
| 116 | Nothing, |
| 117 | } |
| 118 | |
| 119 | fn pull_build(event_name: &str, action: Option<&str>, made: &PullMergeRef) -> PullBuild { |
| 120 | match made { |
| 121 | PullMergeRef::Merged { merge, .. } => PullBuild::Merge(merge.clone()), |
| 122 | PullMergeRef::Conflict { .. } if event_name == "pull_request" && action != Some("closed") => PullBuild::Nothing, |
| 123 | PullMergeRef::Conflict { .. } | PullMergeRef::Unavailable { .. } => PullBuild::Head, |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | /// Whether an `*.assigned` event added nobody: g1t says so for a change |
| 128 | /// that only took people off. |
| 129 | fn nobody_added(data: &Value) -> bool { |
| 130 | data["added"].as_array().is_some_and(Vec::is_empty) |
| 131 | } |
| 132 | |
| 133 | /// The repositories whose workflows an event may start: every repository a |
| 134 | /// work item is linked to (`repoIds`, on its events and on comments on it), |
| 135 | /// else the one the event is filed under. |
| 136 | fn event_repos(event: &Event) -> Vec<String> { |
| 137 | let mut repos: Vec<String> = Vec::new(); |
| 138 | for id in event.data["repoIds"].as_array().into_iter().flatten().filter_map(Value::as_str) { |
| 139 | if !id.is_empty() && !repos.iter().any(|known| known == id) { |
| 140 | repos.push(id.to_owned()); |
| 141 | } |
| 142 | } |
| 143 | if repos.is_empty() |
| 144 | && let Some(id) = event.repo_id.as_deref().filter(|id| !id.is_empty()) |
| 145 | { |
| 146 | repos.push(id.to_owned()); |
| 147 | } |
| 148 | repos |
| 149 | } |
| 150 | |
| 151 | /// Whether whoever a pull request is for is trusted without asking |
| 152 | /// identity: someone whose role here is known to allow pushing. |
| 153 | fn trusted_outright(owner: &User, repo: &Repo) -> bool { |
| 154 | access::can(Some(owner), repo, Capability::Push) |
| 155 | } |
| 156 | |
| 157 | impl Actions { |
| 158 | async fn username(&self, id: Option<&str>) -> Result<Option<String>> { |
| 159 | let Some(id) = id else { return Ok(None) }; |
| 160 | if id == AGENT_ID { |
| 161 | return Ok(Some(AGENT_NAME.to_owned())); |
| 162 | } |
| 163 | let names: std::collections::HashMap<String, String> = |
| 164 | g1t_kit::call(&self.identity, "usernames", &UsernamesArgs { ids: vec![id.to_owned()] }).await?; |
| 165 | Ok(names.get(id).cloned()) |
| 166 | } |
| 167 | |
| 168 | /// Whether whoever a pull request is for (Pull::owner: whoever asked |
| 169 | /// g1t for it, or its author) could push to the repository, so its |
| 170 | /// runs get the secrets and a token. Anyone else's, a reader's included |
| 171 | /// (who may open one on a private repository too), runs without them. |
| 172 | /// A change g1t made for someone is trusted as they are. |
| 173 | async fn insider(&self, owner: &User, repo: &Repo, ws: &User) -> Result<bool> { |
| 174 | if trusted_outright(owner, repo) { |
| 175 | return Ok(true); |
| 176 | } |
| 177 | // Stored authors carry no memberships or grants: ask identity, as |
| 178 | // the workspace (which may see anyone's permission). |
| 179 | let permission: Outcome<access::PermissionInfo> = g1t_kit::call( |
| 180 | &self.identity, |
| 181 | "collaborator_permission", |
| 182 | &access::CollaboratorPermissionArgs { |
| 183 | viewer: Some(ws.clone()), |
| 184 | path: RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() }, |
| 185 | username: owner.username.clone(), |
| 186 | }, |
| 187 | ) |
| 188 | .await?; |
| 189 | Ok(permission |
| 190 | .into_result() |
| 191 | .ok() |
| 192 | .and_then(|info| info.role) |
| 193 | .is_some_and(|role| access::allows(role, Capability::Push))) |
| 194 | } |
| 195 | |
| 196 | async fn commits(&self, repo: &Repo, actor: &User, after: &str, before: Option<&str>) -> Result<Vec<Commit>> { |
| 197 | Ok(self.pushed_commits(repo, actor, after, before).await?.0) |
| 198 | } |
| 199 | |
| 200 | /// The commits a push added, oldest first, and whether it was forced: |
| 201 | /// `before` is not in `after`'s history. Known only when that history |
| 202 | /// is read whole (it is shorter than the [`PUSH_LOG`] commits read); |
| 203 | /// a longer one says not forced. |
| 204 | async fn pushed_commits(&self, repo: &Repo, actor: &User, after: &str, before: Option<&str>) -> Result<(Vec<Commit>, bool)> { |
| 205 | let log: Outcome<Vec<Commit>> = g1t_kit::call( |
| 206 | &self.repos, |
| 207 | "log", |
| 208 | &LogArgs { |
| 209 | path: RepoPath { |
| 210 | namespace: repo.namespace.clone(), |
| 211 | name: repo.name.clone(), |
| 212 | }, |
| 213 | viewer: Some(actor.clone()), |
| 214 | git_ref: Some(after.to_owned()), |
| 215 | limit: PUSH_LOG, |
| 216 | }, |
| 217 | ) |
| 218 | .await?; |
| 219 | let mut commits: Vec<Commit> = log.into_result().unwrap_or_default(); |
| 220 | let whole = commits.len() < PUSH_LOG as usize; |
| 221 | let mut forced = false; |
| 222 | if let Some(before) = before.filter(|before| *before != payload::ZERO) { |
| 223 | match commits.iter().position(|commit| commit.hash == before) { |
| 224 | Some(at) => commits.truncate(at), |
| 225 | None => forced = whole && !commits.is_empty(), |
| 226 | } |
| 227 | } |
| 228 | // GitHub lists them oldest first, with the head commit last. |
| 229 | commits.reverse(); |
| 230 | Ok((commits, forced)) |
| 231 | } |
| 232 | |
| 233 | /// The message of the commit `sha` in `path`, when it can be read. |
| 234 | async fn head_message(&self, path: &RepoPath, actor: &User, sha: &str) -> Result<Option<String>> { |
| 235 | Ok(self.commit_at(path, actor, sha).await?.map(|commit| commit.message)) |
| 236 | } |
| 237 | |
| 238 | /// The commit `sha` in `path`, when it can be read. |
| 239 | async fn commit_at(&self, path: &RepoPath, actor: &User, sha: &str) -> Result<Option<Commit>> { |
| 240 | let log: Outcome<Vec<Commit>> = g1t_kit::call( |
| 241 | &self.repos, |
| 242 | "log", |
| 243 | &LogArgs { path: path.clone(), viewer: Some(actor.clone()), git_ref: Some(sha.to_owned()), limit: 1 }, |
| 244 | ) |
| 245 | .await?; |
| 246 | Ok(log.into_result().ok().and_then(|commits| commits.into_iter().next())) |
| 247 | } |
| 248 | |
| 249 | /// What `head` changes from `base`: each path and how. |
| 250 | async fn changed_paths(&self, repo: &Repo, actor: &User, base: Option<String>, head: String) -> Result<Vec<(String, FileStatus)>> { |
| 251 | let compared: Outcome<Comparison> = g1t_kit::call( |
| 252 | &self.repos, |
| 253 | "compare", |
| 254 | &CompareArgs { |
| 255 | repo_id: repo.id.clone(), |
| 256 | viewer: Some(actor.clone()), |
| 257 | base, |
| 258 | head: Some(head), |
| 259 | base_branch: None, |
| 260 | paths: None, |
| 261 | target_id: None, |
| 262 | }, |
| 263 | ) |
| 264 | .await?; |
| 265 | Ok(compared.into_result().map(|c| c.files.into_iter().map(|f| (f.path, f.status)).collect()).unwrap_or_default()) |
| 266 | } |
| 267 | |
| 268 | /// The workspace's labels, for their colors, when `payload` has any. |
| 269 | async fn label_colors(&self, repo: &Repo, ws: &User, payload: &mut Value) -> Result<()> { |
| 270 | if !payload::has_labels(payload) { |
| 271 | return Ok(()); |
| 272 | } |
| 273 | let args = WorkspaceViewArgs { workspace: repo.namespace.clone(), viewer: Some(ws.clone()) }; |
| 274 | let labels: Outcome<Vec<Label>> = g1t_kit::call(&self.work, "list_labels", &args).await?; |
| 275 | if let Outcome::Ok(labels) = labels { |
| 276 | payload::color_labels(payload, &labels); |
| 277 | } |
| 278 | Ok(()) |
| 279 | } |
| 280 | |
| 281 | async fn default_head(&self, repo: &Repo) -> Result<Option<String>> { |
| 282 | self.branch_head(repo, &repo.default_branch).await |
| 283 | } |
| 284 | |
| 285 | /// The commit `branch` points to now. |
| 286 | async fn branch_head(&self, repo: &Repo, branch: &str) -> Result<Option<String>> { |
| 287 | g1t_kit::call( |
| 288 | &self.repos, |
| 289 | "head", |
| 290 | &g1t_contracts::repos::HeadArgs { |
| 291 | repo_id: repo.id.clone(), |
| 292 | branch: branch.to_owned(), |
| 293 | }, |
| 294 | ) |
| 295 | .await |
| 296 | } |
| 297 | |
| 298 | /// The pull request's test merge commit for `head` (repos |
| 299 | /// `pull_merge_ref`), made or moved now. A failure to ask is |
| 300 | /// unavailable, so that its runs still start, on the head. |
| 301 | async fn test_merge(&self, repo: &Repo, pull: &g1t_contracts::work::Pull, head: &str, base_ref: &str) -> PullMergeRef { |
| 302 | let asked: Result<PullMergeRef> = g1t_kit::call( |
| 303 | &self.repos, |
| 304 | "pull_merge_ref", |
| 305 | &PullMergeRefArgs { |
| 306 | repo_id: repo.id.clone(), |
| 307 | source_id: pull.source_id().to_owned(), |
| 308 | head: head.to_owned(), |
| 309 | number: pull.number, |
| 310 | target_branch: Some(base_ref.to_owned()), |
| 311 | }, |
| 312 | ) |
| 313 | .await; |
| 314 | asked.unwrap_or_else(|error| PullMergeRef::Unavailable { reason: error.to_string() }) |
| 315 | } |
| 316 | |
| 317 | /// Whether `name` is one of the repository's branches. |
| 318 | async fn is_branch(&self, repo: &Repo, ws: &User, name: &str) -> Result<bool> { |
| 319 | let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call( |
| 320 | &self.repos, |
| 321 | "branches", |
| 322 | &g1t_contracts::repos::BranchesArgs { |
| 323 | path: Self::repo_path(repo), |
| 324 | viewer: Some(ws.clone()), |
| 325 | }, |
| 326 | ) |
| 327 | .await?; |
| 328 | Ok(branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == name)) |
| 329 | } |
| 330 | |
| 331 | fn repo_path(repo: &Repo) -> RepoPath { |
| 332 | RepoPath { |
| 333 | namespace: repo.namespace.clone(), |
| 334 | name: repo.name.clone(), |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | /// The subject of an event of `kind`, as GitHub's `event_name`. |
| 339 | async fn subject(&self, event: &Event, event_name: &str, action: Option<&str>, repo: &Repo, ws: &User, sender: &str) -> Result<Option<Subject>> { |
| 340 | let path = Self::repo_path(repo); |
| 341 | let data = &event.data; |
| 342 | let on_default = |sha: String, payload: Value, title: String, pull: Option<u32>| Subject { |
| 343 | source: path.clone(), |
| 344 | source_ref: None, |
| 345 | git_ref: format!("refs/heads/{}", repo.default_branch), |
| 346 | sha, |
| 347 | head_ref: None, |
| 348 | base_ref: None, |
| 349 | pull, |
| 350 | filter_ref: format!("refs/heads/{}", repo.default_branch), |
| 351 | paths: None, |
| 352 | compare: None, |
| 353 | payload, |
| 354 | title, |
| 355 | trusted: true, |
| 356 | approval: None, |
| 357 | merge: None, |
| 358 | }; |
| 359 | let view = |number: u32| ViewArgs { |
| 360 | repo: path.clone(), |
| 361 | number, |
| 362 | viewer: Some(ws.clone()), |
| 363 | after_seq: 0, |
| 364 | }; |
| 365 | Ok(match event_name { |
| 366 | "push" => { |
| 367 | let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else { |
| 368 | return Ok(None); |
| 369 | }; |
| 370 | // The merge queue's states run merge_group workflows, not push ones. |
| 371 | if git_ref.starts_with("refs/heads/g1t-queue/") { |
| 372 | return Ok(None); |
| 373 | } |
| 374 | let before = data["before"].as_str(); |
| 375 | let (commits, forced) = self.pushed_commits(repo, ws, after, before).await?; |
| 376 | let title = commits.last().map(|c| c.message.lines().next().unwrap_or_default().to_owned()).unwrap_or_default(); |
| 377 | let email = pusher_email(event.actor.as_deref(), sender); |
| 378 | let payload = payload::push(repo, git_ref, before, after, &commits, sender, email.as_deref(), forced); |
| 379 | Some(Subject { |
| 380 | source: path.clone(), |
| 381 | source_ref: Some(after.to_owned()), |
| 382 | git_ref: git_ref.to_owned(), |
| 383 | sha: after.to_owned(), |
| 384 | head_ref: None, |
| 385 | base_ref: None, |
| 386 | pull: None, |
| 387 | filter_ref: git_ref.to_owned(), |
| 388 | paths: None, |
| 389 | compare: Some((before.map(str::to_owned), after.to_owned())), |
| 390 | payload, |
| 391 | title, |
| 392 | trusted: true, |
| 393 | approval: None, |
| 394 | merge: None, |
| 395 | }) |
| 396 | } |
| 397 | // A branch or tag was made: its own commit, as on GitHub. |
| 398 | "create" => { |
| 399 | let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else { |
| 400 | return Ok(None); |
| 401 | }; |
| 402 | if git_ref.starts_with("refs/heads/g1t-queue/") || !data["before"].is_null() { |
| 403 | return Ok(None); |
| 404 | } |
| 405 | let Some((ref_type, name)) = branch_or_tag(git_ref) else { return Ok(None) }; |
| 406 | let payload = json!({ |
| 407 | "ref": name, |
| 408 | "ref_type": ref_type, |
| 409 | "master_branch": repo.default_branch, |
| 410 | "description": Value::Null, |
| 411 | "pusher_type": "user", |
| 412 | "repository": payload::repository(repo), |
| 413 | "sender": payload::user(sender), |
| 414 | }); |
| 415 | Some(Subject { |
| 416 | source: path.clone(), |
| 417 | source_ref: Some(after.to_owned()), |
| 418 | git_ref: git_ref.to_owned(), |
| 419 | sha: after.to_owned(), |
| 420 | head_ref: None, |
| 421 | base_ref: None, |
| 422 | pull: None, |
| 423 | filter_ref: git_ref.to_owned(), |
| 424 | paths: None, |
| 425 | compare: None, |
| 426 | payload, |
| 427 | title: format!("Created {ref_type} {name}"), |
| 428 | trusted: true, |
| 429 | approval: None, |
| 430 | merge: None, |
| 431 | }) |
| 432 | } |
| 433 | // A branch or tag was deleted: on the default branch's latest |
| 434 | // commit, as on GitHub, since what was deleted has no commit to |
| 435 | // run on now. |
| 436 | "delete" => { |
| 437 | let Some(git_ref) = data["ref"].as_str() else { return Ok(None) }; |
| 438 | let Some((ref_type, name)) = branch_or_tag(git_ref) else { return Ok(None) }; |
| 439 | let Some(sha) = self.default_head(repo).await? else { return Ok(None) }; |
| 440 | let payload = json!({ |
| 441 | "ref": name, |
| 442 | "ref_type": ref_type, |
| 443 | "pusher_type": "user", |
| 444 | "repository": payload::repository(repo), |
| 445 | "sender": payload::user(sender), |
| 446 | }); |
| 447 | Some(on_default(sha, payload, format!("Deleted {ref_type} {name}"), None)) |
| 448 | } |
| 449 | "pull_request" | "pull_request_target" | "pull_request_review" => { |
| 450 | let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) }; |
| 451 | // Assignees changed but nobody was added: someone was only |
| 452 | // taken off, which is not `assigned`. |
| 453 | if action == Some("assigned") && nobody_added(data) { |
| 454 | return Ok(None); |
| 455 | } |
| 456 | let detail: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?; |
| 457 | let Outcome::Ok(detail) = detail else { return Ok(None) }; |
| 458 | let pull = &detail.pull; |
| 459 | let base_ref = pull.base_branch(&repo.default_branch).to_owned(); |
| 460 | let mut payload = json!({ |
| 461 | "action": action, |
| 462 | "number": pull.number, |
| 463 | "pull_request": payload::pull(repo, pull), |
| 464 | "repository": payload::repository(repo), |
| 465 | "sender": payload::user(sender), |
| 466 | }); |
| 467 | payload::changed(repo, &mut payload, data); |
| 468 | self.label_colors(repo, ws, &mut payload).await?; |
| 469 | // `base.sha` is the base branch's tip now, as GitHub gives |
| 470 | // it, not where the two last agreed. |
| 471 | if let Some(tip) = self.branch_head(repo, &base_ref).await? { |
| 472 | payload["pull_request"]["base"]["sha"] = json!(tip); |
| 473 | } |
| 474 | // A merge's commit, once it has landed. |
| 475 | if pull.status == g1t_contracts::work::PullStatus::Merged |
| 476 | && let Some(commit) = data["commit"].as_str() |
| 477 | { |
| 478 | payload["pull_request"]["merge_commit_sha"] = json!(commit); |
| 479 | } |
| 480 | if event_name == "pull_request_review" { |
| 481 | let review = detail.comments.iter().rev().find(|c| c.verdict.is_some() && !c.advisory); |
| 482 | payload["review"] = payload::review(repo, pull, review); |
| 483 | } |
| 484 | // A branch of someone's fork takes pushes from whoever can |
| 485 | // push to the fork, not only from who opened the pull |
| 486 | // request: its runs are an outside contribution's. |
| 487 | let trusted = !pull.from_head_repo() && self.insider(pull.owner(), repo, ws).await?; |
| 488 | // A pull request from outside may wait for approval before |
| 489 | // its head's code runs. `pull_request_target` runs the |
| 490 | // base's code, and a merged one's run the commit it landed |
| 491 | // as, so neither waits. |
| 492 | let approval = if event_name != "pull_request_target" && action != Some("closed") { |
| 493 | self.approval_needed(repo, pull.owner(), ws).await? |
| 494 | } else { |
| 495 | None |
| 496 | }; |
| 497 | let head_ref = payload::head_ref(pull); |
| 498 | if event_name == "pull_request_target" { |
| 499 | // In the base's context: its workflows, its head. |
| 500 | let Some(sha) = self.default_head(repo).await? else { return Ok(None) }; |
| 501 | let mut subject = on_default(sha, payload, pull.title.clone(), Some(pull.number)); |
| 502 | subject.head_ref = Some(head_ref); |
| 503 | subject.base_ref = Some(base_ref.clone()); |
| 504 | subject.filter_ref = format!("refs/heads/{base_ref}"); |
| 505 | subject.paths = Some(pull.files.iter().map(|f| f.path.clone()).collect()); |
| 506 | return Ok(Some(subject)); |
| 507 | } |
| 508 | // A merged pull request's run is on the commit it landed as, |
| 509 | // in the repository; otherwise on its head, where that is. |
| 510 | let landed = match (action, data["commit"].as_str()) { |
| 511 | (Some("closed"), Some(commit)) => Some(commit.to_owned()), |
| 512 | _ => None, |
| 513 | }; |
| 514 | let sha = match (&landed, data["commit"].as_str(), &pull.head_commit) { |
| 515 | (Some(commit), _, _) => commit.clone(), |
| 516 | (None, Some(commit), _) => commit.to_owned(), |
| 517 | (None, None, Some(head)) => head.clone(), |
| 518 | (None, None, None) => return Ok(None), |
| 519 | }; |
| 520 | // Otherwise it builds the head merged into the base's tip, |
| 521 | // as on GitHub: the test merge commit at refs/pull/<n>/merge, |
| 522 | // in the repository, whose workflows it reads. |
| 523 | let merge = match landed { |
| 524 | Some(_) => None, |
| 525 | None => { |
| 526 | let made = self.test_merge(repo, pull, &sha, &base_ref).await; |
| 527 | match pull_build(event_name, action, &made) { |
| 528 | PullBuild::Merge(merge) => Some(merge), |
| 529 | PullBuild::Nothing => { |
| 530 | worker::console_log!("actions: pull request #{} conflicts with {base_ref}: {made:?}; no pull_request workflows run", pull.number); |
| 531 | return Ok(None); |
| 532 | } |
| 533 | PullBuild::Head => { |
| 534 | worker::console_log!("actions: no merge commit for pull request #{}: {made:?}; its head is built", pull.number); |
| 535 | None |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | }; |
| 540 | if let Some(merge) = &merge { |
| 541 | payload["pull_request"]["merge_commit_sha"] = json!(merge); |
| 542 | } |
| 543 | let (source, source_ref) = match (&landed, &merge) { |
| 544 | (Some(_), _) => (path.clone(), sha.clone()), |
| 545 | (None, Some(merge)) => (path.clone(), merge.clone()), |
| 546 | (None, None) => (pull.source_path(&path), sha.clone()), |
| 547 | }; |
| 548 | Some(Subject { |
| 549 | source, |
| 550 | source_ref: Some(source_ref), |
| 551 | merge, |
| 552 | git_ref: format!("refs/pull/{}/merge", pull.number), |
| 553 | sha, |
| 554 | head_ref: Some(head_ref), |
| 555 | base_ref: Some(base_ref.clone()), |
| 556 | pull: Some(pull.number), |
| 557 | // `branches` filters on pull requests name the base. |
| 558 | filter_ref: format!("refs/heads/{base_ref}"), |
| 559 | paths: Some(pull.files.iter().map(|f| f.path.clone()).collect()), |
| 560 | compare: None, |
| 561 | payload, |
| 562 | title: pull.title.clone(), |
| 563 | trusted, |
| 564 | approval, |
| 565 | }) |
| 566 | } |
| 567 | "workflow_run" => { |
| 568 | // A run of a workflow_run workflow does not start another, |
| 569 | // so two such workflows cannot set each other off. |
| 570 | if data["event"].as_str() == Some("workflow_run") { |
| 571 | return Ok(None); |
| 572 | } |
| 573 | let Some(sha) = self.default_head(repo).await? else { return Ok(None) }; |
| 574 | let head_branch = data["ref"].as_str().unwrap_or_default().trim_start_matches("refs/heads/").to_owned(); |
| 575 | let name = data["workflow"].as_str().unwrap_or_default(); |
| 576 | // The followed run's row, for what the event does not carry. |
| 577 | let row = match data["runId"].as_str() { |
| 578 | Some(id) => self.db.prepare("SELECT * FROM runs WHERE id = ?").bind(&[id.into()])?.first::<crate::plan::RunRow>(None).await?, |
| 579 | None => None, |
| 580 | }; |
| 581 | let head_commit = match data["sha"].as_str() { |
| 582 | Some(head) => self.commit_at(&path, ws, head).await?.filter(|commit| commit.hash == head), |
| 583 | None => None, |
| 584 | }; |
| 585 | // Its pull request, for `pull_requests[]`. |
| 586 | let pull = match data["pull"].as_u64() { |
| 587 | Some(number) => match g1t_kit::call::<_, Outcome<PullDetail>>(&self.work, "get_pull", &view(number as u32)).await? { |
| 588 | Outcome::Ok(detail) => Some(detail.pull), |
| 589 | Outcome::Fail(_) => None, |
| 590 | }, |
| 591 | None => None, |
| 592 | }; |
| 593 | let base_sha = match &pull { |
| 594 | Some(pull) if !pull.from_other_repo() => self.branch_head(repo, pull.base_branch(&repo.default_branch)).await?, |
| 595 | _ => None, |
| 596 | }; |
| 597 | let followed = payload::FollowedRun { |
| 598 | pull: pull.as_ref(), |
| 599 | base_sha: base_sha.as_deref(), |
| 600 | data, |
| 601 | workflow_id: row.as_ref().map(|r| r.workflow_id.as_str()), |
| 602 | attempt: row.as_ref().map(|r| r.attempt), |
| 603 | created_at: row.as_ref().map(|r| r.created_at.as_str()), |
| 604 | started_at: row.as_ref().and_then(|r| r.started_at.as_deref()), |
| 605 | updated_at: row.as_ref().and_then(|r| r.finished_at.as_deref()), |
| 606 | actor: row.as_ref().and_then(|r| r.actor.as_deref()), |
| 607 | triggering_actor: row.as_ref().and_then(|r| r.triggering_actor.as_deref()), |
| 608 | title: row.as_ref().map(|r| r.title.as_str()), |
| 609 | head_commit: head_commit.as_ref(), |
| 610 | }; |
| 611 | let payload = json!({ |
| 612 | "action": "completed", |
| 613 | "workflow_run": payload::workflow_run(repo, &followed), |
| 614 | "workflow": { |
| 615 | "id": followed.workflow_id, |
| 616 | "node_id": followed.workflow_id, |
| 617 | "name": name, |
| 618 | "path": data["path"], |
| 619 | "state": "active", |
| 620 | "html_url": format!("{SITE}/{}/{}/actions", repo.namespace, repo.name), |
| 621 | }, |
| 622 | "repository": payload::repository(repo), |
| 623 | "sender": payload::user(sender), |
| 624 | }); |
| 625 | let mut subject = on_default(sha, payload, format!("After {name}"), None); |
| 626 | // Branch filters apply to the branch the followed run was on. |
| 627 | subject.filter_ref = format!("refs/heads/{head_branch}"); |
| 628 | Some(subject) |
| 629 | } |
| 630 | // A work item, or a comment on one or on a pull request: on the |
| 631 | // default branch, as GitHub's `issues` and `issue_comment` are. |
| 632 | "work_item" | "work_item_comment" => { |
| 633 | let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) }; |
| 634 | if action == Some("assigned") && nobody_added(data) { |
| 635 | return Ok(None); |
| 636 | } |
| 637 | let on_pull = event_name == "work_item_comment" && data["pullId"].is_string(); |
| 638 | let workspace = data["workspace"].as_str().unwrap_or(&repo.namespace).to_owned(); |
| 639 | let Some(sha) = self.default_head(repo).await? else { return Ok(None) }; |
| 640 | let (item_json, comments, title, thread) = if on_pull { |
| 641 | let pull: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?; |
| 642 | let Outcome::Ok(detail) = pull else { return Ok(None) }; |
| 643 | (payload::pull_as_item(repo, &detail.pull), detail.comments, detail.pull.title.clone(), payload::Thread::Pull) |
| 644 | } else { |
| 645 | let args = WorkItemViewArgs { workspace: workspace.clone(), number, viewer: Some(ws.clone()) }; |
| 646 | let item: Outcome<WorkItemDetail> = g1t_kit::call(&self.work, "get_work_item", &args).await?; |
| 647 | let Outcome::Ok(detail) = item else { return Ok(None) }; |
| 648 | let thread = payload::Thread::Item { workspace: &workspace }; |
| 649 | (payload::work_item(repo, &detail.item), detail.comments, detail.item.title.clone(), thread) |
| 650 | }; |
| 651 | let mut payload = json!({ |
| 652 | "action": action, |
| 653 | "work_item": item_json, |
| 654 | "repository": payload::repository(repo), |
| 655 | "sender": payload::user(sender), |
| 656 | }); |
| 657 | payload::changed(repo, &mut payload, data); |
| 658 | if event_name == "work_item" { |
| 659 | payload::work_item_changed(&mut payload, data); |
| 660 | } |
| 661 | self.label_colors(repo, ws, &mut payload).await?; |
| 662 | if event_name == "work_item_comment" { |
| 663 | let comment_id = data["commentId"].as_str(); |
| 664 | if action == Some("deleted") { |
| 665 | // Gone by now: as the event kept it. |
| 666 | match data.get("comment").filter(|kept| kept.is_object()) { |
| 667 | Some(kept) => payload["comment"] = payload::deleted_comment(repo, number, kept, thread), |
| 668 | None => return Ok(None), |
| 669 | } |
| 670 | } else { |
| 671 | let comment = comments.iter().find(|c| Some(c.id.as_str()) == comment_id); |
| 672 | // A new comment is the newest; an edited one must be found. |
| 673 | let comment = if action == Some("created") { comment.or(comments.last()) } else { comment }; |
| 674 | match comment { |
| 675 | Some(comment) => payload["comment"] = payload::comment(repo, number, comment, thread), |
| 676 | None => return Ok(None), |
| 677 | } |
| 678 | } |
| 679 | // `edited`: what the body was before. |
| 680 | if let Some(changes) = data.get("changes").filter(|changes| changes.is_object()) { |
| 681 | payload["changes"] = changes.clone(); |
| 682 | } |
| 683 | } |
| 684 | Some(on_default(sha, payload, title, on_pull.then_some(number))) |
| 685 | } |
| 686 | // A release: on its tag, at the commit the tag named. |
| 687 | "release" => { |
| 688 | let release = &data["release"]; |
| 689 | let Some(tag) = data["tagName"].as_str().or_else(|| release["tagName"].as_str()) else { return Ok(None) }; |
| 690 | let sha = match release["target"].as_str().filter(|target| !target.is_empty()) { |
| 691 | Some(target) => target.to_owned(), |
| 692 | None => match self.default_head(repo).await? { |
| 693 | Some(head) => head, |
| 694 | None => return Ok(None), |
| 695 | }, |
| 696 | }; |
| 697 | let git_ref = format!("refs/tags/{tag}"); |
| 698 | let mut payload = json!({ |
| 699 | "action": action, |
| 700 | "release": payload::release(repo, release), |
| 701 | "repository": payload::repository(repo), |
| 702 | "sender": payload::user(sender), |
| 703 | }); |
| 704 | if let Some(changes) = data.get("changes").filter(|changes| changes.is_object()) { |
| 705 | payload["changes"] = changes.clone(); |
| 706 | } |
| 707 | let name = release["name"].as_str().filter(|name| !name.is_empty()).unwrap_or(tag); |
| 708 | Some(Subject { |
| 709 | source: path.clone(), |
| 710 | source_ref: Some(sha.clone()), |
| 711 | git_ref: git_ref.clone(), |
| 712 | sha, |
| 713 | head_ref: None, |
| 714 | base_ref: None, |
| 715 | pull: None, |
| 716 | filter_ref: git_ref, |
| 717 | paths: None, |
| 718 | compare: None, |
| 719 | payload, |
| 720 | title: format!("Release {name} {}", action.unwrap_or("changed")), |
| 721 | trusted: true, |
| 722 | approval: None, |
| 723 | merge: None, |
| 724 | }) |
| 725 | } |
| 726 | // A deployment, or a new status of one: at the commit deployed, |
| 727 | // on the branch or tag it names (none for a bare commit). |
| 728 | "deployment" | "deployment_status" => { |
| 729 | let deployment = &data["deployment"]; |
| 730 | let Some(sha) = deployment["sha"].as_str().filter(|sha| !sha.is_empty()).map(str::to_owned) else { return Ok(None) }; |
| 731 | let named = deployment["ref"].as_str().unwrap_or_default(); |
| 732 | let git_ref = if named.is_empty() || named == sha || is_commit(named) { |
| 733 | String::new() |
| 734 | } else if named.starts_with("refs/") { |
| 735 | named.to_owned() |
| 736 | } else if self.is_branch(repo, ws, named).await? { |
| 737 | format!("refs/heads/{named}") |
| 738 | } else { |
| 739 | format!("refs/tags/{named}") |
| 740 | }; |
| 741 | let environment = deployment["environment"].as_str().unwrap_or_default(); |
| 742 | let mut payload = json!({ |
| 743 | "action": "created", |
| 744 | "deployment": payload::deployment(repo, deployment), |
| 745 | "repository": payload::repository(repo), |
| 746 | "sender": payload::user(sender), |
| 747 | }); |
| 748 | let title = if event_name == "deployment_status" { |
| 749 | let status = &data["deploymentStatus"]; |
| 750 | payload["deployment_status"] = payload::deployment_status(repo, status, deployment); |
| 751 | format!("Deployment to {environment}: {}", status["state"].as_str().unwrap_or("changed")) |
| 752 | } else { |
| 753 | format!("Deployment to {environment}") |
| 754 | }; |
| 755 | Some(Subject { |
| 756 | source: path.clone(), |
| 757 | source_ref: Some(sha.clone()), |
| 758 | filter_ref: git_ref.clone(), |
| 759 | git_ref, |
| 760 | sha, |
| 761 | head_ref: None, |
| 762 | base_ref: None, |
| 763 | pull: None, |
| 764 | paths: None, |
| 765 | compare: None, |
| 766 | payload, |
| 767 | title, |
| 768 | trusted: true, |
| 769 | approval: None, |
| 770 | merge: None, |
| 771 | }) |
| 772 | } |
| 773 | _ => None, |
| 774 | }) |
| 775 | } |
| 776 | |
| 777 | /// A push keeps the repository's schedules going (`run_schedules`). |
| 778 | /// Written at most once a day, and only on scheduled workflows. |
| 779 | async fn note_push(&self, repo_id: &str) -> Result<()> { |
| 780 | let at = now_ms(); |
| 781 | self.db |
| 782 | .prepare("UPDATE workflows SET pushed_at = ? WHERE repo_id = ? AND crons != '[]' AND (pushed_at IS NULL OR pushed_at < ?)") |
| 783 | .bind(&[rfc3339(at).into(), repo_id.into(), rfc3339(at.saturating_sub(24 * 60 * 60 * 1000)).into()])? |
| 784 | .run() |
| 785 | .await?; |
| 786 | Ok(()) |
| 787 | } |
| 788 | |
| 789 | pub async fn on_event(&self, event: &Event) -> Result<()> { |
| 790 | // Each queued event reads repositories' settings afresh. |
| 791 | self.actions_on.clear(); |
| 792 | for repo_id in event_repos(event) { |
| 793 | self.on_event_in(event, &repo_id).await?; |
| 794 | } |
| 795 | Ok(()) |
| 796 | } |
| 797 | |
| 798 | /// What `event` starts in one of the repositories it is about. |
| 799 | async fn on_event_in(&self, event: &Event, repo_id: &str) -> Result<()> { |
| 800 | let mut mapped = github_events(&event.kind); |
| 801 | // A new branch or tag is also `create`. |
| 802 | if event.kind == "git.push" && event.data["before"].is_null() { |
| 803 | mapped.push(("create", None)); |
| 804 | } |
| 805 | let pushed_default = event.kind == "git.push" && event.data["defaultBranch"].as_bool() == Some(true); |
| 806 | if event.kind == "git.push" { |
| 807 | self.note_push(repo_id).await?; |
| 808 | } |
| 809 | if mapped.is_empty() && !pushed_default { |
| 810 | return Ok(()); |
| 811 | } |
| 812 | let Some((repo, ws)) = self.repo_by_id(repo_id).await? else { return Ok(()) }; |
| 813 | // What the sync read, which a push to the default branch starts |
| 814 | // from while the branch is still at the pushed commit. |
| 815 | let synced = if pushed_default { Some(self.sync(&repo, &ws).await?) } else { None }; |
| 816 | // Nothing starts while the repository's Actions are off (a fork's |
| 817 | // are, until someone turns them on). Its workflows are still synced |
| 818 | // above, so turning them on finds them listed. `create_run` holds |
| 819 | // the gate; asking here (the same read) skips reading workflows |
| 820 | // from git for nothing. |
| 821 | if !self.actions_on(&repo).await? { |
| 822 | return Ok(()); |
| 823 | } |
| 824 | // What a workflow job's own token did starts no workflows, as on |
| 825 | // GitHub, so a workflow cannot set itself off; only |
| 826 | // `workflow_dispatch` and `repository_dispatch` do. |
| 827 | if let Some(run) = caused_by_job(&event.data) { |
| 828 | worker::console_log!("actions: {} {} came from run {run}'s token; no workflows start for it", event.kind, event.id); |
| 829 | return Ok(()); |
| 830 | } |
| 831 | let sender = self.username(event.actor.as_deref()).await?.unwrap_or_else(|| repo.namespace.clone()); |
| 832 | for (event_name, action) in mapped { |
| 833 | // Work items and comments start the default branch's |
| 834 | // workflows, which the synced table lists: when none listens, |
| 835 | // nothing is read from git. Agents make many of these events. |
| 836 | // Deployments' statuses are as frequent (every g1t.page build |
| 837 | // reports several), so they look there first too. |
| 838 | if matches!(event_name, "work_item" | "work_item_comment" | "deployment" | "deployment_status" | "delete") |
| 839 | && self.listens(repo_id, event_name).await? == Some(false) |
| 840 | { |
| 841 | continue; |
| 842 | } |
| 843 | let Some(mut subject) = self.subject(event, event_name, action, &repo, &ws, &sender).await? else { |
| 844 | continue; |
| 845 | }; |
| 846 | // `[skip ci]` in the head commit's message, as on GitHub. |
| 847 | if matches!(event_name, "push" | "pull_request") { |
| 848 | let message = match subject.payload["head_commit"]["message"].as_str() { |
| 849 | Some(message) => Some(message.to_owned()), |
| 850 | None => self.head_message(&subject.source, &ws, &subject.sha).await?, |
| 851 | }; |
| 852 | if message.as_deref().is_some_and(g1t_actions::events::skips_ci) { |
| 853 | worker::console_log!("actions: {} {} at {} asks to skip its runs", event.kind, event.id, subject.sha); |
| 854 | continue; |
| 855 | } |
| 856 | } |
| 857 | // A pull request from a working copy reads the copy's files. |
| 858 | let read = if subject.source == Self::repo_path(&repo) { |
| 859 | match synced.as_ref().filter(|read| read.head.as_deref() == Some(subject.sha.as_str())) { |
| 860 | // The same files at the same commit: reading them again |
| 861 | // took seconds of every push to the default branch. |
| 862 | Some(read) => read.clone(), |
| 863 | None => self.read_for(&repo, &ws, subject.source_ref.as_deref()).await?, |
| 864 | } |
| 865 | } else if !subject.source.namespace.eq_ignore_ascii_case(WORKING_COPIES) { |
| 866 | // A branch of someone's fork, built as its head (there was |
| 867 | // no merge commit): the workflows are this repository's, at |
| 868 | // the branch it merges into, never the fork's own. |
| 869 | self.read_for(&repo, &ws, subject.base_ref.as_deref()).await? |
| 870 | } else { |
| 871 | // And this repository's managed workflows: they are its own, |
| 872 | // whatever the fork's files say (managed.rs). |
| 873 | let mut read = self.read_workflows(&subject.source, &ws, subject.source_ref.as_deref()).await?; |
| 874 | read.files = self.with_managed(&repo, read.files).await?; |
| 875 | read |
| 876 | }; |
| 877 | // A pull request's head runs each workflow once, however many |
| 878 | // events say it is there (marked ready, and pushed). |
| 879 | let key = match subject.pull { |
| 880 | Some(number) if event_name.starts_with("pull_request") && event_name != "pull_request_review" => { |
| 881 | // Reopened or made a draft again runs anew, at a head |
| 882 | // that may have run before. |
| 883 | let phase = match action { |
| 884 | Some("closed") => "closed".to_owned(), |
| 885 | Some(again @ ("reopened" | "converted_to_draft")) => format!("{again}:{}", event.id), |
| 886 | _ => "open".to_owned(), |
| 887 | }; |
| 888 | format!("{event_name}:{number}:{}:{phase}", subject.sha) |
| 889 | } |
| 890 | _ if event_name == "create" => format!("{}:create", event.id), |
| 891 | _ => event.id.clone(), |
| 892 | }; |
| 893 | self.start_matching(&repo, &ws, read, &mut subject, event_name, action, &key, event.actor.as_deref(), &sender) |
| 894 | .await?; |
| 895 | } |
| 896 | Ok(()) |
| 897 | } |
| 898 | |
| 899 | #[allow(clippy::too_many_arguments)] |
| 900 | async fn start_matching( |
| 901 | &self, |
| 902 | repo: &Repo, |
| 903 | ws: &User, |
| 904 | read: Read, |
| 905 | subject: &mut Subject, |
| 906 | event_name: &str, |
| 907 | action: Option<&str>, |
| 908 | event_key: &str, |
| 909 | actor_id: Option<&str>, |
| 910 | sender: &str, |
| 911 | ) -> Result<()> { |
| 912 | let parsed: Vec<_> = read.files.into_iter().map(|file| (workflow::parse(&file.source), file)).collect(); |
| 913 | // A push some workflow filters by path is compared before any run |
| 914 | // starts, so every run's payload lists what its commit changed. |
| 915 | let filters_paths = |(parsed, _): &(std::result::Result<Workflow, _>, _)| { |
| 916 | parsed.as_ref().ok().and_then(|w: &Workflow| w.trigger(event_name)).is_some_and(|t| t.paths.is_set()) |
| 917 | }; |
| 918 | if event_name == "push" && subject.paths.is_none() && parsed.iter().any(filters_paths) { |
| 919 | let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone())); |
| 920 | subject.changed(self.changed_paths(repo, ws, base, head).await?); |
| 921 | } |
| 922 | for (parsed, file) in parsed { |
| 923 | let workflow = match parsed { |
| 924 | Ok(workflow) => workflow, |
| 925 | Err(problem) => { |
| 926 | // A push shows a broken workflow as a failed run, as GitHub does. |
| 927 | if event_name == "push" && file.source.contains("on") { |
| 928 | self.record_invalid(repo, &file.path, &file.source, subject, event_key, actor_id, sender, &problem) |
| 929 | .await?; |
| 930 | } |
| 931 | continue; |
| 932 | } |
| 933 | }; |
| 934 | let Some(trigger) = workflow.trigger(event_name) else { continue }; |
| 935 | // workflow_run follows the workflows it names. |
| 936 | if event_name == "workflow_run" { |
| 937 | let followed = subject.payload["workflow_run"]["name"].as_str().unwrap_or_default(); |
| 938 | if !trigger.workflows.iter().any(|name| name == followed) { |
| 939 | continue; |
| 940 | } |
| 941 | } |
| 942 | if !trigger.wants_type(action) || !self.passes(repo, ws, trigger, subject, event_name).await? { |
| 943 | continue; |
| 944 | } |
| 945 | // A workspace's required workflow runs whatever its row says. |
| 946 | if !file.required && self.disabled(&repo.id, &file.path).await? { |
| 947 | continue; |
| 948 | } |
| 949 | self.create_run(NewRun { |
| 950 | repo: repo.clone(), |
| 951 | path: file.path, |
| 952 | source: file.source, |
| 953 | info: self.run_info(repo, &workflow, event_name, subject, sender, actor_id), |
| 954 | workflow, |
| 955 | action: action.map(str::to_owned), |
| 956 | pull: subject.pull, |
| 957 | title: subject.title.clone(), |
| 958 | inputs: Map::new(), |
| 959 | event_key: event_key.to_owned(), |
| 960 | actor_id: actor_id.map(str::to_owned), |
| 961 | actor: Some(sender.to_owned()), |
| 962 | trusted: subject.trusted, |
| 963 | approval: subject.approval.clone(), |
| 964 | head_sha: subject.merge.as_ref().map(|_| subject.sha.clone()), |
| 965 | }) |
| 966 | .await?; |
| 967 | } |
| 968 | Ok(()) |
| 969 | } |
| 970 | |
| 971 | /// Whether the branch, tag and path filters let the event through. |
| 972 | async fn passes(&self, repo: &Repo, ws: &User, trigger: &Trigger, subject: &mut Subject, event_name: &str) -> Result<bool> { |
| 973 | // GitHub takes no filters on these: a workflow with `branches` on |
| 974 | // `create` or `delete` still runs for every branch and tag. |
| 975 | if unfiltered(event_name) { |
| 976 | return Ok(true); |
| 977 | } |
| 978 | let git_ref = subject.filter_ref.as_str(); |
| 979 | if let Some(tag) = git_ref.strip_prefix("refs/tags/") { |
| 980 | // A tag push runs a workflow that filters tags, or filters nothing. |
| 981 | if trigger.tags.is_set() { |
| 982 | if !trigger.tags.allows(tag) { |
| 983 | return Ok(false); |
| 984 | } |
| 985 | } else if trigger.branches.is_set() { |
| 986 | return Ok(false); |
| 987 | } |
| 988 | // Paths are not checked for tags, as on GitHub. |
| 989 | return Ok(true); |
| 990 | } |
| 991 | let branch = git_ref.strip_prefix("refs/heads/").unwrap_or(git_ref); |
| 992 | if trigger.branches.is_set() { |
| 993 | if !trigger.branches.allows(branch) { |
| 994 | return Ok(false); |
| 995 | } |
| 996 | } else if event_name == "push" && trigger.tags.is_set() { |
| 997 | return Ok(false); |
| 998 | } |
| 999 | if trigger.paths.is_set() { |
| 1000 | if subject.paths.is_none() { |
| 1001 | let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone())); |
| 1002 | subject.changed(self.changed_paths(repo, ws, base, head).await?); |
| 1003 | } |
| 1004 | if !trigger.paths.allows_paths(subject.paths.as_deref().unwrap_or_default()) { |
| 1005 | return Ok(false); |
| 1006 | } |
| 1007 | } |
| 1008 | Ok(true) |
| 1009 | } |
| 1010 | |
| 1011 | async fn disabled(&self, repo_id: &str, path: &str) -> Result<bool> { |
| 1012 | let row = self |
| 1013 | .db |
| 1014 | .prepare("SELECT * FROM workflows WHERE repo_id = ? AND path = ?") |
| 1015 | .bind(&[repo_id.into(), path.into()])? |
| 1016 | .first::<WorkflowRow>(None) |
| 1017 | .await?; |
| 1018 | Ok(row.is_some_and(|row| row.state == "disabled")) |
| 1019 | } |
| 1020 | |
| 1021 | fn run_info(&self, repo: &Repo, workflow: &Workflow, event_name: &str, subject: &Subject, sender: &str, actor_id: Option<&str>) -> RunInfo { |
| 1022 | RunInfo { |
| 1023 | repository: format!("{}/{}", repo.namespace, repo.name), |
| 1024 | repository_id: repo.id.clone(), |
| 1025 | default_branch: repo.default_branch.clone(), |
| 1026 | event_name: event_name.to_owned(), |
| 1027 | event: subject.payload.clone(), |
| 1028 | git_ref: subject.git_ref.clone(), |
| 1029 | sha: subject.merge.clone().unwrap_or_else(|| subject.sha.clone()), |
| 1030 | head_ref: subject.head_ref.clone(), |
| 1031 | base_ref: subject.base_ref.clone(), |
| 1032 | actor: sender.to_owned(), |
| 1033 | actor_id: actor_id.unwrap_or_default().to_owned(), |
| 1034 | triggering_actor: sender.to_owned(), |
| 1035 | run_id: String::new(), |
| 1036 | run_number: 0, |
| 1037 | run_attempt: 1, |
| 1038 | workflow: workflow.name.clone().unwrap_or_default(), |
| 1039 | workflow_path: String::new(), |
| 1040 | server_url: SITE.to_owned(), |
| 1041 | api_url: API.to_owned(), |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | #[allow(clippy::too_many_arguments)] |
| 1046 | async fn record_invalid( |
| 1047 | &self, |
| 1048 | repo: &Repo, |
| 1049 | path: &str, |
| 1050 | source: &str, |
| 1051 | subject: &Subject, |
| 1052 | event_key: &str, |
| 1053 | actor_id: Option<&str>, |
| 1054 | sender: &str, |
| 1055 | problem: &str, |
| 1056 | ) -> Result<()> { |
| 1057 | let row = self.workflow_row(repo, path, path, source).await?; |
| 1058 | self.record_failed_run(repo, &row, subject.git_ref.as_str(), &subject.sha, event_key, actor_id, sender, problem).await |
| 1059 | } |
| 1060 | |
| 1061 | /// Scheduled workflows that run this minute, on the default branch: at |
| 1062 | /// most every five minutes (`cron::Schedule::runs_at`). Not in a |
| 1063 | /// repository with no push for [`crate::SCHEDULE_IDLE_MS`], nor for an |
| 1064 | /// hour after billing refused one of the workflow's scheduled jobs |
| 1065 | /// ([`crate::SCHEDULE_REFUSED_MS`]): no run is made only to be refused. |
| 1066 | pub async fn run_schedules(&self, minute: u64) -> Result<()> { |
| 1067 | let rows = self |
| 1068 | .db |
| 1069 | .prepare( |
| 1070 | "SELECT * FROM workflows WHERE state = 'active' AND crons != '[]' AND error IS NULL |
| 1071 | AND COALESCE(pushed_at, updated_at) >= ? AND (schedule_refused_until IS NULL OR schedule_refused_until <= ?)", |
| 1072 | ) |
| 1073 | .bind(&[rfc3339(minute.saturating_sub(crate::SCHEDULE_IDLE_MS)).into(), rfc3339(minute).into()])? |
| 1074 | .all() |
| 1075 | .await? |
| 1076 | .results::<WorkflowRow>()?; |
| 1077 | for row in rows { |
| 1078 | let crons: Vec<String> = serde_json::from_str(&row.crons).unwrap_or_default(); |
| 1079 | let Some(cron) = crons.iter().find(|cron| g1t_actions::cron::Schedule::parse(cron).is_ok_and(|s| s.runs_at(minute))) else { |
| 1080 | continue; |
| 1081 | }; |
| 1082 | let Ok(workflow) = workflow::parse(&row.source) else { continue }; |
| 1083 | // Schedules wait while a repository is archived; a deleted one is |
| 1084 | // not found. |
| 1085 | let Some((repo, _ws)) = self |
| 1086 | .repo_by_id(&row.repo_id) |
| 1087 | .await? |
| 1088 | .filter(|(repo, _)| !repo.archived()) |
| 1089 | else { |
| 1090 | continue; |
| 1091 | }; |
| 1092 | // Nor while its Actions are off. |
| 1093 | if !self.actions_on(&repo).await? { |
| 1094 | continue; |
| 1095 | } |
| 1096 | // A managed workflow's row may be out of date while its |
| 1097 | // repository waits to be synced again (managed.rs). |
| 1098 | if g1t_actions::managed::is_managed(&row.path) && !self.synced(&repo.id).await? { |
| 1099 | continue; |
| 1100 | } |
| 1101 | let Some(sha) = self.default_head(&repo).await? else { continue }; |
| 1102 | let payload = json!({ "schedule": cron, "repository": payload::repository(&repo), "workflow": row.path }); |
| 1103 | let mut subject = Subject { |
| 1104 | source: Self::repo_path(&repo), |
| 1105 | source_ref: None, |
| 1106 | git_ref: format!("refs/heads/{}", repo.default_branch), |
| 1107 | sha, |
| 1108 | head_ref: None, |
| 1109 | base_ref: None, |
| 1110 | pull: None, |
| 1111 | filter_ref: String::new(), |
| 1112 | paths: None, |
| 1113 | compare: None, |
| 1114 | payload, |
| 1115 | title: format!("Scheduled: {cron}"), |
| 1116 | trusted: true, |
| 1117 | approval: None, |
| 1118 | merge: None, |
| 1119 | }; |
| 1120 | subject.filter_ref = subject.git_ref.clone(); |
| 1121 | let info = self.run_info(&repo, &workflow, "schedule", &subject, &repo.namespace, None); |
| 1122 | self.create_run(NewRun { |
| 1123 | repo: repo.clone(), |
| 1124 | path: row.path.clone(), |
| 1125 | source: row.source.clone(), |
| 1126 | workflow, |
| 1127 | info, |
| 1128 | action: None, |
| 1129 | pull: None, |
| 1130 | title: subject.title.clone(), |
| 1131 | inputs: Map::new(), |
| 1132 | event_key: format!("schedule:{minute}"), |
| 1133 | actor_id: None, |
| 1134 | actor: None, |
| 1135 | trusted: true, |
| 1136 | approval: None, |
| 1137 | head_sha: None, |
| 1138 | }) |
| 1139 | .await?; |
| 1140 | } |
| 1141 | Ok(()) |
| 1142 | } |
| 1143 | |
| 1144 | /// `dispatch`: someone with the Write role runs a workflow that has |
| 1145 | /// `workflow_dispatch`. |
| 1146 | pub async fn dispatch(&self, a: DispatchArgs) -> Result<Outcome<WorkflowRun>> { |
| 1147 | let repo = check!(self.may(&a.actor, &a.repo, Capability::Run).await?); |
| 1148 | if repo.archived() { |
| 1149 | return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name))); |
| 1150 | } |
| 1151 | if !self.actions_on(&repo).await? { |
| 1152 | return Ok(fail(FailureCode::Forbidden, g1t_contracts::actions::actions_disabled_message(&repo.namespace, &repo.name))); |
| 1153 | } |
| 1154 | let Some(ws) = self.workspace_actor(&repo.namespace).await? else { |
| 1155 | return Ok(fail(FailureCode::NotFound, "There is no such workspace.")); |
| 1156 | }; |
| 1157 | let git_ref = a.git_ref.clone().unwrap_or_else(|| repo.default_branch.clone()); |
| 1158 | let full_ref = if git_ref.starts_with("refs/") { |
| 1159 | git_ref.clone() |
| 1160 | } else { |
| 1161 | // A branch if there is one by that name, otherwise a tag. |
| 1162 | let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call( |
| 1163 | &self.repos, |
| 1164 | "branches", |
| 1165 | &g1t_contracts::repos::BranchesArgs { |
| 1166 | path: Self::repo_path(&repo), |
| 1167 | viewer: Some(ws.clone()), |
| 1168 | }, |
| 1169 | ) |
| 1170 | .await?; |
| 1171 | let is_branch = branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == git_ref); |
| 1172 | format!("refs/{}/{git_ref}", if is_branch { "heads" } else { "tags" }) |
| 1173 | }; |
| 1174 | let short = full_ref.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/").to_owned(); |
| 1175 | let read = self.read_for(&repo, &ws, Some(&short)).await?; |
| 1176 | let Some(sha) = read.head.clone() else { |
| 1177 | return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}."))); |
| 1178 | }; |
| 1179 | // A workflow is named by its file (`build.yml`), its path, or its id |
| 1180 | // (`wfl_…`), which stands for the path it was read from. |
| 1181 | let by_id = if a.workflow.starts_with("wfl_") { |
| 1182 | self.db |
| 1183 | .prepare("SELECT * FROM workflows WHERE repo_id = ? AND id = ?") |
| 1184 | .bind(&[repo.id.as_str().into(), a.workflow.as_str().into()])? |
| 1185 | .first::<WorkflowRow>(None) |
| 1186 | .await? |
| 1187 | .map(|row| row.path) |
| 1188 | } else { |
| 1189 | None |
| 1190 | }; |
| 1191 | let named = by_id.as_deref().unwrap_or(&a.workflow); |
| 1192 | let wanted = named.trim_start_matches(".g1t/workflows/"); |
| 1193 | let Some(file) = read.files.iter().find(|file| { |
| 1194 | file.path.rsplit('/').next() == Some(wanted) || file.path == named |
| 1195 | }) else { |
| 1196 | return Ok(fail(FailureCode::NotFound, format!("There is no workflow {wanted} on {short}."))); |
| 1197 | }; |
| 1198 | let workflow = match workflow::parse(&file.source) { |
| 1199 | Ok(workflow) => workflow, |
| 1200 | Err(problem) => return Ok(fail(FailureCode::Invalid, format!("The workflow does not read: {problem}"))), |
| 1201 | }; |
| 1202 | let Some(trigger) = workflow.trigger("workflow_dispatch") else { |
| 1203 | return Ok(fail(FailureCode::Invalid, "That workflow cannot be run by hand: it has no `workflow_dispatch` trigger.")); |
| 1204 | }; |
| 1205 | // `type: environment` names one of the repository's environments. |
| 1206 | let environments = if trigger.inputs.values().any(|spec| spec.get("type").and_then(Value::as_str) == Some("environment")) { |
| 1207 | self.environment_list(&repo.id).await?.into_iter().map(|env| env.name).collect() |
| 1208 | } else { |
| 1209 | Vec::new() |
| 1210 | }; |
| 1211 | let inputs = check!(dispatch_inputs(trigger, &a.inputs, &environments)); |
| 1212 | let payload = json!({ |
| 1213 | // As GitHub gives them here: text, `true` and `false` included. |
| 1214 | // The `inputs` context keeps booleans and numbers. |
| 1215 | "inputs": event_inputs(&inputs), |
| 1216 | "ref": full_ref, |
| 1217 | "repository": payload::repository(&repo), |
| 1218 | "sender": payload::user(&a.actor.username), |
| 1219 | "workflow": file.path, |
| 1220 | }); |
| 1221 | let subject = Subject { |
| 1222 | source: Self::repo_path(&repo), |
| 1223 | source_ref: Some(sha.clone()), |
| 1224 | git_ref: full_ref.clone(), |
| 1225 | sha, |
| 1226 | head_ref: None, |
| 1227 | base_ref: None, |
| 1228 | pull: None, |
| 1229 | filter_ref: full_ref, |
| 1230 | paths: None, |
| 1231 | compare: None, |
| 1232 | payload, |
| 1233 | title: format!("{} run by {}", workflow.display_name(&file.path), a.actor.username), |
| 1234 | trusted: true, |
| 1235 | approval: None, |
| 1236 | merge: None, |
| 1237 | }; |
| 1238 | let info = self.run_info(&repo, &workflow, "workflow_dispatch", &subject, &a.actor.username, Some(&a.actor.id)); |
| 1239 | let created = self |
| 1240 | .create_run(NewRun { |
| 1241 | repo: repo.clone(), |
| 1242 | path: file.path.clone(), |
| 1243 | source: file.source.clone(), |
| 1244 | workflow, |
| 1245 | info, |
| 1246 | action: None, |
| 1247 | pull: None, |
| 1248 | title: subject.title.clone(), |
| 1249 | inputs, |
| 1250 | event_key: format!("dispatch:{}", new_id("dsp", now_ms())), |
| 1251 | actor_id: Some(a.actor.id.clone()), |
| 1252 | actor: Some(a.actor.username.clone()), |
| 1253 | trusted: true, |
| 1254 | approval: None, |
| 1255 | head_sha: None, |
| 1256 | }) |
| 1257 | .await?; |
| 1258 | match created { |
| 1259 | Some(id) => self.run_summary(&id).await, |
| 1260 | None => Ok(fail(FailureCode::Conflict, "It did not start.")), |
| 1261 | } |
| 1262 | } |
| 1263 | |
| 1264 | /// `repository_dispatch`: an outside event, by name, starts the default |
| 1265 | /// branch's workflows that run `on: repository_dispatch` with that type |
| 1266 | /// (or with no `types`). A workflow job's token may send one: this, |
| 1267 | /// with `workflow_dispatch`, is how a workflow starts another. |
| 1268 | pub async fn repository_dispatch(&self, a: RepositoryDispatchArgs) -> Result<Outcome<u32>> { |
| 1269 | let repo = check!(self.may(&a.actor, &a.repo, Capability::Push).await?); |
| 1270 | if repo.archived() { |
| 1271 | return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name))); |
| 1272 | } |
| 1273 | if !self.actions_on(&repo).await? { |
| 1274 | return Ok(fail(FailureCode::Forbidden, g1t_contracts::actions::actions_disabled_message(&repo.namespace, &repo.name))); |
| 1275 | } |
| 1276 | let event_type = a.event_type.trim().to_owned(); |
| 1277 | if event_type.is_empty() || event_type.chars().count() > 100 { |
| 1278 | return Ok(fail(FailureCode::Invalid, "event_type is 1 to 100 characters.")); |
| 1279 | } |
| 1280 | let client_payload = match a.client_payload { |
| 1281 | Value::Null => json!({}), |
| 1282 | Value::Object(map) if map.len() <= 10 => Value::Object(map), |
| 1283 | Value::Object(_) => return Ok(fail(FailureCode::Invalid, "client_payload has at most 10 top-level properties.")), |
| 1284 | _ => return Ok(fail(FailureCode::Invalid, "client_payload is a JSON object.")), |
| 1285 | }; |
| 1286 | if serde_json::to_string(&client_payload).map_or(0, |text| text.len()) > 64 * 1024 { |
| 1287 | return Ok(fail(FailureCode::Invalid, "client_payload is at most 64 KB.")); |
| 1288 | } |
| 1289 | let Some(ws) = self.workspace_actor(&repo.namespace).await? else { |
| 1290 | return Ok(fail(FailureCode::NotFound, "There is no such workspace.")); |
| 1291 | }; |
| 1292 | let read = self.read_for(&repo, &ws, Some(&repo.default_branch)).await?; |
| 1293 | let Some(sha) = read.head.clone() else { |
| 1294 | return Ok(fail(FailureCode::NotFound, "The repository has no default branch to run on yet.")); |
| 1295 | }; |
| 1296 | let git_ref = format!("refs/heads/{}", repo.default_branch); |
| 1297 | let payload = json!({ |
| 1298 | "action": event_type, |
| 1299 | "branch": repo.default_branch, |
| 1300 | "client_payload": client_payload, |
| 1301 | "repository": payload::repository(&repo), |
| 1302 | "sender": payload::user(&a.actor.username), |
| 1303 | }); |
| 1304 | let key = format!("repository_dispatch:{}", new_id("dsp", now_ms())); |
| 1305 | let mut started = 0u32; |
| 1306 | for file in read.files { |
| 1307 | let Ok(workflow) = workflow::parse(&file.source) else { continue }; |
| 1308 | let Some(trigger) = workflow.trigger("repository_dispatch") else { continue }; |
| 1309 | if !trigger.wants_type(Some(&event_type)) || self.disabled(&repo.id, &file.path).await? { |
| 1310 | continue; |
| 1311 | } |
| 1312 | let subject = Subject { |
| 1313 | source: Self::repo_path(&repo), |
| 1314 | source_ref: Some(sha.clone()), |
| 1315 | git_ref: git_ref.clone(), |
| 1316 | sha: sha.clone(), |
| 1317 | head_ref: None, |
| 1318 | base_ref: None, |
| 1319 | pull: None, |
| 1320 | filter_ref: git_ref.clone(), |
| 1321 | paths: None, |
| 1322 | compare: None, |
| 1323 | payload: payload.clone(), |
| 1324 | title: event_type.clone(), |
| 1325 | trusted: true, |
| 1326 | approval: None, |
| 1327 | merge: None, |
| 1328 | }; |
| 1329 | let info = self.run_info(&repo, &workflow, "repository_dispatch", &subject, &a.actor.username, Some(&a.actor.id)); |
| 1330 | let created = self |
| 1331 | .create_run(NewRun { |
| 1332 | repo: repo.clone(), |
| 1333 | path: file.path.clone(), |
| 1334 | source: file.source.clone(), |
| 1335 | workflow, |
| 1336 | info, |
| 1337 | action: Some(event_type.clone()), |
| 1338 | pull: None, |
| 1339 | title: subject.title.clone(), |
| 1340 | inputs: Map::new(), |
| 1341 | event_key: key.clone(), |
| 1342 | actor_id: Some(a.actor.id.clone()), |
| 1343 | actor: Some(a.actor.username.clone()), |
| 1344 | trusted: true, |
| 1345 | approval: None, |
| 1346 | head_sha: None, |
| 1347 | }) |
| 1348 | .await?; |
| 1349 | if created.is_some() { |
| 1350 | started += 1; |
| 1351 | } |
| 1352 | } |
| 1353 | Ok(Outcome::Ok(started)) |
| 1354 | } |
| 1355 | } |
| 1356 | |
| 1357 | #[derive(serde::Deserialize)] |
| 1358 | #[serde(rename_all = "camelCase")] |
| 1359 | pub struct MergeGroupArgs { |
| 1360 | pub repo_id: String, |
| 1361 | pub entry: String, |
| 1362 | pub sha: String, |
| 1363 | pub head_ref: String, |
| 1364 | #[serde(default)] |
| 1365 | pub base_sha: Option<String>, |
| 1366 | pub number: u32, |
| 1367 | #[serde(default)] |
| 1368 | pub ahead: Vec<u32>, |
| 1369 | } |
| 1370 | |
| 1371 | impl MergeGroupArgs { |
| 1372 | fn event_key(&self) -> String { |
| 1373 | format!("merge_group:{}:{}:{}", self.entry, self.head_ref, self.sha) |
| 1374 | } |
| 1375 | } |
| 1376 | |
| 1377 | impl Actions { |
| 1378 | /// `merge_group`: the merge queue built a state and its checks passed. |
| 1379 | /// Starts the workflows that run `on: merge_group` on it, as GitHub's |
| 1380 | /// queue does, and says how many started; the queue waits for their |
| 1381 | /// statuses on that commit. |
| 1382 | pub async fn merge_group(&self, a: MergeGroupArgs) -> Result<Outcome<Value>> { |
| 1383 | let Some((repo, ws)) = self.repo_by_id(&a.repo_id).await? else { |
| 1384 | return Ok(Outcome::Ok(json!({ "runs": 0 }))); |
| 1385 | }; |
| 1386 | if !self.actions_on(&repo).await? { |
| 1387 | return Ok(Outcome::Ok(json!({ "runs": 0 }))); |
| 1388 | } |
| 1389 | let mut read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&a.sha)).await?; |
| 1390 | // A required workflow's check holds the queue too (managed.rs). |
| 1391 | read.files = self.with_managed(&repo, read.files).await?; |
| 1392 | let head_commit = self.commits(&repo, &ws, &a.sha, None).await?.pop(); |
| 1393 | let payload = json!({ |
| 1394 | "action": "checks_requested", |
| 1395 | "merge_group": { |
| 1396 | "head_sha": a.sha, |
| 1397 | "head_ref": a.head_ref, |
| 1398 | "base_sha": a.base_sha, |
| 1399 | "base_ref": format!("refs/heads/{}", repo.default_branch), |
| 1400 | "head_commit": head_commit.as_ref().map(|c| payload::commit(&repo, c)), |
| 1401 | }, |
| 1402 | "repository": payload::repository(&repo), |
| 1403 | "sender": payload::user(&repo.namespace), |
| 1404 | }); |
| 1405 | let mut started = 0u32; |
| 1406 | for file in read.files { |
| 1407 | let Ok(workflow) = workflow::parse(&file.source) else { continue }; |
| 1408 | let Some(trigger) = workflow.trigger("merge_group") else { continue }; |
| 1409 | if !trigger.wants_type(Some("checks_requested")) || (!file.required && self.disabled(&repo.id, &file.path).await?) { |
| 1410 | continue; |
| 1411 | } |
| 1412 | // Branch filters on merge_group name the branch it merges into. |
| 1413 | if trigger.branches.is_set() && !trigger.branches.allows(&repo.default_branch) { |
| 1414 | continue; |
| 1415 | } |
| 1416 | let ahead = if a.ahead.is_empty() { |
| 1417 | String::new() |
| 1418 | } else { |
| 1419 | format!(" after {}", a.ahead.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ")) |
| 1420 | }; |
| 1421 | let subject = Subject { |
| 1422 | source: Self::repo_path(&repo), |
| 1423 | source_ref: Some(a.sha.clone()), |
| 1424 | git_ref: a.head_ref.clone(), |
| 1425 | sha: a.sha.clone(), |
| 1426 | head_ref: None, |
| 1427 | base_ref: Some(repo.default_branch.clone()), |
| 1428 | pull: Some(a.number), |
| 1429 | filter_ref: format!("refs/heads/{}", repo.default_branch), |
| 1430 | paths: None, |
| 1431 | compare: None, |
| 1432 | payload: payload.clone(), |
| 1433 | title: format!("Merge queue: #{}{ahead}", a.number), |
| 1434 | trusted: true, |
| 1435 | approval: None, |
| 1436 | merge: None, |
| 1437 | }; |
| 1438 | let info = self.run_info(&repo, &workflow, "merge_group", &subject, &repo.namespace, None); |
| 1439 | // Its pending status must be registered: the queue waits on |
| 1440 | // this attempt's runs, and one it was never told about would |
| 1441 | // read as finished. A failure fails the dispatch (Work retests). |
| 1442 | let created = self |
| 1443 | .create_run_registered(NewRun { |
| 1444 | repo: repo.clone(), |
| 1445 | path: file.path.clone(), |
| 1446 | source: file.source.clone(), |
| 1447 | workflow, |
| 1448 | info, |
| 1449 | action: Some("checks_requested".to_owned()), |
| 1450 | pull: Some(a.number), |
| 1451 | title: subject.title.clone(), |
| 1452 | inputs: Map::new(), |
| 1453 | event_key: a.event_key(), |
| 1454 | actor_id: None, |
| 1455 | actor: None, |
| 1456 | trusted: true, |
| 1457 | approval: None, |
| 1458 | head_sha: None, |
| 1459 | }) |
| 1460 | .await?; |
| 1461 | // Retried dispatches still await runs already registered for the group. |
| 1462 | let _ = created; |
| 1463 | started += 1; |
| 1464 | } |
| 1465 | Ok(Outcome::Ok(json!({ "runs": started }))) |
| 1466 | } |
| 1467 | } |
| 1468 | |
| 1469 | /// The inputs of a manual run: what was given, checked against the |
| 1470 | /// workflow's declared inputs, with their defaults filled in. An input the |
| 1471 | /// workflow does not declare is refused, as GitHub refuses it. |
| 1472 | /// `environments` are the repository's, for `type: environment`. |
| 1473 | fn dispatch_inputs(trigger: &Trigger, given: &Map<String, Value>, environments: &[String]) -> Outcome<Map<String, Value>> { |
| 1474 | let unexpected: Vec<&String> = given.keys().filter(|name| !trigger.inputs.contains_key(*name)).collect(); |
| 1475 | if !unexpected.is_empty() { |
| 1476 | let names = serde_json::to_string(&unexpected).unwrap_or_default(); |
| 1477 | let declared = if trigger.inputs.is_empty() { |
| 1478 | "The workflow declares no inputs.".to_owned() |
| 1479 | } else { |
| 1480 | format!("The workflow declares {}.", trigger.inputs.keys().map(|name| format!("`{name}`")).collect::<Vec<_>>().join(", ")) |
| 1481 | }; |
| 1482 | return fail(FailureCode::Invalid, format!("Unexpected inputs provided: {names}. {declared}")); |
| 1483 | } |
| 1484 | let mut inputs = Map::new(); |
| 1485 | for (name, spec) in &trigger.inputs { |
| 1486 | let kind = spec.get("type").and_then(Value::as_str).unwrap_or("string"); |
| 1487 | let value = given.get(name).cloned().or_else(|| spec.get("default").cloned()); |
| 1488 | let required = spec.get("required").and_then(Value::as_bool).unwrap_or(false); |
| 1489 | let value = match value { |
| 1490 | Some(Value::Null) | None if required => return fail(FailureCode::Invalid, format!("The input `{name}` is required.")), |
| 1491 | Some(Value::Null) | None => match kind { |
| 1492 | "boolean" => Value::Bool(false), |
| 1493 | _ => Value::String(String::new()), |
| 1494 | }, |
| 1495 | Some(value) => match kind { |
| 1496 | "boolean" => Value::Bool(match &value { |
| 1497 | Value::Bool(flag) => *flag, |
| 1498 | Value::String(text) if text.trim().eq_ignore_ascii_case("true") => true, |
| 1499 | Value::String(text) if text.trim().eq_ignore_ascii_case("false") || text.trim().is_empty() => false, |
| 1500 | _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a boolean: true or false.")), |
| 1501 | }), |
| 1502 | "number" => match &value { |
| 1503 | Value::Number(_) => value, |
| 1504 | Value::String(text) => match number(text) { |
| 1505 | Some(number) => Value::Number(number), |
| 1506 | None => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")), |
| 1507 | }, |
| 1508 | _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")), |
| 1509 | }, |
| 1510 | "choice" => { |
| 1511 | let text = g1t_actions::expr::to_text(&value); |
| 1512 | let options: Vec<String> = |
| 1513 | spec.get("options").and_then(Value::as_array).map(|o| o.iter().map(g1t_actions::expr::to_text).collect()).unwrap_or_default(); |
| 1514 | if !options.is_empty() && !options.contains(&text) { |
| 1515 | return fail(FailureCode::Invalid, format!("The input `{name}` is one of {}.", options.join(", "))); |
| 1516 | } |
| 1517 | Value::String(text) |
| 1518 | } |
| 1519 | "environment" => { |
| 1520 | let text = g1t_actions::expr::to_text(&value); |
| 1521 | let wanted = text.trim().to_ascii_lowercase(); |
| 1522 | if !wanted.is_empty() && !environments.iter().any(|env| env.eq_ignore_ascii_case(&wanted)) { |
| 1523 | return fail( |
| 1524 | FailureCode::Invalid, |
| 1525 | format!("The input `{name}` names an environment, and this repository has none called `{}`.", text.trim()), |
| 1526 | ); |
| 1527 | } |
| 1528 | Value::String(text) |
| 1529 | } |
| 1530 | _ => Value::String(g1t_actions::expr::to_text(&value)), |
| 1531 | }, |
| 1532 | }; |
| 1533 | inputs.insert(name.clone(), value); |
| 1534 | } |
| 1535 | Outcome::Ok(inputs) |
| 1536 | } |
| 1537 | |
| 1538 | /// A number input given as text: a whole number stays one. |
| 1539 | fn number(text: &str) -> Option<serde_json::Number> { |
| 1540 | let text = text.trim(); |
| 1541 | match text.parse::<i64>() { |
| 1542 | Ok(whole) => Some(whole.into()), |
| 1543 | Err(_) => text.parse::<f64>().ok().filter(|n| n.is_finite()).and_then(serde_json::Number::from_f64), |
| 1544 | } |
| 1545 | } |
| 1546 | |
| 1547 | /// A manual run's inputs as `github.event.inputs` gives them: every one as |
| 1548 | /// text, as GitHub's `workflow_dispatch` payload has them. |
| 1549 | fn event_inputs(inputs: &Map<String, Value>) -> Map<String, Value> { |
| 1550 | inputs.iter().map(|(name, value)| (name.clone(), Value::String(g1t_actions::expr::to_text(value)))).collect() |
| 1551 | } |
| 1552 | |
| 1553 | #[cfg(test)] |
| 1554 | mod tests { |
| 1555 | use super::*; |
| 1556 | use g1t_contracts::work::{Pull, g1t_author}; |
| 1557 | |
| 1558 | #[test] |
| 1559 | fn merge_group_retries_deduplicate_but_new_attempts_run_again() { |
| 1560 | let mut args = MergeGroupArgs { repo_id: "repo".into(), entry: "entry".into(), sha: "tested".into(), |
| 1561 | head_ref: "refs/heads/g1t-queue/entry-first".into(), base_sha: Some("base".into()), number: 1, ahead: vec![] }; |
| 1562 | let first = args.event_key(); |
| 1563 | assert_eq!(first, args.event_key()); |
| 1564 | args.head_ref = "refs/heads/g1t-queue/entry-second".into(); |
| 1565 | assert_ne!(first, args.event_key()); |
| 1566 | let second = args.event_key(); |
| 1567 | args.sha = "different".into(); |
| 1568 | assert_ne!(second, args.event_key()); |
| 1569 | } |
| 1570 | |
| 1571 | #[test] |
| 1572 | fn every_event_a_workflow_runs_on_is_sent_to_this_queue() { |
| 1573 | for kind in g1t_contracts::webhooks::EVENT_TYPES { |
| 1574 | if !github_events(kind).is_empty() { |
| 1575 | assert!( |
| 1576 | g1t_contracts::subscribers::routed("SUBSCRIBER_ACTIONS", kind), |
| 1577 | "{kind} starts workflows but is not routed to actions (g1t_contracts::subscribers)" |
| 1578 | ); |
| 1579 | } |
| 1580 | } |
| 1581 | } |
| 1582 | use g1t_contracts::{Membership, PrincipalKind}; |
| 1583 | |
| 1584 | #[test] |
| 1585 | fn a_pushers_email_is_their_noreply_address() { |
| 1586 | assert_eq!(pusher_email(Some("usr_01j9zq4m8x7k2v5n3b6c1d0efg"), "Ada").as_deref(), Some("6c1d0efg+ada@users.noreply.g1t.sh")); |
| 1587 | assert_eq!(pusher_email(Some(AGENT_ID), AGENT_NAME).as_deref(), Some(g1t_contracts::system::EMAIL)); |
| 1588 | assert_eq!(pusher_email(Some("wsp_1"), "acme"), None); |
| 1589 | assert_eq!(pusher_email(None, "acme"), None); |
| 1590 | } |
| 1591 | |
| 1592 | #[test] |
| 1593 | fn a_pull_request_builds_its_merge_commit_and_nothing_while_it_conflicts() { |
| 1594 | let merged = PullMergeRef::Merged { head: "h".into(), base: "b".into(), merge: "m".into() }; |
| 1595 | let conflict = PullMergeRef::Conflict { head: "h".into(), base: "b".into(), paths: vec!["a".into()] }; |
| 1596 | let unavailable = PullMergeRef::Unavailable { reason: "too large".into() }; |
| 1597 | assert_eq!(pull_build("pull_request", Some("synchronize"), &merged), PullBuild::Merge("m".into())); |
| 1598 | assert_eq!(pull_build("pull_request_review", Some("submitted"), &merged), PullBuild::Merge("m".into())); |
| 1599 | // GitHub runs no pull_request workflow while it conflicts. |
| 1600 | for action in ["opened", "synchronize", "reopened", "edited"] { |
| 1601 | assert_eq!(pull_build("pull_request", Some(action), &conflict), PullBuild::Nothing); |
| 1602 | } |
| 1603 | // Closing it, or reviewing it, still runs, on the head. |
| 1604 | assert_eq!(pull_build("pull_request", Some("closed"), &conflict), PullBuild::Head); |
| 1605 | assert_eq!(pull_build("pull_request_review", Some("submitted"), &conflict), PullBuild::Head); |
| 1606 | // What g1t could not merge itself runs on the head. |
| 1607 | assert_eq!(pull_build("pull_request", Some("opened"), &unavailable), PullBuild::Head); |
| 1608 | } |
| 1609 | |
| 1610 | fn repo() -> Repo { |
| 1611 | serde_json::from_value(json!({ |
| 1612 | "id": "rep_1", "namespace": "acme", "name": "web", "isPrivate": true, |
| 1613 | "ownerId": "ws_1", "defaultBranch": "main", "forkOf": null, "createdAt": "" |
| 1614 | })) |
| 1615 | .unwrap() |
| 1616 | } |
| 1617 | |
| 1618 | fn person(id: &str, username: &str) -> User { |
| 1619 | User { id: id.into(), username: username.into(), kind: PrincipalKind::User, ..User::default() } |
| 1620 | } |
| 1621 | |
| 1622 | fn made_for(asker: User) -> Pull { |
| 1623 | serde_json::from_value(json!({ |
| 1624 | "id": "pr_1", "repoId": "rep_1", "number": 14, "item": 12, "title": "Fix it", "body": null, |
| 1625 | "agent": "g1t", "runtime": "hosted", "status": "open", |
| 1626 | "fork": { "namespace": "pulls", "name": "pr_1" }, "forkRepoId": "rep_f", |
| 1627 | "branch": null, "headCommit": "abc", "mergeBase": null, "mergedBy": null, "mergedAt": null, |
| 1628 | "supersededBy": null, "checkStatus": null, |
| 1629 | "author": g1t_author(), "requestedBy": asker, |
| 1630 | "createdAt": "", "updatedAt": "" |
| 1631 | })) |
| 1632 | .unwrap() |
| 1633 | } |
| 1634 | |
| 1635 | #[test] |
| 1636 | fn g1t_s_change_for_someone_is_trusted_as_they_are() { |
| 1637 | // Stored people carry no memberships, so identity is asked about |
| 1638 | // them; being g1t's change gives it nothing more. |
| 1639 | let pull = made_for(person("usr_2", "ana")); |
| 1640 | assert!(!trusted_outright(pull.owner(), &repo())); |
| 1641 | // Someone known to be able to push is trusted at once. |
| 1642 | let mut member = person("usr_1", "syntaqx"); |
| 1643 | member.workspaces.push(Membership::member("acme")); |
| 1644 | let pull = made_for(member); |
| 1645 | assert!(trusted_outright(pull.owner(), &repo())); |
| 1646 | } |
| 1647 | |
| 1648 | #[test] |
| 1649 | fn the_payload_names_g1t_as_its_user_and_who_asked_for_it() { |
| 1650 | let pull = made_for(person("usr_1", "syntaqx")); |
| 1651 | let event = payload::pull(&repo(), &pull); |
| 1652 | assert_eq!(event["user"]["login"], "g1t"); |
| 1653 | assert_eq!(event["user"]["type"], "Bot"); |
| 1654 | assert_eq!(event["requested_by"]["login"], "syntaqx"); |
| 1655 | assert_eq!(event["requested_by"]["type"], "User"); |
| 1656 | assert_eq!(event["item"], 12); |
| 1657 | assert_eq!(event["item_url"], format!("{API}/workspaces/acme/work/12")); |
| 1658 | let as_item = payload::pull_as_item(&repo(), &pull); |
| 1659 | assert_eq!(as_item["user"]["login"], "g1t"); |
| 1660 | assert_eq!(as_item["requested_by"]["login"], "syntaqx"); |
| 1661 | assert!(as_item["pull_request"].is_object()); |
| 1662 | } |
| 1663 | |
| 1664 | #[test] |
| 1665 | fn releases_deployments_and_deleted_comments_read_as_githubs() { |
| 1666 | let release = payload::release( |
| 1667 | &repo(), |
| 1668 | &json!({ "id": "rel_1", "tagName": "v1.2.0", "target": "abc", "name": null, "body": "Notes", "draft": false, |
| 1669 | "prerelease": true, "author": "ana", "createdAt": "2026-10-08T00:00:00Z", "publishedAt": "2026-10-08T00:00:00Z" }), |
| 1670 | ); |
| 1671 | assert_eq!(release["tag_name"], "v1.2.0"); |
| 1672 | assert_eq!(release["name"], "v1.2.0"); |
| 1673 | assert_eq!(release["prerelease"], true); |
| 1674 | assert_eq!(release["author"]["login"], "ana"); |
| 1675 | assert_eq!(release["html_url"], "https://g1t.sh/acme/web/releases/tag/v1.2.0"); |
| 1676 | let deployment = json!({ "id": "dep_1", "sha": "abc", "ref": "main", "environment": "staging", "creator": "ana", |
| 1677 | "production_environment": false, "created_at": "t", "updated_at": "t" }); |
| 1678 | let status = payload::deployment_status(&repo(), &json!({ "id": "dst_1", "state": "success", "environment_url": "https://s.example", "log_url": null, "creator": "g1t", "created_at": "t" }), &deployment); |
| 1679 | assert_eq!(status["state"], "success"); |
| 1680 | assert_eq!(status["environment"], "staging"); |
| 1681 | assert_eq!(status["environment_url"], "https://s.example"); |
| 1682 | assert_eq!(payload::deployment(&repo(), &deployment)["payload"], json!({})); |
| 1683 | let gone = payload::deleted_comment(&repo(), 7, &json!({ "id": "cmt_1", "body": "hi", "author": { "id": "usr_1", "username": "bo" }, "createdAt": "t" }), payload::Thread::Pull); |
| 1684 | assert_eq!(gone["user"]["login"], "bo"); |
| 1685 | assert_eq!(gone["html_url"], "https://g1t.sh/acme/web/pull/7#cmt_1"); |
| 1686 | let on_item = payload::deleted_comment(&repo(), 9, &json!({ "id": "cmt_2", "body": "hi", "author": { "username": "bo" } }), payload::Thread::Item { workspace: "acme" }); |
| 1687 | assert_eq!(on_item["html_url"], "https://g1t.sh/acme/-/work/9#cmt_2"); |
| 1688 | assert_eq!(on_item["item_url"], format!("{API}/workspaces/acme/work/9")); |
| 1689 | assert_eq!(on_item["url"], format!("{API}/workspaces/acme/work/comments/cmt_2")); |
| 1690 | assert!(is_commit("0123456789abcdef0123456789abcdef01234567")); |
| 1691 | assert!(!is_commit("main")); |
| 1692 | } |
| 1693 | |
| 1694 | #[test] |
| 1695 | fn a_pull_request_names_its_own_base_labels_and_milestone() { |
| 1696 | let mut pull = made_for(person("usr_1", "syntaqx")); |
| 1697 | let event = payload::pull(&repo(), &pull); |
| 1698 | assert_eq!(event["base"]["ref"], repo().default_branch); |
| 1699 | pull.base = Some("release/1.x".into()); |
| 1700 | pull.labels = vec!["bug".into()]; |
| 1701 | pull.milestone = Some(g1t_contracts::work::MilestoneRef { number: 2, title: "1.1".into() }); |
| 1702 | let event = payload::pull(&repo(), &pull); |
| 1703 | assert_eq!(event["base"]["ref"], "release/1.x"); |
| 1704 | assert_eq!(event["labels"][0]["name"], "bug"); |
| 1705 | assert!(event["labels"][0]["id"].is_u64()); |
| 1706 | assert_eq!(event["milestone"]["title"], "1.1"); |
| 1707 | let mut labeled = serde_json::json!({ "action": "labeled" }); |
| 1708 | payload::changed(&repo(), &mut labeled, &serde_json::json!({ "label": { "name": "bug", "color": "d73a4a" } })); |
| 1709 | assert_eq!(labeled["label"]["color"], "d73a4a"); |
| 1710 | let mut assigned = serde_json::json!({ "action": "assigned" }); |
| 1711 | payload::changed(&repo(), &mut assigned, &serde_json::json!({ "assignees": ["ana", "bo"], "added": ["bo"] })); |
| 1712 | assert_eq!(assigned["assignee"]["login"], "bo"); |
| 1713 | assert!(nobody_added(&serde_json::json!({ "assignees": ["ana"], "added": [] }))); |
| 1714 | assert!(!nobody_added(&serde_json::json!({ "assignees": ["ana"], "added": ["ana"] }))); |
| 1715 | } |
| 1716 | |
| 1717 | fn event(repo_id: Option<&str>, data: Value) -> Event { |
| 1718 | Event { |
| 1719 | id: "evt_1".into(), |
| 1720 | kind: "work_item.opened".into(), |
| 1721 | source: "work".into(), |
| 1722 | time: "t".into(), |
| 1723 | repo_id: repo_id.map(str::to_owned), |
| 1724 | actor: None, |
| 1725 | data, |
| 1726 | } |
| 1727 | } |
| 1728 | |
| 1729 | #[test] |
| 1730 | fn a_work_item_starts_runs_in_every_repository_it_is_linked_to() { |
| 1731 | // Its origin first, each once. |
| 1732 | let linked = event(Some("rep_1"), json!({ "itemId": "wki_1", "repoIds": ["rep_1", "rep_2", "rep_1"] })); |
| 1733 | assert_eq!(event_repos(&linked), ["rep_1", "rep_2"]); |
| 1734 | // One without an origin is filed under the first it is linked to. |
| 1735 | assert_eq!(event_repos(&event(Some("rep_2"), json!({ "repoIds": ["rep_2", "rep_3"] }))), ["rep_2", "rep_3"]); |
| 1736 | // Linked nowhere: no repository's workflows. |
| 1737 | assert!(event_repos(&event(None, json!({ "repoIds": [] }))).is_empty()); |
| 1738 | // Anything else: the repository it is filed under. |
| 1739 | assert_eq!(event_repos(&event(Some("rep_1"), json!({ "ref": "refs/heads/main" }))), ["rep_1"]); |
| 1740 | assert!(event_repos(&event(None, json!({}))).is_empty()); |
| 1741 | } |
| 1742 | |
| 1743 | fn dispatchable(yaml: &str) -> Trigger { |
| 1744 | workflow::parse(yaml).unwrap().trigger("workflow_dispatch").unwrap().clone() |
| 1745 | } |
| 1746 | |
| 1747 | fn given(value: Value) -> Map<String, Value> { |
| 1748 | value.as_object().unwrap().clone() |
| 1749 | } |
| 1750 | |
| 1751 | const DISPATCH: &str = "on: |
| 1752 | workflow_dispatch: |
| 1753 | inputs: |
| 1754 | dry-run: { type: boolean, default: false } |
| 1755 | count: { type: number, default: 2 } |
| 1756 | target: { type: environment } |
| 1757 | level: { type: choice, options: [low, high], default: low } |
| 1758 | note: { required: false } |
| 1759 | jobs: |
| 1760 | a: |
| 1761 | runs-on: x |
| 1762 | steps: [{ run: 'true' }]"; |
| 1763 | |
| 1764 | #[test] |
| 1765 | fn an_input_the_workflow_does_not_declare_is_refused() { |
| 1766 | let trigger = dispatchable(DISPATCH); |
| 1767 | let Outcome::Fail(failure) = dispatch_inputs(&trigger, &given(json!({ "dry-run": true, "colour": "red" })), &[]) else { |
| 1768 | panic!("an undeclared input was taken"); |
| 1769 | }; |
| 1770 | assert_eq!(failure.code, FailureCode::Invalid); |
| 1771 | assert!(failure.message.starts_with(r#"Unexpected inputs provided: ["colour"]."#), "{}", failure.message); |
| 1772 | assert!(failure.message.contains("`dry-run`")); |
| 1773 | let bare = dispatchable("on: workflow_dispatch\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]"); |
| 1774 | let Outcome::Fail(failure) = dispatch_inputs(&bare, &given(json!({ "x": "1" })), &[]) else { panic!() }; |
| 1775 | assert!(failure.message.contains("declares no inputs")); |
| 1776 | assert!(matches!(dispatch_inputs(&bare, &Map::new(), &[]), Outcome::Ok(inputs) if inputs.is_empty())); |
| 1777 | } |
| 1778 | |
| 1779 | #[test] |
| 1780 | fn inputs_are_typed_and_the_event_has_them_as_text() { |
| 1781 | let trigger = dispatchable(DISPATCH); |
| 1782 | let environments = vec!["staging".to_owned(), "production".to_owned()]; |
| 1783 | let Outcome::Ok(inputs) = dispatch_inputs(&trigger, &given(json!({ "dry-run": "true", "count": "3", "target": "Staging" })), &environments) |
| 1784 | else { |
| 1785 | panic!("refused"); |
| 1786 | }; |
| 1787 | assert_eq!(inputs["dry-run"], json!(true)); |
| 1788 | assert_eq!(inputs["count"], json!(3)); |
| 1789 | assert_eq!(inputs["level"], json!("low")); |
| 1790 | assert_eq!(inputs["note"], json!("")); |
| 1791 | let event = event_inputs(&inputs); |
| 1792 | assert_eq!(event["dry-run"], json!("true")); |
| 1793 | assert_eq!(event["count"], json!("3")); |
| 1794 | assert_eq!(event["target"], json!("Staging")); |
| 1795 | let Outcome::Ok(defaults) = dispatch_inputs(&trigger, &Map::new(), &environments) else { panic!() }; |
| 1796 | assert_eq!(event_inputs(&defaults)["dry-run"], json!("false")); |
| 1797 | assert_eq!(defaults["count"], json!(2)); |
| 1798 | let refused = |value: Value| match dispatch_inputs(&trigger, &given(value), &environments) { |
| 1799 | Outcome::Fail(failure) => failure.message, |
| 1800 | Outcome::Ok(_) => panic!("taken"), |
| 1801 | }; |
| 1802 | assert!(refused(json!({ "target": "qa" })).contains("none called `qa`")); |
| 1803 | assert!(refused(json!({ "dry-run": "yes" })).contains("true or false")); |
| 1804 | assert!(refused(json!({ "count": "many" })).contains("is a number")); |
| 1805 | assert!(refused(json!({ "level": "mid" })).contains("low, high")); |
| 1806 | } |
| 1807 | |
| 1808 | #[test] |
| 1809 | fn create_and_delete_take_no_filters_and_name_their_ref() { |
| 1810 | assert!(unfiltered("create") && unfiltered("delete")); |
| 1811 | assert!(!unfiltered("push") && !unfiltered("pull_request")); |
| 1812 | assert_eq!(branch_or_tag("refs/heads/feature/x"), Some(("branch", "feature/x"))); |
| 1813 | assert_eq!(branch_or_tag("refs/tags/v1.0"), Some(("tag", "v1.0"))); |
| 1814 | assert_eq!(branch_or_tag("refs/heads/g1t-queue/main/3"), None); |
| 1815 | assert_eq!(branch_or_tag("refs/notes/commits"), None); |
| 1816 | // A workflow can name `delete`. It takes no filters, as GitHub's |
| 1817 | // schema says, so writing one is refused when the workflow is read. |
| 1818 | assert!(workflow::parse("on:\n delete:\n branches: [release/*]\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").is_err()); |
| 1819 | let workflow = workflow::parse("on:\n delete:\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap(); |
| 1820 | let trigger = workflow.trigger("delete").unwrap(); |
| 1821 | assert!(trigger.wants_type(None)); |
| 1822 | assert!(!workflow.notes.iter().any(|note| note.severity == workflow::Severity::Unsupported)); |
| 1823 | } |
| 1824 | } |
| 1825 | |
| 1826 | #[cfg(test)] |
| 1827 | mod work_item_runs { |
| 1828 | use rusqlite::Connection; |
| 1829 | use serde_json::{Value, json}; |
| 1830 | |
| 1831 | const MIGRATION: &str = "0024_work_items.sql"; |
| 1832 | |
| 1833 | /// The migrations before [`MIGRATION`], and [`MIGRATION`] itself. |
| 1834 | fn migrations() -> (Vec<String>, String) { |
| 1835 | let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("migrations"); |
| 1836 | let mut names: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); |
| 1837 | names.sort(); |
| 1838 | let read = |name: &str| std::fs::read_to_string(dir.join(name)).unwrap(); |
| 1839 | let before = names.iter().filter(|name| name.as_str() < MIGRATION).map(|name| read(name)).collect(); |
| 1840 | (before, read(MIGRATION)) |
| 1841 | } |
| 1842 | |
| 1843 | fn run(db: &Connection, id: &str, event: &str, info: &Value) { |
| 1844 | db.execute( |
| 1845 | "INSERT INTO runs (id, workflow_id, repo_id, repo, path, name, title, number, event, action, git_ref, sha, status, source, info, event_key, created_at) |
| 1846 | VALUES (?1, 'wfl_1', 'rep_1', 'acme/web', '.g1t/workflows/t.yml', 'T', 'T', 1, ?2, 'opened', 'refs/heads/main', 'abc', 'completed', '', ?3, ?1, 't')", |
| 1847 | rusqlite::params![id, event, info.to_string()], |
| 1848 | ) |
| 1849 | .unwrap(); |
| 1850 | } |
| 1851 | |
| 1852 | fn row(db: &Connection, id: &str) -> (String, Value) { |
| 1853 | db.query_row("SELECT event, info FROM runs WHERE id = ?1", [id], |row| { |
| 1854 | Ok((row.get::<_, String>(0)?, serde_json::from_str(&row.get::<_, String>(1)?).unwrap())) |
| 1855 | }) |
| 1856 | .unwrap() |
| 1857 | } |
| 1858 | |
| 1859 | #[test] |
| 1860 | fn runs_issues_started_name_work_items() { |
| 1861 | let db = Connection::open_in_memory().unwrap(); |
| 1862 | let (before, migration) = migrations(); |
| 1863 | for sql in before { |
| 1864 | db.execute_batch(&sql).unwrap(); |
| 1865 | } |
| 1866 | let issue = json!({ "number": 4, "labels": [{ "name": "bug" }] }); |
| 1867 | run(&db, "run_1", "issues", &json!({ "eventName": "issues", "event": { "action": "opened", "issue": issue } })); |
| 1868 | run(&db, "run_2", "issue_comment", &json!({ "eventName": "issue_comment", "event": { "issue": issue, "comment": { "id": "cmt_1" } } })); |
| 1869 | run(&db, "run_3", "push", &json!({ "eventName": "push", "event": { "ref": "refs/heads/main" } })); |
| 1870 | run(&db, "run_4", "issues", &json!({ "eventName": "issues", "event": {} })); |
| 1871 | db.execute_batch(&migration).unwrap(); |
| 1872 | let (event, info) = row(&db, "run_1"); |
| 1873 | assert_eq!(event, "work_item"); |
| 1874 | assert_eq!(info["eventName"], "work_item"); |
| 1875 | assert_eq!(info["event"]["work_item"], issue, "the item as an object, not text"); |
| 1876 | assert!(info["event"].get("issue").is_none()); |
| 1877 | assert_eq!(info["event"]["action"], "opened"); |
| 1878 | let (event, info) = row(&db, "run_2"); |
| 1879 | assert_eq!(event, "work_item_comment"); |
| 1880 | assert_eq!(info["eventName"], "work_item_comment"); |
| 1881 | assert_eq!(info["event"]["work_item"]["number"], 4); |
| 1882 | assert_eq!(info["event"]["comment"]["id"], "cmt_1"); |
| 1883 | assert_eq!(row(&db, "run_3"), ("push".into(), json!({ "eventName": "push", "event": { "ref": "refs/heads/main" } }))); |
| 1884 | let (event, info) = row(&db, "run_4"); |
| 1885 | assert_eq!(event, "work_item"); |
| 1886 | assert!(info["event"].get("work_item").is_none(), "no item where there was no issue"); |
| 1887 | // Applied again, it changes nothing. |
| 1888 | db.execute_batch(&migration).unwrap(); |
| 1889 | assert_eq!(row(&db, "run_1").0, "work_item"); |
| 1890 | } |
| 1891 | } |