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,752 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": repo.description,
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 if pushed_default {
780 self.sync(&repo, &ws).await?;
781 }
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 self.read_for(&repo, &ws, subject.source_ref.as_deref()).await?
826 } else if !subject.source.namespace.eq_ignore_ascii_case(WORKING_COPIES) {
827 // A branch of someone's fork, built as its head (there was
828 // no merge commit): the workflows are this repository's, at
829 // the branch it merges into, never the fork's own.
830 self.read_for(&repo, &ws, subject.base_ref.as_deref()).await?
831 } else {
832 // And this repository's managed workflows: they are its own,
833 // whatever the fork's files say (managed.rs).
834 let mut read = self.read_workflows(&subject.source, &ws, subject.source_ref.as_deref()).await?;
835 read.files = self.with_managed(&repo, read.files).await?;
836 read
837 };
838 // A pull request's head runs each workflow once, however many
839 // events say it is there (marked ready, and pushed).
840 let key = match subject.pull {
841 Some(number) if event_name.starts_with("pull_request") && event_name != "pull_request_review" => {
842 // Reopened or made a draft again runs anew, at a head
843 // that may have run before.
844 let phase = match action {
845 Some("closed") => "closed".to_owned(),
846 Some(again @ ("reopened" | "converted_to_draft")) => format!("{again}:{}", event.id),
847 _ => "open".to_owned(),
848 };
849 format!("{event_name}:{number}:{}:{phase}", subject.sha)
850 }
851 _ if event_name == "create" => format!("{}:create", event.id),
852 _ => event.id.clone(),
853 };
854 self.start_matching(&repo, &ws, read, &mut subject, event_name, action, &key, event.actor.as_deref(), &sender)
855 .await?;
856 }
857 Ok(())
858 }
859
860 #[allow(clippy::too_many_arguments)]
861 async fn start_matching(
862 &self,
863 repo: &Repo,
864 ws: &User,
865 read: Read,
866 subject: &mut Subject,
867 event_name: &str,
868 action: Option<&str>,
869 event_key: &str,
870 actor_id: Option<&str>,
871 sender: &str,
872 ) -> Result<()> {
873 let parsed: Vec<_> = read.files.into_iter().map(|file| (workflow::parse(&file.source), file)).collect();
874 // A push some workflow filters by path is compared before any run
875 // starts, so every run's payload lists what its commit changed.
876 let filters_paths = |(parsed, _): &(std::result::Result<Workflow, _>, _)| {
877 parsed.as_ref().ok().and_then(|w: &Workflow| w.trigger(event_name)).is_some_and(|t| t.paths.is_set())
878 };
879 if event_name == "push" && subject.paths.is_none() && parsed.iter().any(filters_paths) {
880 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
881 subject.changed(self.changed_paths(repo, ws, base, head).await?);
882 }
883 for (parsed, file) in parsed {
884 let workflow = match parsed {
885 Ok(workflow) => workflow,
886 Err(problem) => {
887 // A push shows a broken workflow as a failed run, as GitHub does.
888 if event_name == "push" && file.source.contains("on") {
889 self.record_invalid(repo, &file.path, &file.source, subject, event_key, actor_id, sender, &problem)
890 .await?;
891 }
892 continue;
893 }
894 };
895 let Some(trigger) = workflow.trigger(event_name) else { continue };
896 // workflow_run follows the workflows it names.
897 if event_name == "workflow_run" {
898 let followed = subject.payload["workflow_run"]["name"].as_str().unwrap_or_default();
899 if !trigger.workflows.iter().any(|name| name == followed) {
900 continue;
901 }
902 }
903 if !trigger.wants_type(action) || !self.passes(repo, ws, trigger, subject, event_name).await? {
904 continue;
905 }
906 // A workspace's required workflow runs whatever its row says.
907 if !file.required && self.disabled(&repo.id, &file.path).await? {
908 continue;
909 }
910 self.create_run(NewRun {
911 repo: repo.clone(),
912 path: file.path,
913 source: file.source,
914 info: self.run_info(repo, &workflow, event_name, subject, sender, actor_id),
915 workflow,
916 action: action.map(str::to_owned),
917 pull: subject.pull,
918 title: subject.title.clone(),
919 inputs: Map::new(),
920 event_key: event_key.to_owned(),
921 actor_id: actor_id.map(str::to_owned),
922 actor: Some(sender.to_owned()),
923 trusted: subject.trusted,
924 approval: subject.approval.clone(),
925 head_sha: subject.merge.as_ref().map(|_| subject.sha.clone()),
926 })
927 .await?;
928 }
929 Ok(())
930 }
931
932 /// Whether the branch, tag and path filters let the event through.
933 async fn passes(&self, repo: &Repo, ws: &User, trigger: &Trigger, subject: &mut Subject, event_name: &str) -> Result<bool> {
934 // GitHub takes no filters on these: a workflow with `branches` on
935 // `create` or `delete` still runs for every branch and tag.
936 if unfiltered(event_name) {
937 return Ok(true);
938 }
939 let git_ref = subject.filter_ref.as_str();
940 if let Some(tag) = git_ref.strip_prefix("refs/tags/") {
941 // A tag push runs a workflow that filters tags, or filters nothing.
942 if trigger.tags.is_set() {
943 if !trigger.tags.allows(tag) {
944 return Ok(false);
945 }
946 } else if trigger.branches.is_set() {
947 return Ok(false);
948 }
949 // Paths are not checked for tags, as on GitHub.
950 return Ok(true);
951 }
952 let branch = git_ref.strip_prefix("refs/heads/").unwrap_or(git_ref);
953 if trigger.branches.is_set() {
954 if !trigger.branches.allows(branch) {
955 return Ok(false);
956 }
957 } else if event_name == "push" && trigger.tags.is_set() {
958 return Ok(false);
959 }
960 if trigger.paths.is_set() {
961 if subject.paths.is_none() {
962 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
963 subject.changed(self.changed_paths(repo, ws, base, head).await?);
964 }
965 if !trigger.paths.allows_paths(subject.paths.as_deref().unwrap_or_default()) {
966 return Ok(false);
967 }
968 }
969 Ok(true)
970 }
971
972 async fn disabled(&self, repo_id: &str, path: &str) -> Result<bool> {
973 let row = self
974 .db
975 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND path = ?")
976 .bind(&[repo_id.into(), path.into()])?
977 .first::<WorkflowRow>(None)
978 .await?;
979 Ok(row.is_some_and(|row| row.state == "disabled"))
980 }
981
982 fn run_info(&self, repo: &Repo, workflow: &Workflow, event_name: &str, subject: &Subject, sender: &str, actor_id: Option<&str>) -> RunInfo {
983 RunInfo {
984 repository: format!("{}/{}", repo.namespace, repo.name),
985 repository_id: repo.id.clone(),
986 default_branch: repo.default_branch.clone(),
987 event_name: event_name.to_owned(),
988 event: subject.payload.clone(),
989 git_ref: subject.git_ref.clone(),
990 sha: subject.merge.clone().unwrap_or_else(|| subject.sha.clone()),
991 head_ref: subject.head_ref.clone(),
992 base_ref: subject.base_ref.clone(),
993 actor: sender.to_owned(),
994 actor_id: actor_id.unwrap_or_default().to_owned(),
995 triggering_actor: sender.to_owned(),
996 run_id: String::new(),
997 run_number: 0,
998 run_attempt: 1,
999 workflow: workflow.name.clone().unwrap_or_default(),
1000 workflow_path: String::new(),
1001 server_url: SITE.to_owned(),
1002 api_url: API.to_owned(),
1003 }
1004 }
1005
1006 #[allow(clippy::too_many_arguments)]
1007 async fn record_invalid(
1008 &self,
1009 repo: &Repo,
1010 path: &str,
1011 source: &str,
1012 subject: &Subject,
1013 event_key: &str,
1014 actor_id: Option<&str>,
1015 sender: &str,
1016 problem: &str,
1017 ) -> Result<()> {
1018 let row = self.workflow_row(repo, path, path, source).await?;
1019 self.record_failed_run(repo, &row, subject.git_ref.as_str(), &subject.sha, event_key, actor_id, sender, problem).await
1020 }
1021
1022 /// Scheduled workflows that run this minute, on the default branch: at
1023 /// most every five minutes (`cron::Schedule::runs_at`). Not in a
1024 /// repository with no push for [`crate::SCHEDULE_IDLE_MS`], nor for an
1025 /// hour after billing refused one of the workflow's scheduled jobs
1026 /// ([`crate::SCHEDULE_REFUSED_MS`]): no run is made only to be refused.
1027 pub async fn run_schedules(&self, minute: u64) -> Result<()> {
1028 let rows = self
1029 .db
1030 .prepare(
1031 "SELECT * FROM workflows WHERE state = 'active' AND crons != '[]' AND error IS NULL
1032 AND COALESCE(pushed_at, updated_at) >= ? AND (schedule_refused_until IS NULL OR schedule_refused_until <= ?)",
1033 )
1034 .bind(&[rfc3339(minute.saturating_sub(crate::SCHEDULE_IDLE_MS)).into(), rfc3339(minute).into()])?
1035 .all()
1036 .await?
1037 .results::<WorkflowRow>()?;
1038 for row in rows {
1039 let crons: Vec<String> = serde_json::from_str(&row.crons).unwrap_or_default();
1040 let Some(cron) = crons.iter().find(|cron| g1t_actions::cron::Schedule::parse(cron).is_ok_and(|s| s.runs_at(minute))) else {
1041 continue;
1042 };
1043 let Ok(workflow) = workflow::parse(&row.source) else { continue };
1044 // Schedules wait while a repository is archived; a deleted one is
1045 // not found.
1046 let Some((repo, _ws)) = self
1047 .repo_by_id(&row.repo_id)
1048 .await?
1049 .filter(|(repo, _)| !repo.archived())
1050 else {
1051 continue;
1052 };
1053 // Nor while its Actions are off.
1054 if !self.actions_on(&repo).await? {
1055 continue;
1056 }
1057 // A managed workflow's row may be out of date while its
1058 // repository waits to be synced again (managed.rs).
1059 if g1t_actions::managed::is_managed(&row.path) && !self.synced(&repo.id).await? {
1060 continue;
1061 }
1062 let Some(sha) = self.default_head(&repo).await? else { continue };
1063 let payload = json!({ "schedule": cron, "repository": payload::repository(&repo), "workflow": row.path });
1064 let mut subject = Subject {
1065 source: Self::repo_path(&repo),
1066 source_ref: None,
1067 git_ref: format!("refs/heads/{}", repo.default_branch),
1068 sha,
1069 head_ref: None,
1070 base_ref: None,
1071 pull: None,
1072 filter_ref: String::new(),
1073 paths: None,
1074 compare: None,
1075 payload,
1076 title: format!("Scheduled: {cron}"),
1077 trusted: true,
1078 approval: None,
1079 merge: None,
1080 };
1081 subject.filter_ref = subject.git_ref.clone();
1082 let info = self.run_info(&repo, &workflow, "schedule", &subject, &repo.namespace, None);
1083 self.create_run(NewRun {
1084 repo: repo.clone(),
1085 path: row.path.clone(),
1086 source: row.source.clone(),
1087 workflow,
1088 info,
1089 action: None,
1090 pull: None,
1091 title: subject.title.clone(),
1092 inputs: Map::new(),
1093 event_key: format!("schedule:{minute}"),
1094 actor_id: None,
1095 actor: None,
1096 trusted: true,
1097 approval: None,
1098 head_sha: None,
1099 })
1100 .await?;
1101 }
1102 Ok(())
1103 }
1104
1105 /// `dispatch`: someone with the Write role runs a workflow that has
1106 /// `workflow_dispatch`.
1107 pub async fn dispatch(&self, a: DispatchArgs) -> Result<Outcome<WorkflowRun>> {
1108 let repo = check!(self.may(&a.actor, &a.repo, Capability::Run).await?);
1109 if repo.archived() {
1110 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
1111 }
1112 if !self.actions_on(&repo).await? {
1113 return Ok(fail(FailureCode::Forbidden, g1t_contracts::actions::actions_disabled_message(&repo.namespace, &repo.name)));
1114 }
1115 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
1116 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
1117 };
1118 let git_ref = a.git_ref.clone().unwrap_or_else(|| repo.default_branch.clone());
1119 let full_ref = if git_ref.starts_with("refs/") {
1120 git_ref.clone()
1121 } else {
1122 // A branch if there is one by that name, otherwise a tag.
1123 let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call(
1124 &self.repos,
1125 "branches",
1126 &g1t_contracts::repos::BranchesArgs {
1127 path: Self::repo_path(&repo),
1128 viewer: Some(ws.clone()),
1129 },
1130 )
1131 .await?;
1132 let is_branch = branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == git_ref);
1133 format!("refs/{}/{git_ref}", if is_branch { "heads" } else { "tags" })
1134 };
1135 let short = full_ref.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/").to_owned();
1136 let read = self.read_for(&repo, &ws, Some(&short)).await?;
1137 let Some(sha) = read.head.clone() else {
1138 return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}.")));
1139 };
1140 // A workflow is named by its file (`build.yml`), its path, or its id
1141 // (`wfl_…`), which stands for the path it was read from.
1142 let by_id = if a.workflow.starts_with("wfl_") {
1143 self.db
1144 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND id = ?")
1145 .bind(&[repo.id.as_str().into(), a.workflow.as_str().into()])?
1146 .first::<WorkflowRow>(None)
1147 .await?
1148 .map(|row| row.path)
1149 } else {
1150 None
1151 };
1152 let named = by_id.as_deref().unwrap_or(&a.workflow);
1153 let wanted = named.trim_start_matches(".g1t/workflows/");
1154 let Some(file) = read.files.iter().find(|file| {
1155 file.path.rsplit('/').next() == Some(wanted) || file.path == named
1156 }) else {
1157 return Ok(fail(FailureCode::NotFound, format!("There is no workflow {wanted} on {short}.")));
1158 };
1159 let workflow = match workflow::parse(&file.source) {
1160 Ok(workflow) => workflow,
1161 Err(problem) => return Ok(fail(FailureCode::Invalid, format!("The workflow does not read: {problem}"))),
1162 };
1163 let Some(trigger) = workflow.trigger("workflow_dispatch") else {
1164 return Ok(fail(FailureCode::Invalid, "That workflow cannot be run by hand: it has no `workflow_dispatch` trigger."));
1165 };
1166 // `type: environment` names one of the repository's environments.
1167 let environments = if trigger.inputs.values().any(|spec| spec.get("type").and_then(Value::as_str) == Some("environment")) {
1168 self.environment_list(&repo.id).await?.into_iter().map(|env| env.name).collect()
1169 } else {
1170 Vec::new()
1171 };
1172 let inputs = check!(dispatch_inputs(trigger, &a.inputs, &environments));
1173 let payload = json!({
1174 // As GitHub gives them here: text, `true` and `false` included.
1175 // The `inputs` context keeps booleans and numbers.
1176 "inputs": event_inputs(&inputs),
1177 "ref": full_ref,
1178 "repository": payload::repository(&repo),
1179 "sender": payload::user(&a.actor.username),
1180 "workflow": file.path,
1181 });
1182 let subject = Subject {
1183 source: Self::repo_path(&repo),
1184 source_ref: Some(sha.clone()),
1185 git_ref: full_ref.clone(),
1186 sha,
1187 head_ref: None,
1188 base_ref: None,
1189 pull: None,
1190 filter_ref: full_ref,
1191 paths: None,
1192 compare: None,
1193 payload,
1194 title: format!("{} run by {}", workflow.display_name(&file.path), a.actor.username),
1195 trusted: true,
1196 approval: None,
1197 merge: None,
1198 };
1199 let info = self.run_info(&repo, &workflow, "workflow_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
1200 let created = self
1201 .create_run(NewRun {
1202 repo: repo.clone(),
1203 path: file.path.clone(),
1204 source: file.source.clone(),
1205 workflow,
1206 info,
1207 action: None,
1208 pull: None,
1209 title: subject.title.clone(),
1210 inputs,
1211 event_key: format!("dispatch:{}", new_id("dsp", now_ms())),
1212 actor_id: Some(a.actor.id.clone()),
1213 actor: Some(a.actor.username.clone()),
1214 trusted: true,
1215 approval: None,
1216 head_sha: None,
1217 })
1218 .await?;
1219 match created {
1220 Some(id) => self.run_summary(&id).await,
1221 None => Ok(fail(FailureCode::Conflict, "It did not start.")),
1222 }
1223 }
1224
1225 /// `repository_dispatch`: an outside event, by name, starts the default
1226 /// branch's workflows that run `on: repository_dispatch` with that type
1227 /// (or with no `types`). A workflow job's token may send one: this,
1228 /// with `workflow_dispatch`, is how a workflow starts another.
1229 pub async fn repository_dispatch(&self, a: RepositoryDispatchArgs) -> Result<Outcome<u32>> {
1230 let repo = check!(self.may(&a.actor, &a.repo, Capability::Push).await?);
1231 if repo.archived() {
1232 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
1233 }
1234 if !self.actions_on(&repo).await? {
1235 return Ok(fail(FailureCode::Forbidden, g1t_contracts::actions::actions_disabled_message(&repo.namespace, &repo.name)));
1236 }
1237 let event_type = a.event_type.trim().to_owned();
1238 if event_type.is_empty() || event_type.chars().count() > 100 {
1239 return Ok(fail(FailureCode::Invalid, "event_type is 1 to 100 characters."));
1240 }
1241 let client_payload = match a.client_payload {
1242 Value::Null => json!({}),
1243 Value::Object(map) if map.len() <= 10 => Value::Object(map),
1244 Value::Object(_) => return Ok(fail(FailureCode::Invalid, "client_payload has at most 10 top-level properties.")),
1245 _ => return Ok(fail(FailureCode::Invalid, "client_payload is a JSON object.")),
1246 };
1247 if serde_json::to_string(&client_payload).map_or(0, |text| text.len()) > 64 * 1024 {
1248 return Ok(fail(FailureCode::Invalid, "client_payload is at most 64 KB."));
1249 }
1250 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
1251 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
1252 };
1253 let read = self.read_for(&repo, &ws, Some(&repo.default_branch)).await?;
1254 let Some(sha) = read.head.clone() else {
1255 return Ok(fail(FailureCode::NotFound, "The repository has no default branch to run on yet."));
1256 };
1257 let git_ref = format!("refs/heads/{}", repo.default_branch);
1258 let payload = json!({
1259 "action": event_type,
1260 "branch": repo.default_branch,
1261 "client_payload": client_payload,
1262 "repository": payload::repository(&repo),
1263 "sender": payload::user(&a.actor.username),
1264 });
1265 let key = format!("repository_dispatch:{}", new_id("dsp", now_ms()));
1266 let mut started = 0u32;
1267 for file in read.files {
1268 let Ok(workflow) = workflow::parse(&file.source) else { continue };
1269 let Some(trigger) = workflow.trigger("repository_dispatch") else { continue };
1270 if !trigger.wants_type(Some(&event_type)) || self.disabled(&repo.id, &file.path).await? {
1271 continue;
1272 }
1273 let subject = Subject {
1274 source: Self::repo_path(&repo),
1275 source_ref: Some(sha.clone()),
1276 git_ref: git_ref.clone(),
1277 sha: sha.clone(),
1278 head_ref: None,
1279 base_ref: None,
1280 pull: None,
1281 filter_ref: git_ref.clone(),
1282 paths: None,
1283 compare: None,
1284 payload: payload.clone(),
1285 title: event_type.clone(),
1286 trusted: true,
1287 approval: None,
1288 merge: None,
1289 };
1290 let info = self.run_info(&repo, &workflow, "repository_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
1291 let created = self
1292 .create_run(NewRun {
1293 repo: repo.clone(),
1294 path: file.path.clone(),
1295 source: file.source.clone(),
1296 workflow,
1297 info,
1298 action: Some(event_type.clone()),
1299 pull: None,
1300 title: subject.title.clone(),
1301 inputs: Map::new(),
1302 event_key: key.clone(),
1303 actor_id: Some(a.actor.id.clone()),
1304 actor: Some(a.actor.username.clone()),
1305 trusted: true,
1306 approval: None,
1307 head_sha: None,
1308 })
1309 .await?;
1310 if created.is_some() {
1311 started += 1;
1312 }
1313 }
1314 Ok(Outcome::Ok(started))
1315 }
1316}
1317
1318#[derive(serde::Deserialize)]
1319#[serde(rename_all = "camelCase")]
1320pub struct MergeGroupArgs {
1321 pub repo_id: String,
1322 pub entry: String,
1323 pub sha: String,
1324 pub head_ref: String,
1325 #[serde(default)]
1326 pub base_sha: Option<String>,
1327 pub number: u32,
1328 #[serde(default)]
1329 pub ahead: Vec<u32>,
1330}
1331
1332impl MergeGroupArgs {
1333 fn event_key(&self) -> String {
1334 format!("merge_group:{}:{}:{}", self.entry, self.head_ref, self.sha)
1335 }
1336}
1337
1338impl Actions {
1339 /// `merge_group`: the merge queue built a state and its checks passed.
1340 /// Starts the workflows that run `on: merge_group` on it, as GitHub's
1341 /// queue does, and says how many started; the queue waits for their
1342 /// statuses on that commit.
1343 pub async fn merge_group(&self, a: MergeGroupArgs) -> Result<Outcome<Value>> {
1344 let Some((repo, ws)) = self.repo_by_id(&a.repo_id).await? else {
1345 return Ok(Outcome::Ok(json!({ "runs": 0 })));
1346 };
1347 if !self.actions_on(&repo).await? {
1348 return Ok(Outcome::Ok(json!({ "runs": 0 })));
1349 }
1350 let mut read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&a.sha)).await?;
1351 // A required workflow's check holds the queue too (managed.rs).
1352 read.files = self.with_managed(&repo, read.files).await?;
1353 let head_commit = self.commits(&repo, &ws, &a.sha, None).await?.pop();
1354 let payload = json!({
1355 "action": "checks_requested",
1356 "merge_group": {
1357 "head_sha": a.sha,
1358 "head_ref": a.head_ref,
1359 "base_sha": a.base_sha,
1360 "base_ref": format!("refs/heads/{}", repo.default_branch),
1361 "head_commit": head_commit.as_ref().map(|c| payload::commit(&repo, c)),
1362 },
1363 "repository": payload::repository(&repo),
1364 "sender": payload::user(&repo.namespace),
1365 });
1366 let mut started = 0u32;
1367 for file in read.files {
1368 let Ok(workflow) = workflow::parse(&file.source) else { continue };
1369 let Some(trigger) = workflow.trigger("merge_group") else { continue };
1370 if !trigger.wants_type(Some("checks_requested")) || (!file.required && self.disabled(&repo.id, &file.path).await?) {
1371 continue;
1372 }
1373 // Branch filters on merge_group name the branch it merges into.
1374 if trigger.branches.is_set() && !trigger.branches.allows(&repo.default_branch) {
1375 continue;
1376 }
1377 let ahead = if a.ahead.is_empty() {
1378 String::new()
1379 } else {
1380 format!(" after {}", a.ahead.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", "))
1381 };
1382 let subject = Subject {
1383 source: Self::repo_path(&repo),
1384 source_ref: Some(a.sha.clone()),
1385 git_ref: a.head_ref.clone(),
1386 sha: a.sha.clone(),
1387 head_ref: None,
1388 base_ref: Some(repo.default_branch.clone()),
1389 pull: Some(a.number),
1390 filter_ref: format!("refs/heads/{}", repo.default_branch),
1391 paths: None,
1392 compare: None,
1393 payload: payload.clone(),
1394 title: format!("Merge queue: #{}{ahead}", a.number),
1395 trusted: true,
1396 approval: None,
1397 merge: None,
1398 };
1399 let info = self.run_info(&repo, &workflow, "merge_group", &subject, &repo.namespace, None);
1400 // Its pending status must be registered: the queue waits on
1401 // this attempt's runs, and one it was never told about would
1402 // read as finished. A failure fails the dispatch (Work retests).
1403 let created = self
1404 .create_run_registered(NewRun {
1405 repo: repo.clone(),
1406 path: file.path.clone(),
1407 source: file.source.clone(),
1408 workflow,
1409 info,
1410 action: Some("checks_requested".to_owned()),
1411 pull: Some(a.number),
1412 title: subject.title.clone(),
1413 inputs: Map::new(),
1414 event_key: a.event_key(),
1415 actor_id: None,
1416 actor: None,
1417 trusted: true,
1418 approval: None,
1419 head_sha: None,
1420 })
1421 .await?;
1422 // Retried dispatches still await runs already registered for the group.
1423 let _ = created;
1424 started += 1;
1425 }
1426 Ok(Outcome::Ok(json!({ "runs": started })))
1427 }
1428}
1429
1430/// The inputs of a manual run: what was given, checked against the
1431/// workflow's declared inputs, with their defaults filled in. An input the
1432/// workflow does not declare is refused, as GitHub refuses it.
1433/// `environments` are the repository's, for `type: environment`.
1434fn dispatch_inputs(trigger: &Trigger, given: &Map<String, Value>, environments: &[String]) -> Outcome<Map<String, Value>> {
1435 let unexpected: Vec<&String> = given.keys().filter(|name| !trigger.inputs.contains_key(*name)).collect();
1436 if !unexpected.is_empty() {
1437 let names = serde_json::to_string(&unexpected).unwrap_or_default();
1438 let declared = if trigger.inputs.is_empty() {
1439 "The workflow declares no inputs.".to_owned()
1440 } else {
1441 format!("The workflow declares {}.", trigger.inputs.keys().map(|name| format!("`{name}`")).collect::<Vec<_>>().join(", "))
1442 };
1443 return fail(FailureCode::Invalid, format!("Unexpected inputs provided: {names}. {declared}"));
1444 }
1445 let mut inputs = Map::new();
1446 for (name, spec) in &trigger.inputs {
1447 let kind = spec.get("type").and_then(Value::as_str).unwrap_or("string");
1448 let value = given.get(name).cloned().or_else(|| spec.get("default").cloned());
1449 let required = spec.get("required").and_then(Value::as_bool).unwrap_or(false);
1450 let value = match value {
1451 Some(Value::Null) | None if required => return fail(FailureCode::Invalid, format!("The input `{name}` is required.")),
1452 Some(Value::Null) | None => match kind {
1453 "boolean" => Value::Bool(false),
1454 _ => Value::String(String::new()),
1455 },
1456 Some(value) => match kind {
1457 "boolean" => Value::Bool(match &value {
1458 Value::Bool(flag) => *flag,
1459 Value::String(text) if text.trim().eq_ignore_ascii_case("true") => true,
1460 Value::String(text) if text.trim().eq_ignore_ascii_case("false") || text.trim().is_empty() => false,
1461 _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a boolean: true or false.")),
1462 }),
1463 "number" => match &value {
1464 Value::Number(_) => value,
1465 Value::String(text) => match number(text) {
1466 Some(number) => Value::Number(number),
1467 None => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
1468 },
1469 _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
1470 },
1471 "choice" => {
1472 let text = g1t_actions::expr::to_text(&value);
1473 let options: Vec<String> =
1474 spec.get("options").and_then(Value::as_array).map(|o| o.iter().map(g1t_actions::expr::to_text).collect()).unwrap_or_default();
1475 if !options.is_empty() && !options.contains(&text) {
1476 return fail(FailureCode::Invalid, format!("The input `{name}` is one of {}.", options.join(", ")));
1477 }
1478 Value::String(text)
1479 }
1480 "environment" => {
1481 let text = g1t_actions::expr::to_text(&value);
1482 let wanted = text.trim().to_ascii_lowercase();
1483 if !wanted.is_empty() && !environments.iter().any(|env| env.eq_ignore_ascii_case(&wanted)) {
1484 return fail(
1485 FailureCode::Invalid,
1486 format!("The input `{name}` names an environment, and this repository has none called `{}`.", text.trim()),
1487 );
1488 }
1489 Value::String(text)
1490 }
1491 _ => Value::String(g1t_actions::expr::to_text(&value)),
1492 },
1493 };
1494 inputs.insert(name.clone(), value);
1495 }
1496 Outcome::Ok(inputs)
1497}
1498
1499/// A number input given as text: a whole number stays one.
1500fn number(text: &str) -> Option<serde_json::Number> {
1501 let text = text.trim();
1502 match text.parse::<i64>() {
1503 Ok(whole) => Some(whole.into()),
1504 Err(_) => text.parse::<f64>().ok().filter(|n| n.is_finite()).and_then(serde_json::Number::from_f64),
1505 }
1506}
1507
1508/// A manual run's inputs as `github.event.inputs` gives them: every one as
1509/// text, as GitHub's `workflow_dispatch` payload has them.
1510fn event_inputs(inputs: &Map<String, Value>) -> Map<String, Value> {
1511 inputs.iter().map(|(name, value)| (name.clone(), Value::String(g1t_actions::expr::to_text(value)))).collect()
1512}
1513
1514#[cfg(test)]
1515mod tests {
1516 use super::*;
1517 use g1t_contracts::work::{Pull, g1t_author};
1518
1519 #[test]
1520 fn merge_group_retries_deduplicate_but_new_attempts_run_again() {
1521 let mut args = MergeGroupArgs { repo_id: "repo".into(), entry: "entry".into(), sha: "tested".into(),
1522 head_ref: "refs/heads/g1t-queue/entry-first".into(), base_sha: Some("base".into()), number: 1, ahead: vec![] };
1523 let first = args.event_key();
1524 assert_eq!(first, args.event_key());
1525 args.head_ref = "refs/heads/g1t-queue/entry-second".into();
1526 assert_ne!(first, args.event_key());
1527 let second = args.event_key();
1528 args.sha = "different".into();
1529 assert_ne!(second, args.event_key());
1530 }
1531
1532 #[test]
1533 fn every_event_a_workflow_runs_on_is_sent_to_this_queue() {
1534 for kind in g1t_contracts::webhooks::EVENT_TYPES {
1535 if !github_events(kind).is_empty() {
1536 assert!(
1537 g1t_contracts::subscribers::routed("SUBSCRIBER_ACTIONS", kind),
1538 "{kind} starts workflows but is not routed to actions (g1t_contracts::subscribers)"
1539 );
1540 }
1541 }
1542 }
1543 use g1t_contracts::{Membership, PrincipalKind};
1544
1545 #[test]
1546 fn a_pushers_email_is_their_noreply_address() {
1547 assert_eq!(pusher_email(Some("usr_01j9zq4m8x7k2v5n3b6c1d0efg"), "Ada").as_deref(), Some("6c1d0efg+ada@users.noreply.g1t.sh"));
1548 assert_eq!(pusher_email(Some(AGENT_ID), AGENT_NAME).as_deref(), Some(g1t_contracts::system::EMAIL));
1549 assert_eq!(pusher_email(Some("wsp_1"), "acme"), None);
1550 assert_eq!(pusher_email(None, "acme"), None);
1551 }
1552
1553 #[test]
1554 fn a_pull_request_builds_its_merge_commit_and_nothing_while_it_conflicts() {
1555 let merged = PullMergeRef::Merged { head: "h".into(), base: "b".into(), merge: "m".into() };
1556 let conflict = PullMergeRef::Conflict { head: "h".into(), base: "b".into(), paths: vec!["a".into()] };
1557 let unavailable = PullMergeRef::Unavailable { reason: "too large".into() };
1558 assert_eq!(pull_build("pull_request", Some("synchronize"), &merged), PullBuild::Merge("m".into()));
1559 assert_eq!(pull_build("pull_request_review", Some("submitted"), &merged), PullBuild::Merge("m".into()));
1560 // GitHub runs no pull_request workflow while it conflicts.
1561 for action in ["opened", "synchronize", "reopened", "edited"] {
1562 assert_eq!(pull_build("pull_request", Some(action), &conflict), PullBuild::Nothing);
1563 }
1564 // Closing it, or reviewing it, still runs, on the head.
1565 assert_eq!(pull_build("pull_request", Some("closed"), &conflict), PullBuild::Head);
1566 assert_eq!(pull_build("pull_request_review", Some("submitted"), &conflict), PullBuild::Head);
1567 // What g1t could not merge itself runs on the head.
1568 assert_eq!(pull_build("pull_request", Some("opened"), &unavailable), PullBuild::Head);
1569 }
1570
1571 fn repo() -> Repo {
1572 serde_json::from_value(json!({
1573 "id": "rep_1", "namespace": "acme", "name": "web", "description": null, "isPrivate": true,
1574 "ownerId": "ws_1", "defaultBranch": "main", "forkOf": null, "createdAt": ""
1575 }))
1576 .unwrap()
1577 }
1578
1579 fn person(id: &str, username: &str) -> User {
1580 User { id: id.into(), username: username.into(), kind: PrincipalKind::User, ..User::default() }
1581 }
1582
1583 fn made_for(asker: User) -> Pull {
1584 serde_json::from_value(json!({
1585 "id": "pr_1", "repoId": "rep_1", "number": 14, "issue": 12, "title": "Fix it", "body": null,
1586 "agent": "g1t", "runtime": "hosted", "status": "open",
1587 "fork": { "namespace": "pulls", "name": "pr_1" }, "forkRepoId": "rep_f",
1588 "branch": null, "headCommit": "abc", "mergeBase": null, "mergedBy": null, "mergedAt": null,
1589 "supersededBy": null, "checkStatus": null,
1590 "author": g1t_author(), "requestedBy": asker,
1591 "createdAt": "", "updatedAt": ""
1592 }))
1593 .unwrap()
1594 }
1595
1596 #[test]
1597 fn g1t_s_change_for_someone_is_trusted_as_they_are() {
1598 // Stored people carry no memberships, so identity is asked about
1599 // them; being g1t's change gives it nothing more.
1600 let pull = made_for(person("usr_2", "ana"));
1601 assert!(!trusted_outright(pull.owner(), &repo()));
1602 // Someone known to be able to push is trusted at once.
1603 let mut member = person("usr_1", "syntaqx");
1604 member.workspaces.push(Membership::member("acme"));
1605 let pull = made_for(member);
1606 assert!(trusted_outright(pull.owner(), &repo()));
1607 }
1608
1609 #[test]
1610 fn the_payload_names_g1t_as_its_user_and_who_asked_for_it() {
1611 let pull = made_for(person("usr_1", "syntaqx"));
1612 let event = payload::pull(&repo(), &pull);
1613 assert_eq!(event["user"]["login"], "g1t");
1614 assert_eq!(event["user"]["type"], "Bot");
1615 assert_eq!(event["requested_by"]["login"], "syntaqx");
1616 assert_eq!(event["requested_by"]["type"], "User");
1617 let as_issue = payload::pull_as_issue(&repo(), &pull);
1618 assert_eq!(as_issue["user"]["login"], "g1t");
1619 assert_eq!(as_issue["requested_by"]["login"], "syntaqx");
1620 }
1621
1622 #[test]
1623 fn releases_deployments_and_deleted_comments_read_as_githubs() {
1624 let release = payload::release(
1625 &repo(),
1626 &json!({ "id": "rel_1", "tagName": "v1.2.0", "target": "abc", "name": null, "body": "Notes", "draft": false,
1627 "prerelease": true, "author": "ana", "createdAt": "2026-10-08T00:00:00Z", "publishedAt": "2026-10-08T00:00:00Z" }),
1628 );
1629 assert_eq!(release["tag_name"], "v1.2.0");
1630 assert_eq!(release["name"], "v1.2.0");
1631 assert_eq!(release["prerelease"], true);
1632 assert_eq!(release["author"]["login"], "ana");
1633 assert_eq!(release["html_url"], "https://g1t.sh/acme/web/releases/tag/v1.2.0");
1634 let deployment = json!({ "id": "dep_1", "sha": "abc", "ref": "main", "environment": "staging", "creator": "ana",
1635 "production_environment": false, "created_at": "t", "updated_at": "t" });
1636 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);
1637 assert_eq!(status["state"], "success");
1638 assert_eq!(status["environment"], "staging");
1639 assert_eq!(status["environment_url"], "https://s.example");
1640 assert_eq!(payload::deployment(&repo(), &deployment)["payload"], json!({}));
1641 let gone = payload::deleted_comment(&repo(), 7, &json!({ "id": "cmt_1", "body": "hi", "author": { "id": "usr_1", "username": "bo" }, "createdAt": "t" }), true);
1642 assert_eq!(gone["user"]["login"], "bo");
1643 assert_eq!(gone["html_url"], "https://g1t.sh/acme/web/pull/7#cmt_1");
1644 assert!(is_commit("0123456789abcdef0123456789abcdef01234567"));
1645 assert!(!is_commit("main"));
1646 }
1647
1648 #[test]
1649 fn a_pull_request_names_its_own_base_labels_and_milestone() {
1650 let mut pull = made_for(person("usr_1", "syntaqx"));
1651 let event = payload::pull(&repo(), &pull);
1652 assert_eq!(event["base"]["ref"], repo().default_branch);
1653 pull.base = Some("release/1.x".into());
1654 pull.labels = vec!["bug".into()];
1655 pull.milestone = Some(g1t_contracts::work::MilestoneRef { number: 2, title: "1.1".into() });
1656 let event = payload::pull(&repo(), &pull);
1657 assert_eq!(event["base"]["ref"], "release/1.x");
1658 assert_eq!(event["labels"][0]["name"], "bug");
1659 assert!(event["labels"][0]["id"].is_u64());
1660 assert_eq!(event["milestone"]["title"], "1.1");
1661 let mut labeled = serde_json::json!({ "action": "labeled" });
1662 payload::changed(&repo(), &mut labeled, &serde_json::json!({ "label": { "name": "bug", "color": "d73a4a" } }));
1663 assert_eq!(labeled["label"]["color"], "d73a4a");
1664 let mut assigned = serde_json::json!({ "action": "assigned" });
1665 payload::changed(&repo(), &mut assigned, &serde_json::json!({ "assignees": ["ana", "bo"], "added": ["bo"] }));
1666 assert_eq!(assigned["assignee"]["login"], "bo");
1667 assert!(nobody_added(&serde_json::json!({ "assignees": ["ana"], "added": [] })));
1668 assert!(!nobody_added(&serde_json::json!({ "assignees": ["ana"], "added": ["ana"] })));
1669 }
1670
1671 fn dispatchable(yaml: &str) -> Trigger {
1672 workflow::parse(yaml).unwrap().trigger("workflow_dispatch").unwrap().clone()
1673 }
1674
1675 fn given(value: Value) -> Map<String, Value> {
1676 value.as_object().unwrap().clone()
1677 }
1678
1679 const DISPATCH: &str = "on:
1680 workflow_dispatch:
1681 inputs:
1682 dry-run: { type: boolean, default: false }
1683 count: { type: number, default: 2 }
1684 target: { type: environment }
1685 level: { type: choice, options: [low, high], default: low }
1686 note: { required: false }
1687jobs:
1688 a:
1689 runs-on: x
1690 steps: [{ run: 'true' }]";
1691
1692 #[test]
1693 fn an_input_the_workflow_does_not_declare_is_refused() {
1694 let trigger = dispatchable(DISPATCH);
1695 let Outcome::Fail(failure) = dispatch_inputs(&trigger, &given(json!({ "dry-run": true, "colour": "red" })), &[]) else {
1696 panic!("an undeclared input was taken");
1697 };
1698 assert_eq!(failure.code, FailureCode::Invalid);
1699 assert!(failure.message.starts_with(r#"Unexpected inputs provided: ["colour"]."#), "{}", failure.message);
1700 assert!(failure.message.contains("`dry-run`"));
1701 let bare = dispatchable("on: workflow_dispatch\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]");
1702 let Outcome::Fail(failure) = dispatch_inputs(&bare, &given(json!({ "x": "1" })), &[]) else { panic!() };
1703 assert!(failure.message.contains("declares no inputs"));
1704 assert!(matches!(dispatch_inputs(&bare, &Map::new(), &[]), Outcome::Ok(inputs) if inputs.is_empty()));
1705 }
1706
1707 #[test]
1708 fn inputs_are_typed_and_the_event_has_them_as_text() {
1709 let trigger = dispatchable(DISPATCH);
1710 let environments = vec!["staging".to_owned(), "production".to_owned()];
1711 let Outcome::Ok(inputs) = dispatch_inputs(&trigger, &given(json!({ "dry-run": "true", "count": "3", "target": "Staging" })), &environments)
1712 else {
1713 panic!("refused");
1714 };
1715 assert_eq!(inputs["dry-run"], json!(true));
1716 assert_eq!(inputs["count"], json!(3));
1717 assert_eq!(inputs["level"], json!("low"));
1718 assert_eq!(inputs["note"], json!(""));
1719 let event = event_inputs(&inputs);
1720 assert_eq!(event["dry-run"], json!("true"));
1721 assert_eq!(event["count"], json!("3"));
1722 assert_eq!(event["target"], json!("Staging"));
1723 let Outcome::Ok(defaults) = dispatch_inputs(&trigger, &Map::new(), &environments) else { panic!() };
1724 assert_eq!(event_inputs(&defaults)["dry-run"], json!("false"));
1725 assert_eq!(defaults["count"], json!(2));
1726 let refused = |value: Value| match dispatch_inputs(&trigger, &given(value), &environments) {
1727 Outcome::Fail(failure) => failure.message,
1728 Outcome::Ok(_) => panic!("taken"),
1729 };
1730 assert!(refused(json!({ "target": "qa" })).contains("none called `qa`"));
1731 assert!(refused(json!({ "dry-run": "yes" })).contains("true or false"));
1732 assert!(refused(json!({ "count": "many" })).contains("is a number"));
1733 assert!(refused(json!({ "level": "mid" })).contains("low, high"));
1734 }
1735
1736 #[test]
1737 fn create_and_delete_take_no_filters_and_name_their_ref() {
1738 assert!(unfiltered("create") && unfiltered("delete"));
1739 assert!(!unfiltered("push") && !unfiltered("pull_request"));
1740 assert_eq!(branch_or_tag("refs/heads/feature/x"), Some(("branch", "feature/x")));
1741 assert_eq!(branch_or_tag("refs/tags/v1.0"), Some(("tag", "v1.0")));
1742 assert_eq!(branch_or_tag("refs/heads/g1t-queue/main/3"), None);
1743 assert_eq!(branch_or_tag("refs/notes/commits"), None);
1744 // A workflow can name `delete`. It takes no filters, as GitHub's
1745 // schema says, so writing one is refused when the workflow is read.
1746 assert!(workflow::parse("on:\n delete:\n branches: [release/*]\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").is_err());
1747 let workflow = workflow::parse("on:\n delete:\njobs:\n a:\n runs-on: x\n steps: [{ run: 'true' }]").unwrap();
1748 let trigger = workflow.trigger("delete").unwrap();
1749 assert!(trigger.wants_type(None));
1750 assert!(!workflow.notes.iter().any(|note| note.severity == workflow::Severity::Unsupported));
1751 }
1752}