g1t/crates/actions/src/events.rs

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