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.

420 linesCodeBlameRaw
1//! g1t's events as GitHub's: which event and activity type each one is,
2//! and the `github` context and `GITHUB_*` variables a run sees.
3
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value, json};
6
7/// The GitHub event and activity type for a g1t event, if it has one.
8/// A g1t event can be more than one GitHub event: a pull request opening
9/// is `pull_request` and `pull_request_target`. A new branch or tag is
10/// `push` and `create`; services/actions adds `create` for a `git.push`
11/// with no `before`.
12pub fn github_events(kind: &str) -> Vec<(&'static str, Option<&'static str>)> {
13 let pull = |action| vec![("pull_request", Some(action)), ("pull_request_target", Some(action))];
14 match kind {
15 "git.push" => vec![("push", None)],
16 "git.deleted" => vec![("delete", None)],
17 "pull.opened" => pull("opened"),
18 "pull.updated" => pull("synchronize"),
19 "pull.ready" => pull("ready_for_review"),
20 "pull.reopened" => pull("reopened"),
21 "pull.converted_to_draft" => pull("converted_to_draft"),
22 "pull.closed" | "pull.merged" => pull("closed"),
23 "pull.assigned" => pull("assigned"),
24 "pull.review_requested" => pull("review_requested"),
25 "pull.review_request_removed" => pull("review_request_removed"),
26 "pull.labeled" => pull("labeled"),
27 "pull.unlabeled" => pull("unlabeled"),
28 "pull.milestoned" => pull("milestoned"),
29 "pull.demilestoned" => pull("demilestoned"),
30 "pull.base_changed" => pull("edited"),
31 "work_item.opened" => vec![("work_item", Some("opened"))],
32 "work_item.updated" => vec![("work_item", Some("edited"))],
33 "work_item.closed" => vec![("work_item", Some("closed"))],
34 "work_item.reopened" => vec![("work_item", Some("reopened"))],
35 "work_item.assigned" => vec![("work_item", Some("assigned"))],
36 "work_item.labeled" => vec![("work_item", Some("labeled"))],
37 "work_item.unlabeled" => vec![("work_item", Some("unlabeled"))],
38 "work_item.milestoned" => vec![("work_item", Some("milestoned"))],
39 "work_item.demilestoned" => vec![("work_item", Some("demilestoned"))],
40 "work_item.linked" => vec![("work_item", Some("linked"))],
41 "work_item.unlinked" => vec![("work_item", Some("unlinked"))],
42 "work_item.landed" => vec![("work_item", Some("landed"))],
43 "comment.created" => vec![("work_item_comment", Some("created"))],
44 "comment.edited" => vec![("work_item_comment", Some("edited"))],
45 "comment.deleted" => vec![("work_item_comment", Some("deleted"))],
46 "release.created" => vec![("release", Some("created"))],
47 "release.published" => vec![("release", Some("published"))],
48 "release.released" => vec![("release", Some("released"))],
49 "release.prereleased" => vec![("release", Some("prereleased"))],
50 "release.edited" => vec![("release", Some("edited"))],
51 "release.unpublished" => vec![("release", Some("unpublished"))],
52 "release.deleted" => vec![("release", Some("deleted"))],
53 "deployment.created" => vec![("deployment", None)],
54 "deployment_status.created" => vec![("deployment_status", Some("created"))],
55 "review.completed" => vec![("pull_request_review", Some("submitted"))],
56 "workflow.completed" => vec![("workflow_run", Some("completed"))],
57 _ => Vec::new(),
58 }
59}
60
61/// What a run is about: enough to fill the `github` context.
62#[derive(Clone, Debug, Default, Serialize, Deserialize)]
63#[serde(rename_all = "camelCase")]
64pub struct RunInfo {
65 /// `acme/web`.
66 pub repository: String,
67 pub repository_id: String,
68 pub default_branch: String,
69 pub event_name: String,
70 /// The webhook-shaped payload, `github.event`.
71 pub event: Value,
72 /// `refs/heads/main`, `refs/tags/v1`, `refs/pull/3/merge`.
73 pub git_ref: String,
74 pub sha: String,
75 /// For pull requests: the head and base branches.
76 pub head_ref: Option<String>,
77 pub base_ref: Option<String>,
78 pub actor: String,
79 pub actor_id: String,
80 pub triggering_actor: String,
81 pub run_id: String,
82 pub run_number: u64,
83 pub run_attempt: u64,
84 /// The workflow's name.
85 pub workflow: String,
86 /// `.g1t/workflows/ci.yml`.
87 pub workflow_path: String,
88 pub server_url: String,
89 pub api_url: String,
90}
91
92impl RunInfo {
93 pub fn ref_name(&self) -> String {
94 self.git_ref
95 .strip_prefix("refs/heads/")
96 .or_else(|| self.git_ref.strip_prefix("refs/tags/"))
97 .or_else(|| self.git_ref.strip_prefix("refs/"))
98 .unwrap_or(&self.git_ref)
99 .to_owned()
100 }
101
102 pub fn ref_type(&self) -> &'static str {
103 if self.git_ref.starts_with("refs/tags/") { "tag" } else { "branch" }
104 }
105
106 fn owner(&self) -> &str {
107 self.repository.split('/').next().unwrap_or_default()
108 }
109
110 /// The owner's id, as the event's `repository.owner.id` gives it, or
111 /// else the number for the owner's name ([`account_id`]).
112 fn owner_id(&self) -> String {
113 owner_id(&self.event).unwrap_or_else(|| match self.owner() {
114 "" => String::new(),
115 owner => account_id(owner).to_string(),
116 })
117 }
118
119 /// `github.repository_id`: the repository's number ([`github_id`]).
120 fn repository_number(&self) -> String {
121 id_text(&self.repository_id)
122 }
123
124 /// `github.actor_id`: the actor's number, as the event's `sender.id`
125 /// gives it ([`account_id`]).
126 fn actor_number(&self) -> String {
127 match self.actor.as_str() {
128 "" => id_text(&self.actor_id),
129 actor => account_id(actor).to_string(),
130 }
131 }
132
133 /// The `github` context for a job. `token` is `github.token` (and
134 /// `secrets.GITHUB_TOKEN`); `job` is the job's id.
135 pub fn context(&self, job: &str, token: &str, action: Option<&str>) -> Value {
136 json!({
137 "action": action.unwrap_or_default(),
138 "action_path": "",
139 "action_ref": "",
140 "action_repository": "",
141 "actor": self.actor,
142 "actor_id": self.actor_number(),
143 "api_url": self.api_url,
144 "base_ref": self.base_ref.clone().unwrap_or_default(),
145 "env": "",
146 "event": self.event,
147 "event_name": self.event_name,
148 "event_path": "/home/runner/_temp/event.json",
149 "graphql_url": "",
150 "head_ref": self.head_ref.clone().unwrap_or_default(),
151 "job": job,
152 "path": "",
153 "ref": self.git_ref,
154 "ref_name": self.ref_name(),
155 "ref_protected": self.ref_name() == self.default_branch,
156 "ref_type": self.ref_type(),
157 "repository": self.repository,
158 "repository_id": self.repository_number(),
159 "repository_owner": self.owner(),
160 "repository_owner_id": self.owner_id(),
161 "repositoryUrl": format!("{}/{}.git", self.server_url, self.repository),
162 "retention_days": 14,
163 "run_attempt": self.run_attempt.to_string(),
164 "run_id": self.run_id,
165 "run_number": self.run_number.to_string(),
166 "secret_source": "Actions",
167 "server_url": self.server_url,
168 "sha": self.sha,
169 "token": token,
170 "triggering_actor": self.triggering_actor,
171 "workflow": self.workflow,
172 "workflow_ref": format!("{}/{}@{}", self.repository, self.workflow_path, self.git_ref),
173 "workflow_sha": self.sha,
174 "workspace": WORKSPACE,
175 })
176 }
177
178 /// The `GITHUB_*` and `RUNNER_*` variables every step gets.
179 pub fn variables(&self, job: &str) -> Map<String, Value> {
180 let mut vars = Map::new();
181 let mut set = |key: &str, value: String| {
182 vars.insert(key.to_owned(), Value::String(value));
183 };
184 set("CI", "true".into());
185 set("GITHUB_ACTIONS", "true".into());
186 set("G1T", "true".into());
187 set("GITHUB_ACTOR", self.actor.clone());
188 set("GITHUB_ACTOR_ID", self.actor_number());
189 set("GITHUB_API_URL", self.api_url.clone());
190 set("GITHUB_BASE_REF", self.base_ref.clone().unwrap_or_default());
191 set("GITHUB_EVENT_NAME", self.event_name.clone());
192 set("GITHUB_EVENT_PATH", "/home/runner/_temp/event.json".into());
193 set("GITHUB_GRAPHQL_URL", String::new());
194 set("GITHUB_HEAD_REF", self.head_ref.clone().unwrap_or_default());
195 set("GITHUB_JOB", job.to_owned());
196 set("GITHUB_REF", self.git_ref.clone());
197 set("GITHUB_REF_NAME", self.ref_name());
198 set("GITHUB_REF_PROTECTED", (self.ref_name() == self.default_branch).to_string());
199 set("GITHUB_REF_TYPE", self.ref_type().into());
200 set("GITHUB_REPOSITORY", self.repository.clone());
201 set("GITHUB_REPOSITORY_ID", self.repository_number());
202 set("GITHUB_REPOSITORY_OWNER", self.owner().to_owned());
203 set("GITHUB_REPOSITORY_OWNER_ID", self.owner_id());
204 set("GITHUB_RETENTION_DAYS", "14".into());
205 set("GITHUB_RUN_ATTEMPT", self.run_attempt.to_string());
206 set("GITHUB_RUN_ID", self.run_id.clone());
207 set("GITHUB_RUN_NUMBER", self.run_number.to_string());
208 set("GITHUB_SERVER_URL", self.server_url.clone());
209 set("GITHUB_SHA", self.sha.clone());
210 set("GITHUB_TRIGGERING_ACTOR", self.triggering_actor.clone());
211 set("GITHUB_WORKFLOW", self.workflow.clone());
212 set("GITHUB_WORKFLOW_REF", format!("{}/{}@{}", self.repository, self.workflow_path, self.git_ref));
213 set("GITHUB_WORKFLOW_SHA", self.sha.clone());
214 set("GITHUB_WORKSPACE", WORKSPACE.into());
215 set("RUNNER_ARCH", "X64".into());
216 set("RUNNER_NAME", "g1t".into());
217 set("RUNNER_OS", "Linux".into());
218 set("RUNNER_TEMP", "/home/runner/_temp".into());
219 set("RUNNER_TOOL_CACHE", "/home/runner/_tool".into());
220 set("RUNNER_ENVIRONMENT", "github-hosted".into());
221 set("RUNNER_WORKSPACE", RUNNER_WORKSPACE.into());
222 vars
223 }
224}
225
226/// The whole number GitHub gives an object as its `id`, for a g1t id
227/// (`rep_01kpw0…`, `pr_01…`): the same number every time, positive, and
228/// below 2^53 so JavaScript reads it exactly. g1t's own id stays the
229/// object's `node_id`.
230pub fn github_id(id: &str) -> u64 {
231 // FNV-1a, 64 bits, cut to 53.
232 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
233 for byte in id.bytes() {
234 hash ^= u64::from(byte);
235 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
236 }
237 (hash & ((1 << 53) - 1)).max(1)
238}
239
240/// The number of a person or workspace, by their name: usernames and
241/// workspaces share one namespace, so `sender.id`, `user.id`,
242/// `repository.owner.id`, `github.actor_id` and
243/// `github.repository_owner_id` agree wherever the same name appears, and
244/// a personal workspace's repositories are owned by its person's number,
245/// as on GitHub. Case does not matter.
246pub fn account_id(login: &str) -> u64 {
247 github_id(&format!("account:{}", login.to_ascii_lowercase()))
248}
249
250/// An id as text of a number: one that is already a number as it is,
251/// a g1t id as its [`github_id`], nothing as nothing.
252fn id_text(id: &str) -> String {
253 if id.is_empty() || id.bytes().all(|b| b.is_ascii_digit()) {
254 id.to_owned()
255 } else {
256 github_id(id).to_string()
257 }
258}
259
260/// The owner's id in a webhook-shaped payload, `repository.owner.id`, a
261/// number or a string.
262pub fn owner_id(event: &Value) -> Option<String> {
263 match &event["repository"]["owner"]["id"] {
264 Value::String(id) => Some(id.clone()),
265 Value::Number(id) => Some(id.to_string()),
266 _ => None,
267 }
268}
269
270/// Where a job's repository is checked out, as on GitHub's runners.
271pub const WORKSPACE: &str = "/home/runner/work/repo";
272
273/// The folder the workspace is in, as GitHub's `RUNNER_WORKSPACE` is.
274pub const RUNNER_WORKSPACE: &str = "/home/runner/work";
275
276/// The `runner` context.
277/// Whether a head commit's `message` asks, as GitHub lets it, that the
278/// `push` and `pull_request` workflows it would start don't run: `[skip ci]`,
279/// `[ci skip]`, `[no ci]`, `[skip actions]` or `[actions skip]` anywhere in
280/// it, or a `skip-checks: true` trailer.
281pub fn skips_ci(message: &str) -> bool {
282 let lower = message.to_ascii_lowercase();
283 if ["[skip ci]", "[ci skip]", "[no ci]", "[skip actions]", "[actions skip]"].iter().any(|marker| lower.contains(marker)) {
284 return true;
285 }
286 // Trailers are the last paragraph, after a blank line.
287 let trimmed = lower.trim_end();
288 let Some((_, trailers)) = trimmed.rsplit_once("\n\n") else { return false };
289 trailers.lines().any(|line| line.split_once(':').is_some_and(|(key, value)| key.trim() == "skip-checks" && value.trim() == "true"))
290}
291
292pub fn runner_context() -> Value {
293 json!({
294 "name": "g1t",
295 "os": "Linux",
296 "arch": "X64",
297 "temp": "/home/runner/_temp",
298 "tool_cache": "/home/runner/_tool",
299 "environment": "github-hosted",
300 "debug": "",
301 })
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 #[test]
309 fn g1t_events_are_github_events() {
310 assert_eq!(github_events("git.push"), [("push", None)]);
311 assert_eq!(github_events("git.deleted"), [("delete", None)]);
312 assert_eq!(github_events("pull.labeled")[1], ("pull_request_target", Some("labeled")));
313 assert_eq!(github_events("pull.assigned")[0], ("pull_request", Some("assigned")));
314 assert_eq!(github_events("work_item.unlabeled"), [("work_item", Some("unlabeled"))]);
315 assert_eq!(github_events("work_item.assigned"), [("work_item", Some("assigned"))]);
316 assert_eq!(github_events("work_item.updated"), [("work_item", Some("edited"))]);
317 assert_eq!(github_events("work_item.linked"), [("work_item", Some("linked"))]);
318 assert_eq!(github_events("work_item.landed"), [("work_item", Some("landed"))]);
319 assert!(github_events("issue.opened").is_empty());
320 assert_eq!(github_events("pull.updated")[0], ("pull_request", Some("synchronize")));
321 assert_eq!(github_events("pull.merged")[1], ("pull_request_target", Some("closed")));
322 assert_eq!(github_events("comment.created"), [("work_item_comment", Some("created"))]);
323 assert_eq!(github_events("work_item.labeled"), [("work_item", Some("labeled"))]);
324 assert_eq!(github_events("pull.unlabeled")[0], ("pull_request", Some("unlabeled")));
325 assert_eq!(github_events("pull.milestoned")[1], ("pull_request_target", Some("milestoned")));
326 assert_eq!(github_events("pull.base_changed")[0], ("pull_request", Some("edited")));
327 assert_eq!(github_events("pull.reopened")[0], ("pull_request", Some("reopened")));
328 assert_eq!(github_events("pull.converted_to_draft")[1], ("pull_request_target", Some("converted_to_draft")));
329 assert_eq!(github_events("comment.edited"), [("work_item_comment", Some("edited"))]);
330 assert_eq!(github_events("comment.deleted"), [("work_item_comment", Some("deleted"))]);
331 assert_eq!(github_events("release.published"), [("release", Some("published"))]);
332 assert_eq!(github_events("release.prereleased"), [("release", Some("prereleased"))]);
333 assert_eq!(github_events("deployment_status.created"), [("deployment_status", Some("created"))]);
334 assert_eq!(github_events("deployment.created"), [("deployment", None)]);
335 // g1t.page's own deployment outcomes are the inbox's, not a GitHub event.
336 assert!(github_events("deployment.succeeded").is_empty());
337 assert!(github_events("session.appended").is_empty());
338 }
339
340 #[test]
341 fn contexts_and_variables_agree() {
342 let info = RunInfo {
343 repository: "acme/web".into(),
344 default_branch: "main".into(),
345 event_name: "push".into(),
346 git_ref: "refs/tags/v1.2.0".into(),
347 sha: "abc".into(),
348 run_number: 7,
349 run_attempt: 1,
350 server_url: "https://g1t.sh".into(),
351 ..RunInfo::default()
352 };
353 let github = info.context("build", "tok", None);
354 assert_eq!(github["ref_name"], "v1.2.0");
355 assert_eq!(github["ref_type"], "tag");
356 assert_eq!(github["repository_owner"], "acme");
357 assert_eq!(github["run_number"], "7");
358 let vars = info.variables("build");
359 assert_eq!(vars["GITHUB_REF_NAME"], "v1.2.0");
360 assert_eq!(vars["GITHUB_JOB"], "build");
361 assert_eq!(vars["RUNNER_OS"], "Linux");
362 assert_eq!(vars["RUNNER_WORKSPACE"], "/home/runner/work");
363 assert_eq!(vars["GITHUB_REPOSITORY_OWNER_ID"], account_id("acme").to_string());
364 }
365
366 #[test]
367 fn ids_are_whole_numbers_as_on_github() {
368 let id = github_id("rep_01kpw0abcdefghjkmnpqrstvwx");
369 assert_eq!(id, github_id("rep_01kpw0abcdefghjkmnpqrstvwx"), "the same every time");
370 assert!(id > 0 && id < 1 << 53, "a safe integer in JavaScript");
371 assert_ne!(id, github_id("rep_01kpw0abcdefghjkmnpqrstvwy"));
372 assert_eq!(account_id("Ada"), account_id("ada"));
373 assert_ne!(account_id("ada"), github_id("ada"));
374 let info = RunInfo {
375 repository: "acme/web".into(),
376 repository_id: "rep_1".into(),
377 actor: "ada".into(),
378 actor_id: "usr_1".into(),
379 ..RunInfo::default()
380 };
381 let github = info.context("build", "", None);
382 assert_eq!(github["repository_id"], github_id("rep_1").to_string());
383 assert_eq!(github["actor_id"], account_id("ada").to_string());
384 assert_eq!(github["repository_owner_id"], account_id("acme").to_string());
385 let vars = info.variables("build");
386 assert_eq!(vars["GITHUB_REPOSITORY_ID"], github["repository_id"]);
387 assert_eq!(vars["GITHUB_ACTOR_ID"], github["actor_id"]);
388 assert!(vars["GITHUB_REPOSITORY_ID"].as_str().unwrap().bytes().all(|b| b.is_ascii_digit()));
389 // A number already is one.
390 assert_eq!(RunInfo { repository_id: "42".into(), ..RunInfo::default() }.context("", "", None)["repository_id"], "42");
391 }
392
393 #[test]
394 fn the_owners_id_comes_from_the_event() {
395 let info = RunInfo {
396 repository: "acme/web".into(),
397 event: json!({ "repository": { "owner": { "id": 42 } } }),
398 ..RunInfo::default()
399 };
400 assert_eq!(info.variables("build")["GITHUB_REPOSITORY_OWNER_ID"], "42");
401 assert_eq!(info.context("build", "", None)["repository_owner_id"], "42");
402 assert_eq!(owner_id(&json!({ "repository": { "owner": { "id": "ws_1" } } })).as_deref(), Some("ws_1"));
403 assert_eq!(owner_id(&json!({})), None);
404 }
405}
406
407#[cfg(test)]
408mod skip_tests {
409 use super::skips_ci;
410
411 #[test]
412 fn a_commit_can_skip_its_runs_as_on_github() {
413 for message in ["Fix typo [skip ci]", "[ci skip] docs", "Notes [no ci]", "x [skip actions]", "[Actions Skip]", "Tidy\n\nskip-checks: true", "Tidy\n\nSigned-off-by: A <a@b>\nskip-checks:true\n"] {
414 assert!(skips_ci(message), "{message:?}");
415 }
416 for message in ["Fix the skip ci flag", "skip-checks: true", "Tidy\n\nskip-checks: false", "[skip-ci]", "Tidy\n\nskip-checks: true\n\nMore"] {
417 assert!(!skips_ci(message), "{message:?}");
418 }
419 }
420}