Skip to content

g1t/crates/actions/src/events.rs

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