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