forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

payload.rs403 lines, 12.5 KiBHistoryRawDownload
1//! JSON payload builders for webhook deliveries. Each builder returns the event-specific fields.
2//! `emit` adds `action` (when the event has one), `repository` and `sender`.
3//!
4//! Links are built from `base_url` (the configured
5//! public URL), so they point at the instance a receiver can reach.
6
7use forge_core::{Comment, Issue, PullRequest, Repo, Review, Visibility};
8use forge_git::browse::CommitInfo;
9use serde_json::{Value, json};
10
11/// Most commits listed in a push payload. `total_commits` still counts all of them.
12pub const MAX_PAYLOAD_COMMITS: usize = 20;
13
14/// `base_url` without its trailing slash, so joined paths have exactly one separator.
15fn base(base_url: &str) -> &str {
16 base_url.trim_end_matches('/')
17}
18
19/// `{base}/{owner}/{name}`.
20fn repo_url(base_url: &str, repo: &Repo) -> String {
21 format!("{}/{}/{}", base(base_url), repo.owner_name, repo.name)
22}
23
24/// The page of an issue or pull request: `issues` or `pulls`.
25fn item_url(base_url: &str, repo: &Repo, segment: &str, number: i64) -> String {
26 format!("{}/{segment}/{number}", repo_url(base_url, repo))
27}
28
29/// The repository object carried by every payload. `owner` stays the owner's name; `owner_kind` is
30/// `"user"` or `"org"`.
31pub fn repository(base_url: &str, repo: &Repo, owner_kind: &str) -> Value {
32 let url = repo_url(base_url, repo);
33 json!({
34 "id": repo.id,
35 "owner": repo.owner_name,
36 "owner_kind": owner_kind,
37 "name": repo.name,
38 "full_name": format!("{}/{}", repo.owner_name, repo.name),
39 "private": repo.visibility == Visibility::Private,
40 "html_url": url,
41 "clone_url": format!("{url}.git"),
42 })
43}
44
45/// The sender object, or `null` for a system change (no signed-in user).
46pub fn sender(id: &str, username: &str) -> Value {
47 if id.is_empty() {
48 Value::Null
49 } else {
50 json!({ "id": id, "username": username })
51 }
52}
53
54/// `issues` payload: `issue`. The emit side adds `label` or `assignee` for those actions.
55pub fn issues(base_url: &str, repo: &Repo, issue: &Issue) -> Value {
56 json!({ "issue": issue_object(base_url, repo, issue, false) })
57}
58
59/// `pull_request` payload: `number` and `pull_request`.
60pub fn pull_request(base_url: &str, repo: &Repo, pr: &PullRequest) -> Value {
61 json!({
62 "number": pr.issue.number,
63 "pull_request": pull_object(base_url, repo, pr),
64 })
65}
66
67/// `issue_comment` payload: the item (`issue`, which is a pull request when `pull` is true) and
68/// the `comment`.
69pub fn issue_comment(
70 base_url: &str,
71 repo: &Repo,
72 issue: &Issue,
73 pull: bool,
74 comment: &Comment,
75) -> Value {
76 let page = item_url(
77 base_url,
78 repo,
79 if pull { "pulls" } else { "issues" },
80 issue.number,
81 );
82 json!({
83 "issue": issue_object(base_url, repo, issue, pull),
84 "comment": {
85 "id": comment.id,
86 "body": comment.body,
87 "html_url": format!("{page}#comment-{}", comment.id),
88 },
89 })
90}
91
92/// `pull_request_review` payload: `review` and the `pull_request`.
93pub fn pull_request_review(
94 base_url: &str,
95 repo: &Repo,
96 pr: &PullRequest,
97 review: &Review,
98) -> Value {
99 json!({
100 "review": {
101 "id": review.id,
102 "state": review.state.as_str(),
103 "body": review.body,
104 },
105 "pull_request": pull_object(base_url, repo, pr),
106 })
107}
108
109/// `push` payload. `commits` is the new commits, oldest first; at most [`MAX_PAYLOAD_COMMITS`]
110/// are listed, and `total` is the number found.
111pub fn push(
112 base_url: &str,
113 repo: &Repo,
114 refname: &str,
115 before: &str,
116 after: &str,
117 commits: &[CommitInfo],
118 total: usize,
119) -> Value {
120 let url = repo_url(base_url, repo);
121 let listed: Vec<Value> = commits
122 .iter()
123 .take(MAX_PAYLOAD_COMMITS)
124 .map(|commit| {
125 json!({
126 "id": commit.oid,
127 "message": commit.message,
128 "author": { "name": commit.author_name, "email": commit.author_email },
129 "timestamp": timestamp(commit.author_time),
130 "url": format!("{url}/commit/{}", commit.oid),
131 })
132 })
133 .collect();
134 json!({
135 "ref": refname,
136 "before": before,
137 "after": after,
138 "commits": listed,
139 "total_commits": total,
140 "compare_url": format!("{url}/compare/{before}...{after}"),
141 })
142}
143
144/// `create` and `delete` payload: the short branch or tag name and its kind.
145pub fn ref_change(ref_type: &str, name: &str) -> Value {
146 json!({ "ref": name, "ref_type": ref_type })
147}
148
149/// `ping` payload, sent when a hook is created or tested.
150pub fn ping(hook_id: &str) -> Value {
151 json!({
152 "zen": "Forge keeps the repository close.",
153 "hook_id": hook_id,
154 })
155}
156
157fn issue_object(base_url: &str, repo: &Repo, issue: &Issue, pull: bool) -> Value {
158 json!({
159 "number": issue.number,
160 "title": issue.title,
161 "body": issue.body,
162 "state": issue.state.as_str(),
163 "html_url": item_url(
164 base_url,
165 repo,
166 if pull { "pulls" } else { "issues" },
167 issue.number,
168 ),
169 })
170}
171
172fn pull_object(base_url: &str, repo: &Repo, pr: &PullRequest) -> Value {
173 json!({
174 "title": pr.issue.title,
175 "body": pr.issue.body,
176 "state": pr.issue.state.as_str(),
177 "merged": pr.merged_at.is_some(),
178 "draft": pr.draft,
179 "base": { "ref": pr.base_branch, "sha": pr.base_oid },
180 "head": { "ref": pr.head_branch, "sha": pr.head_oid },
181 "html_url": item_url(base_url, repo, "pulls", pr.issue.number),
182 })
183}
184
185/// RFC 3339 for a Unix time, or an empty string when the time is out of range.
186fn timestamp(seconds: i64) -> String {
187 jiff::Timestamp::from_second(seconds)
188 .map(|t| t.to_string())
189 .unwrap_or_default()
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195 use forge_core::{IssueState, Mergeable, ReviewState};
196
197 fn repo() -> Repo {
198 Repo {
199 id: "r1".into(),
200 owner_id: "u1".into(),
201 owner_name: "tahinli".into(),
202 name: "proj".into(),
203 description: String::new(),
204 visibility: Visibility::Private,
205 default_branch: "main".into(),
206 archived: false,
207 created_at: String::new(),
208 fork_of: None,
209 }
210 }
211
212 fn issue(state: IssueState) -> Issue {
213 Issue {
214 id: "i1".into(),
215 repo_id: "r1".into(),
216 number: 7,
217 title: "Crash".into(),
218 body: "It crashes".into(),
219 state,
220 state_reason: None,
221 author_id: "u1".into(),
222 milestone_id: None,
223 comment_count: 0,
224 created_at: String::new(),
225 updated_at: String::new(),
226 closed_at: None,
227 locked: false,
228 lock_reason: None,
229 }
230 }
231
232 fn pr() -> PullRequest {
233 PullRequest {
234 issue: issue(IssueState::Open),
235 base_branch: "main".into(),
236 head_repo_id: Some("r1".into()),
237 head_branch: "feature".into(),
238 head_oid: "h".repeat(40),
239 base_oid: "b".repeat(40),
240 merge_base: None,
241 mergeable: Mergeable::Unknown,
242 conflict_files: Vec::new(),
243 merged_at: None,
244 merged_by: None,
245 merge_commit: None,
246 draft: false,
247 auto_merge: None,
248 }
249 }
250
251 #[test]
252 fn repository_has_urls_built_from_base() {
253 let v = repository("https://forge.test/", &repo(), "user");
254 assert_eq!(v["full_name"], "tahinli/proj");
255 assert_eq!(v["owner"], "tahinli");
256 assert_eq!(v["owner_kind"], "user");
257 assert_eq!(
258 repository("https://forge.test/", &repo(), "org")["owner_kind"],
259 "org"
260 );
261 assert_eq!(v["private"], true);
262 assert_eq!(v["html_url"], "https://forge.test/tahinli/proj");
263 assert_eq!(v["clone_url"], "https://forge.test/tahinli/proj.git");
264 }
265
266 #[test]
267 fn sender_is_null_for_system_changes() {
268 assert_eq!(sender("", ""), Value::Null);
269 assert_eq!(
270 sender("u1", "tahinli"),
271 json!({"id": "u1", "username": "tahinli"})
272 );
273 }
274
275 #[test]
276 fn issues_payload_shape() {
277 let v = issues("https://forge.test", &repo(), &issue(IssueState::Closed));
278 assert_eq!(v["issue"]["number"], 7);
279 assert_eq!(v["issue"]["state"], "closed");
280 assert_eq!(
281 v["issue"]["html_url"],
282 "https://forge.test/tahinli/proj/issues/7"
283 );
284 assert!(v.get("label").is_none());
285 }
286
287 #[test]
288 fn pull_request_payload_shape() {
289 let v = pull_request("https://forge.test", &repo(), &pr());
290 assert_eq!(v["number"], 7);
291 let p = &v["pull_request"];
292 assert_eq!(p["title"], "Crash");
293 assert_eq!(p["state"], "open");
294 assert_eq!(p["merged"], false);
295 assert_eq!(p["base"]["ref"], "main");
296 assert_eq!(p["head"]["ref"], "feature");
297 assert_eq!(p["html_url"], "https://forge.test/tahinli/proj/pulls/7");
298 }
299
300 #[test]
301 fn comment_and_review_payloads() {
302 let comment = Comment {
303 id: "c9".into(),
304 issue_id: "i1".into(),
305 author_id: "u1".into(),
306 body: "hi".into(),
307 created_at: String::new(),
308 updated_at: String::new(),
309 edited: false,
310 };
311 let v = issue_comment(
312 "https://forge.test",
313 &repo(),
314 &issue(IssueState::Open),
315 true,
316 &comment,
317 );
318 assert_eq!(v["comment"]["id"], "c9");
319 assert_eq!(
320 v["comment"]["html_url"],
321 "https://forge.test/tahinli/proj/pulls/7#comment-c9"
322 );
323 assert_eq!(
324 v["issue"]["html_url"],
325 "https://forge.test/tahinli/proj/pulls/7"
326 );
327
328 let review = Review {
329 id: "rv1".into(),
330 issue_id: "i1".into(),
331 author_id: "u1".into(),
332 author_name: "tahinli".into(),
333 state: ReviewState::Approved,
334 body: "ship it".into(),
335 commit_oid: "h".repeat(40),
336 dismissed_reason: None,
337 dismissed_from: None,
338 created_at: String::new(),
339 submitted_at: None,
340 };
341 let v = pull_request_review("https://forge.test", &repo(), &pr(), &review);
342 assert_eq!(v["review"]["state"], "approved");
343 assert_eq!(v["review"]["body"], "ship it");
344 assert_eq!(v["pull_request"]["title"], "Crash");
345 }
346
347 fn commit(n: usize) -> CommitInfo {
348 CommitInfo {
349 oid: format!("{n:040}"),
350 parents: Vec::new(),
351 author_name: "Ann".into(),
352 author_email: "ann@example.com".into(),
353 author_time: 1_700_000_000,
354 committer_name: "Ann".into(),
355 committer_email: "ann@example.com".into(),
356 committer_time: 1_700_000_000,
357 summary: format!("commit {n}"),
358 message: format!("commit {n}\n"),
359 }
360 }
361
362 #[test]
363 fn push_payload_caps_commits_and_reports_total() {
364 let commits: Vec<CommitInfo> = (0..25).map(commit).collect();
365 let before = "a".repeat(40);
366 let after = "c".repeat(40);
367 let v = push(
368 "https://forge.test",
369 &repo(),
370 "refs/heads/main",
371 &before,
372 &after,
373 &commits,
374 25,
375 );
376 assert_eq!(v["ref"], "refs/heads/main");
377 assert_eq!(v["before"], before.as_str());
378 assert_eq!(v["after"], after.as_str());
379 assert_eq!(v["total_commits"], 25);
380 let listed = v["commits"].as_array().expect("array");
381 assert_eq!(listed.len(), MAX_PAYLOAD_COMMITS);
382 assert_eq!(listed[0]["id"], format!("{:040}", 0));
383 assert_eq!(listed[0]["author"]["email"], "ann@example.com");
384 assert_eq!(listed[0]["timestamp"], "2023-11-14T22:13:20Z");
385 assert_eq!(
386 listed[0]["url"],
387 format!("https://forge.test/tahinli/proj/commit/{:040}", 0)
388 );
389 assert_eq!(
390 v["compare_url"],
391 format!("https://forge.test/tahinli/proj/compare/{before}...{after}")
392 );
393 }
394
395 #[test]
396 fn ref_change_and_ping_shapes() {
397 let v = ref_change("tag", "v1");
398 assert_eq!(v, json!({"ref": "v1", "ref_type": "tag"}));
399 let p = ping("hook1");
400 assert_eq!(p["hook_id"], "hook1");
401 assert!(p["zen"].is_string());
402 }
403}