Skip to content

g1t/crates/actions/src/events.rs

238 lines10,064 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

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