Skip to content
261 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`.
10pub fn github_events(kind: &str) -> Vec<(&'static str, Option<&'static str>)> {
11 let pull = |action| vec![("pull_request", Some(action)), ("pull_request_target", Some(action))];
12 match kind {
13 "git.push" => vec![("push", None)],
14 "pull.opened" => pull("opened"),
15 "pull.updated" => pull("synchronize"),
16 "pull.ready" => pull("ready_for_review"),
17 "pull.reopened" => pull("reopened"),
18 "pull.converted_to_draft" => pull("converted_to_draft"),
19 "pull.closed" | "pull.merged" => pull("closed"),
20 "pull.assigned" => pull("assigned"),
21 "pull.review_requested" => pull("review_requested"),
22 "pull.review_request_removed" => pull("review_request_removed"),
23 "pull.labeled" => pull("labeled"),
24 "pull.unlabeled" => pull("unlabeled"),
25 "pull.milestoned" => pull("milestoned"),
26 "pull.demilestoned" => pull("demilestoned"),
27 "pull.base_changed" => pull("edited"),
28 "issue.opened" => vec![("issues", Some("opened"))],
29 "issue.updated" => vec![("issues", Some("edited"))],
30 "issue.closed" => vec![("issues", Some("closed"))],
31 "issue.reopened" => vec![("issues", Some("reopened"))],
32 "issue.assigned" => vec![("issues", Some("assigned"))],
33 "issue.labeled" => vec![("issues", Some("labeled"))],
34 "issue.unlabeled" => vec![("issues", Some("unlabeled"))],
35 "issue.milestoned" => vec![("issues", Some("milestoned"))],
36 "issue.demilestoned" => vec![("issues", Some("demilestoned"))],
37 "comment.created" => vec![("issue_comment", Some("created"))],
38 "comment.edited" => vec![("issue_comment", Some("edited"))],
39 "comment.deleted" => vec![("issue_comment", Some("deleted"))],
40 "release.created" => vec![("release", Some("created"))],
41 "release.published" => vec![("release", Some("published"))],
42 "release.released" => vec![("release", Some("released"))],
43 "release.prereleased" => vec![("release", Some("prereleased"))],
44 "release.edited" => vec![("release", Some("edited"))],
45 "release.unpublished" => vec![("release", Some("unpublished"))],
46 "release.deleted" => vec![("release", Some("deleted"))],
47 "deployment.created" => vec![("deployment", None)],
48 "deployment_status.created" => vec![("deployment_status", Some("created"))],
49 "review.completed" => vec![("pull_request_review", Some("submitted"))],
50 "workflow.completed" => vec![("workflow_run", Some("completed"))],
51 _ => Vec::new(),
52 }
53}
54
55/// What a run is about: enough to fill the `github` context.
56#[derive(Clone, Debug, Default, Serialize, Deserialize)]
57#[serde(rename_all = "camelCase")]
58pub struct RunInfo {
59 /// `acme/web`.
60 pub repository: String,
61 pub repository_id: String,
62 pub default_branch: String,
63 pub event_name: String,
64 /// The webhook-shaped payload, `github.event`.
65 pub event: Value,
66 /// `refs/heads/main`, `refs/tags/v1`, `refs/pull/3/merge`.
67 pub git_ref: String,
68 pub sha: String,
69 /// For pull requests: the head and base branches.
70 pub head_ref: Option<String>,
71 pub base_ref: Option<String>,
72 pub actor: String,
73 pub actor_id: String,
74 pub triggering_actor: String,
75 pub run_id: String,
76 pub run_number: u64,
77 pub run_attempt: u64,
78 /// The workflow's name.
79 pub workflow: String,
80 /// `.g1t/workflows/ci.yml`.
81 pub workflow_path: String,
82 pub server_url: String,
83 pub api_url: String,
84}
85
86impl RunInfo {
87 pub fn ref_name(&self) -> String {
88 self.git_ref
89 .strip_prefix("refs/heads/")
90 .or_else(|| self.git_ref.strip_prefix("refs/tags/"))
91 .or_else(|| self.git_ref.strip_prefix("refs/"))
92 .unwrap_or(&self.git_ref)
93 .to_owned()
94 }
95
96 pub fn ref_type(&self) -> &'static str {
97 if self.git_ref.starts_with("refs/tags/") { "tag" } else { "branch" }
98 }
99
100 fn owner(&self) -> &str {
101 self.repository.split('/').next().unwrap_or_default()
102 }
103
104 /// The `github` context for a job. `token` is `github.token` (and
105 /// `secrets.GITHUB_TOKEN`); `job` is the job's id.
106 pub fn context(&self, job: &str, token: &str, action: Option<&str>) -> Value {
107 json!({
108 "action": action.unwrap_or_default(),
109 "action_path": "",
110 "action_ref": "",
111 "action_repository": "",
112 "actor": self.actor,
113 "actor_id": self.actor_id,
114 "api_url": self.api_url,
115 "base_ref": self.base_ref.clone().unwrap_or_default(),
116 "env": "",
117 "event": self.event,
118 "event_name": self.event_name,
119 "event_path": "/home/runner/_temp/event.json",
120 "graphql_url": "",
121 "head_ref": self.head_ref.clone().unwrap_or_default(),
122 "job": job,
123 "path": "",
124 "ref": self.git_ref,
125 "ref_name": self.ref_name(),
126 "ref_protected": self.ref_name() == self.default_branch,
127 "ref_type": self.ref_type(),
128 "repository": self.repository,
129 "repository_id": self.repository_id,
130 "repository_owner": self.owner(),
131 "repository_owner_id": "",
132 "repositoryUrl": format!("{}/{}.git", self.server_url, self.repository),
133 "retention_days": 14,
134 "run_attempt": self.run_attempt.to_string(),
135 "run_id": self.run_id,
136 "run_number": self.run_number.to_string(),
137 "secret_source": "Actions",
138 "server_url": self.server_url,
139 "sha": self.sha,
140 "token": token,
141 "triggering_actor": self.triggering_actor,
142 "workflow": self.workflow,
143 "workflow_ref": format!("{}/{}@{}", self.repository, self.workflow_path, self.git_ref),
144 "workflow_sha": self.sha,
145 "workspace": WORKSPACE,
146 })
147 }
148
149 /// The `GITHUB_*` and `RUNNER_*` variables every step gets.
150 pub fn variables(&self, job: &str) -> Map<String, Value> {
151 let mut vars = Map::new();
152 let mut set = |key: &str, value: String| {
153 vars.insert(key.to_owned(), Value::String(value));
154 };
155 set("CI", "true".into());
156 set("GITHUB_ACTIONS", "true".into());
157 set("G1T", "true".into());
158 set("GITHUB_ACTOR", self.actor.clone());
159 set("GITHUB_ACTOR_ID", self.actor_id.clone());
160 set("GITHUB_API_URL", self.api_url.clone());
161 set("GITHUB_BASE_REF", self.base_ref.clone().unwrap_or_default());
162 set("GITHUB_EVENT_NAME", self.event_name.clone());
163 set("GITHUB_EVENT_PATH", "/home/runner/_temp/event.json".into());
164 set("GITHUB_GRAPHQL_URL", String::new());
165 set("GITHUB_HEAD_REF", self.head_ref.clone().unwrap_or_default());
166 set("GITHUB_JOB", job.to_owned());
167 set("GITHUB_REF", self.git_ref.clone());
168 set("GITHUB_REF_NAME", self.ref_name());
169 set("GITHUB_REF_PROTECTED", (self.ref_name() == self.default_branch).to_string());
170 set("GITHUB_REF_TYPE", self.ref_type().into());
171 set("GITHUB_REPOSITORY", self.repository.clone());
172 set("GITHUB_REPOSITORY_ID", self.repository_id.clone());
173 set("GITHUB_REPOSITORY_OWNER", self.owner().to_owned());
174 set("GITHUB_RETENTION_DAYS", "14".into());
175 set("GITHUB_RUN_ATTEMPT", self.run_attempt.to_string());
176 set("GITHUB_RUN_ID", self.run_id.clone());
177 set("GITHUB_RUN_NUMBER", self.run_number.to_string());
178 set("GITHUB_SERVER_URL", self.server_url.clone());
179 set("GITHUB_SHA", self.sha.clone());
180 set("GITHUB_TRIGGERING_ACTOR", self.triggering_actor.clone());
181 set("GITHUB_WORKFLOW", self.workflow.clone());
182 set("GITHUB_WORKFLOW_REF", format!("{}/{}@{}", self.repository, self.workflow_path, self.git_ref));
183 set("GITHUB_WORKFLOW_SHA", self.sha.clone());
184 set("GITHUB_WORKSPACE", WORKSPACE.into());
185 set("RUNNER_ARCH", "X64".into());
186 set("RUNNER_NAME", "g1t".into());
187 set("RUNNER_OS", "Linux".into());
188 set("RUNNER_TEMP", "/home/runner/_temp".into());
189 set("RUNNER_TOOL_CACHE", "/home/runner/_tool".into());
190 set("RUNNER_ENVIRONMENT", "github-hosted".into());
191 vars
192 }
193}
194
195/// Where a job's repository is checked out, as on GitHub's runners.
196pub const WORKSPACE: &str = "/home/runner/work/repo";
197
198/// The `runner` context.
199pub fn runner_context() -> Value {
200 json!({
201 "name": "g1t",
202 "os": "Linux",
203 "arch": "X64",
204 "temp": "/home/runner/_temp",
205 "tool_cache": "/home/runner/_tool",
206 "environment": "github-hosted",
207 "debug": "",
208 })
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn g1t_events_are_github_events() {
217 assert_eq!(github_events("git.push"), [("push", None)]);
218 assert_eq!(github_events("pull.updated")[0], ("pull_request", Some("synchronize")));
219 assert_eq!(github_events("pull.merged")[1], ("pull_request_target", Some("closed")));
220 assert_eq!(github_events("comment.created"), [("issue_comment", Some("created"))]);
221 assert_eq!(github_events("issue.labeled"), [("issues", Some("labeled"))]);
222 assert_eq!(github_events("pull.unlabeled")[0], ("pull_request", Some("unlabeled")));
223 assert_eq!(github_events("pull.milestoned")[1], ("pull_request_target", Some("milestoned")));
224 assert_eq!(github_events("pull.base_changed")[0], ("pull_request", Some("edited")));
225 assert_eq!(github_events("pull.reopened")[0], ("pull_request", Some("reopened")));
226 assert_eq!(github_events("pull.converted_to_draft")[1], ("pull_request_target", Some("converted_to_draft")));
227 assert_eq!(github_events("comment.edited"), [("issue_comment", Some("edited"))]);
228 assert_eq!(github_events("comment.deleted"), [("issue_comment", Some("deleted"))]);
229 assert_eq!(github_events("release.published"), [("release", Some("published"))]);
230 assert_eq!(github_events("release.prereleased"), [("release", Some("prereleased"))]);
231 assert_eq!(github_events("deployment_status.created"), [("deployment_status", Some("created"))]);
232 assert_eq!(github_events("deployment.created"), [("deployment", None)]);
233 // g1t.page's own deployment outcomes are the inbox's, not a GitHub event.
234 assert!(github_events("deployment.succeeded").is_empty());
235 assert!(github_events("session.appended").is_empty());
236 }
237
238 #[test]
239 fn contexts_and_variables_agree() {
240 let info = RunInfo {
241 repository: "acme/web".into(),
242 default_branch: "main".into(),
243 event_name: "push".into(),
244 git_ref: "refs/tags/v1.2.0".into(),
245 sha: "abc".into(),
246 run_number: 7,
247 run_attempt: 1,
248 server_url: "https://g1t.sh".into(),
249 ..RunInfo::default()
250 };
251 let github = info.context("build", "tok", None);
252 assert_eq!(github["ref_name"], "v1.2.0");
253 assert_eq!(github["ref_type"], "tag");
254 assert_eq!(github["repository_owner"], "acme");
255 assert_eq!(github["run_number"], "7");
256 let vars = info.variables("build");
257 assert_eq!(vars["GITHUB_REF_NAME"], "v1.2.0");
258 assert_eq!(vars["GITHUB_JOB"], "build");
259 assert_eq!(vars["RUNNER_OS"], "Linux");
260 }
261}