Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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