1use crate::backends::{ExternalId, ExternalTask, Status};
4use crate::engine;
5use crate::engine::review_gate;
6use crate::engine::tasks::TaskManager;
7use crate::github::http::{GhHttp, RulesetCreateKind, classify_ruleset_create_error};
8use crate::github::types::{GitHubCheckRun, RequiredStatusCheck};
9use crate::plan;
10use crate::store;
11use crate::store::TaskStore;
12use std::sync::Arc;
13
14const KV_PENDING: &str = "pending";
15const KV_APPLIED: &str = "applied";
16const KV_REFUSED: &str = "refused";
17
18pub(crate) fn is_ci_bootstrap_task(title: &str, body: &str) -> bool {
19 if plan::is_ci_bootstrap_body(body)
20 || plan::marker_id(body).is_some_and(|id| plan::is_ci_bootstrap_id(&id))
21 {
22 return true;
23 }
24 title
25 .split_whitespace()
26 .next()
27 .is_some_and(plan::is_ci_bootstrap_id)
28}
29
30pub(crate) fn kv_key(repo: &str, task_id: &str) -> String {
31 format!("ci-bootstrap:{repo}:{task_id}")
32}
33
34pub(crate) async fn hold_after_merge(
36 task: &ExternalTask,
37 store: &Arc<TaskStore>,
38 repo: &str,
39) -> bool {
40 if !is_ci_bootstrap_task(&task.title, &task.body) {
41 return false;
42 }
43 let key = kv_key(repo, &task.id.0);
44 match store.kv_get(&key).await {
45 Ok(Some(state)) if state == KV_APPLIED => false,
46 Ok(Some(_)) => true,
47 Ok(None) => {
48 if let Err(e) = store.kv_set(&key, KV_PENDING).await {
49 tracing::warn!(
50 task_id = %task.id.0,
51 err = %e,
52 "failed to record CI bootstrap pending"
53 );
54 }
55 true
56 }
57 Err(e) => {
58 tracing::warn!(
59 task_id = %task.id.0,
60 err = %e,
61 "failed to read CI bootstrap state"
62 );
63 true
64 }
65 }
66}
67
68pub(crate) async fn apply_pending(
69 store: &Arc<TaskStore>,
70 task_manager: &Arc<TaskManager>,
71 repo: &str,
72) -> anyhow::Result<()> {
73 let gh = GhHttp::owner()?;
74 apply_pending_with(&gh, store, task_manager, repo).await
75}
76
77pub(crate) async fn apply_pending_with(
78 gh: &GhHttp,
79 store: &Arc<TaskStore>,
80 task_manager: &Arc<TaskManager>,
81 repo: &str,
82) -> anyhow::Result<()> {
83 let prefix = format!("ci-bootstrap:{repo}:");
84 let entries = store.kv_list_prefix(&prefix).await?;
85 for (key, state) in entries {
86 if state == KV_APPLIED {
87 continue;
88 }
89 let Some(task_id) = key.strip_prefix(&prefix) else {
90 continue;
91 };
92 if let Err(e) = apply_one(gh, store, task_manager, repo, task_id, &state).await {
93 tracing::warn!(task_id, err = %e, "CI bootstrap ruleset apply failed");
94 }
95 }
96 Ok(())
97}
98
99pub(crate) fn checks_ready_for_ruleset(
100 runs: &[GitHubCheckRun],
101 statuses: &[(String, String)],
102) -> Option<Vec<RequiredStatusCheck>> {
103 let mut ready: Vec<RequiredStatusCheck> = Vec::new();
104 let mut pending = false;
105 let mut failed = false;
106
107 for run in runs {
108 if review_gate::is_own_check(&run.name) {
109 continue;
110 }
111 match run.status.as_str() {
112 "completed" => match run.conclusion.as_deref() {
113 Some("success") => {
114 let integration_id = run.app.as_ref().map(|app| app.id).filter(|&id| id > 0);
115 if !ready.iter().any(|check| check.context == run.name) {
116 ready.push(RequiredStatusCheck {
117 context: run.name.clone(),
118 integration_id,
119 });
120 }
121 }
122 Some("skipped" | "neutral") => {}
123 Some(_) => failed = true,
124 None => pending = true,
125 },
126 _ => pending = true,
127 }
128 }
129
130 for (context, state) in statuses {
131 if review_gate::is_own_check(context) {
132 continue;
133 }
134 match state.as_str() {
135 "pending" => pending = true,
136 "success" => {
137 if !ready.iter().any(|check| &check.context == context) {
138 ready.push(RequiredStatusCheck {
139 context: context.clone(),
140 integration_id: None,
141 });
142 }
143 }
144 "failure" | "error" => failed = true,
145 _ => {}
146 }
147 }
148
149 if pending || failed || ready.is_empty() {
150 None
151 } else {
152 Some(ready)
153 }
154}
155
156async fn apply_one(
157 gh: &GhHttp,
158 store: &Arc<TaskStore>,
159 task_manager: &Arc<TaskManager>,
160 repo: &str,
161 task_id: &str,
162 state: &str,
163) -> anyhow::Result<()> {
164 if store::opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
165 .await
166 .is_none()
167 {
168 return Ok(());
169 }
170
171 let branch = gh.get_default_branch(repo).await?;
172 let required = gh.get_required_status_check_contexts(repo, &branch).await?;
173 if !required.is_empty() {
174 return finish_applied(store, task_manager, task_id, repo).await;
175 }
176
177 reopen_if_closed(gh, repo, task_id).await;
179
180 if state == KV_REFUSED {
181 return Ok(());
182 }
183
184 let sha = gh.get_branch_sha(repo, &branch).await?;
185 let runs = gh.get_check_runs(repo, &sha).await?;
186 let statuses = gh.get_commit_status_contexts(repo, &sha).await?;
187 let Some(checks) = checks_ready_for_ruleset(&runs, &statuses) else {
188 return Ok(());
189 };
190
191 match gh.create_required_check_ruleset(repo, &checks).await {
192 Ok(()) => finish_applied(store, task_manager, task_id, repo).await,
193 Err(e) => {
194 let err = e.to_string();
195 match classify_ruleset_create_error(&err) {
196 RulesetCreateKind::NameTaken => {
197 finish_applied(store, task_manager, task_id, repo).await
198 }
199 RulesetCreateKind::CheckNeverRun | RulesetCreateKind::Retryable => Ok(()),
200 RulesetCreateKind::Refused | RulesetCreateKind::Other => {
201 comment_refused(gh, repo, task_id, &err).await;
202 store.kv_set(&kv_key(repo, task_id), KV_REFUSED).await?;
203 Ok(())
204 }
205 }
206 }
207 }
208}
209
210async fn finish_applied(
211 store: &Arc<TaskStore>,
212 task_manager: &Arc<TaskManager>,
213 task_id: &str,
214 repo: &str,
215) -> anyhow::Result<()> {
216 store.kv_set(&kv_key(repo, task_id), KV_APPLIED).await?;
217 task_manager
218 .update_task_status(&ExternalId(task_id.to_string()), Status::Done)
219 .await?;
220 Ok(())
221}
222
223async fn reopen_if_closed(gh: &GhHttp, repo: &str, task_id: &str) {
224 match gh.get_issue(repo, task_id).await {
225 Ok(issue) if issue.state.eq_ignore_ascii_case("closed") => {
226 if let Err(e) = gh.reopen_issue(repo, task_id).await {
227 tracing::warn!(
228 task_id,
229 err = %e,
230 "failed to reopen CI bootstrap issue"
231 );
232 }
233 }
234 Ok(_) => {}
235 Err(e) => {
236 tracing::warn!(
237 task_id,
238 err = %e,
239 "failed to read CI bootstrap issue"
240 );
241 }
242 }
243}
244
245async fn comment_refused(gh: &GhHttp, repo: &str, task_id: &str, err: &str) {
246 let body = format!(
247 "GitHub refused a required-checks ruleset on the default branch ({err}). Turn branch protection on for this repository. Later tasks stay waiting until that happens.{}",
248 engine::orch_footer()
249 );
250 if let Err(e) = gh.add_comment(repo, task_id, &body).await {
251 tracing::warn!(
252 task_id,
253 err = %e,
254 "failed to comment on CI bootstrap ruleset refusal"
255 );
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262 use crate::backends::ExternalBackend;
263 use crate::backends::test_helpers::NoopBackend;
264 use crate::github::types::GitHubApp;
265 use crate::plan::{CI_BOOTSTRAP_MARKER, ci_bootstrap_task, issue_body};
266 use crate::store::TaskStatus;
267 use crate::store::UpsertExternal;
268 use std::env;
269 use std::ffi::OsString;
270 use wiremock::matchers::{method, path};
271 use wiremock::{Mock, MockServer, ResponseTemplate};
272
273 struct EnvVarGuard {
274 key: &'static str,
275 previous: Option<OsString>,
276 }
277
278 impl EnvVarGuard {
279 fn set(key: &'static str, value: &str) -> Self {
280 let previous = env::var_os(key);
281 unsafe { env::set_var(key, value) };
283 Self { key, previous }
284 }
285 }
286
287 impl Drop for EnvVarGuard {
288 fn drop(&mut self) {
289 match self.previous.take() {
290 Some(value) => unsafe { env::set_var(self.key, value) },
292 None => unsafe { env::remove_var(self.key) },
294 }
295 }
296 }
297
298 fn run(
299 name: &str,
300 status: &str,
301 conclusion: Option<&str>,
302 app_id: Option<i64>,
303 ) -> GitHubCheckRun {
304 GitHubCheckRun {
305 id: 1,
306 name: name.to_string(),
307 status: status.to_string(),
308 conclusion: conclusion.map(String::from),
309 app: app_id.map(|id| GitHubApp { id }),
310 }
311 }
312
313 fn bootstrap_body() -> String {
314 issue_body(
315 &ci_bootstrap_task(false),
316 "acme/app",
317 "main",
318 "docs/ROADMAP.md",
319 )
320 }
321
322 #[test]
323 fn is_ci_bootstrap_task_reads_the_body_marker() {
324 assert!(is_ci_bootstrap_task(
325 "CI-01 Set up CI and tests",
326 &bootstrap_body()
327 ));
328 assert!(is_ci_bootstrap_task("CI-01", ""));
329 assert!(is_ci_bootstrap_task("ci-01 extra", ""));
330 assert!(is_ci_bootstrap_task(
331 "other",
332 &format!("{CI_BOOTSTRAP_MARKER}\n")
333 ));
334 assert!(!is_ci_bootstrap_task("M1-01 Set up the workspace", "goal"));
335 }
336
337 #[test]
338 fn checks_ready_for_ruleset_waits_until_real_checks_pass() {
339 assert!(checks_ready_for_ruleset(&[], &[]).is_none());
340 assert!(checks_ready_for_ruleset(&[run("test", "in_progress", None, None)], &[]).is_none());
341 assert!(
342 checks_ready_for_ruleset(&[run("test", "completed", Some("failure"), None)], &[])
343 .is_none()
344 );
345 assert!(
346 checks_ready_for_ruleset(
347 &[run("orch/review", "completed", Some("success"), None)],
348 &[]
349 )
350 .is_none()
351 );
352 let ready = checks_ready_for_ruleset(
353 &[
354 run("test", "completed", Some("success"), Some(15368)),
355 run("review-gate", "completed", Some("success"), None),
356 ],
357 &[],
358 )
359 .unwrap();
360 assert_eq!(
361 ready,
362 vec![RequiredStatusCheck {
363 context: "test".to_string(),
364 integration_id: Some(15368),
365 }]
366 );
367 }
368
369 #[tokio::test]
370 async fn hold_after_merge_records_pending_for_a_bootstrap_task() {
371 let store = Arc::new(TaskStore::open_memory().await.unwrap());
372 let task = ExternalTask {
373 id: ExternalId("12".to_string()),
374 title: "CI-01 Set up CI and tests".to_string(),
375 body: bootstrap_body(),
376 state: "open".to_string(),
377 labels: vec![],
378 author: String::new(),
379 created_at: String::new(),
380 updated_at: String::new(),
381 url: String::new(),
382 };
383 assert!(hold_after_merge(&task, &store, "o/r").await);
384 assert_eq!(
385 store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
386 Some(KV_PENDING)
387 );
388 store
389 .kv_set(&kv_key("o/r", "12"), KV_APPLIED)
390 .await
391 .unwrap();
392 assert!(!hold_after_merge(&task, &store, "o/r").await);
393 }
394
395 #[tokio::test]
396 async fn apply_pending_dones_when_required_checks_already_exist() {
397 let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
398 let server = MockServer::start().await;
399 Mock::given(method("GET"))
400 .and(path("/repos/o/r"))
401 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
402 "default_branch": "main"
403 })))
404 .mount(&server)
405 .await;
406 Mock::given(method("GET"))
407 .and(path("/repos/o/r/branches/main/protection"))
408 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
409 "required_status_checks": {
410 "checks": [{ "context": "test", "app_id": 15368 }]
411 }
412 })))
413 .mount(&server)
414 .await;
415 Mock::given(method("GET"))
416 .and(path("/repos/o/r/rules/branches/main"))
417 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
418 .mount(&server)
419 .await;
420
421 let store = Arc::new(TaskStore::open_memory().await.unwrap());
422 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
423 let task_manager = Arc::new(TaskManager::with_store(
424 backend,
425 Arc::clone(&store),
426 "o/r".to_string(),
427 ));
428 let id = store
429 .upsert_external(&UpsertExternal {
430 repo: "o/r",
431 ext_id: "12",
432 title: "CI-01 Set up CI and tests",
433 body: &bootstrap_body(),
434 author: "u",
435 url: "",
436 labels: &[],
437 origin: "github",
438 })
439 .await
440 .unwrap();
441 store.update_status(id, TaskStatus::Approved).await.unwrap();
442 store
443 .kv_set(&kv_key("o/r", "12"), KV_PENDING)
444 .await
445 .unwrap();
446
447 let gh = GhHttp::for_test(server.uri(), None);
448 apply_pending_with(&gh, &store, &task_manager, "o/r")
449 .await
450 .unwrap();
451
452 let stored = store.get(id).await.unwrap();
453 assert_eq!(stored.status, TaskStatus::Done);
454 assert_eq!(
455 store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
456 Some(KV_APPLIED)
457 );
458 }
459
460 #[tokio::test]
461 async fn apply_pending_creates_a_ruleset_when_default_branch_checks_pass() {
462 let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
463 let server = MockServer::start().await;
464 Mock::given(method("GET"))
465 .and(path("/repos/o/r"))
466 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
467 "default_branch": "main"
468 })))
469 .mount(&server)
470 .await;
471 Mock::given(method("GET"))
472 .and(path("/repos/o/r/branches/main/protection"))
473 .respond_with(
474 ResponseTemplate::new(404)
475 .set_body_string("{\"message\":\"Branch not protected\"}"),
476 )
477 .mount(&server)
478 .await;
479 Mock::given(method("GET"))
480 .and(path("/repos/o/r/rules/branches/main"))
481 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
482 .mount(&server)
483 .await;
484 Mock::given(method("GET"))
485 .and(path("/repos/o/r/branches/main"))
486 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
487 "commit": { "sha": "deadbeef" }
488 })))
489 .mount(&server)
490 .await;
491 Mock::given(method("GET"))
492 .and(path("/repos/o/r/commits/deadbeef/check-runs"))
493 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
494 "total_count": 1,
495 "check_runs": [{
496 "id": 1,
497 "name": "test",
498 "status": "completed",
499 "conclusion": "success",
500 "app": { "id": 15368 }
501 }]
502 })))
503 .mount(&server)
504 .await;
505 Mock::given(method("GET"))
506 .and(path("/repos/o/r/commits/deadbeef/status"))
507 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
508 "state": "success",
509 "total_count": 0,
510 "statuses": []
511 })))
512 .mount(&server)
513 .await;
514 Mock::given(method("POST"))
515 .and(path("/repos/o/r/rulesets"))
516 .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
517 "id": 9,
518 "name": "orch required checks"
519 })))
520 .expect(1)
521 .mount(&server)
522 .await;
523
524 let store = Arc::new(TaskStore::open_memory().await.unwrap());
525 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
526 let task_manager = Arc::new(TaskManager::with_store(
527 backend,
528 Arc::clone(&store),
529 "o/r".to_string(),
530 ));
531 let id = store
532 .upsert_external(&UpsertExternal {
533 repo: "o/r",
534 ext_id: "12",
535 title: "CI-01 Set up CI and tests",
536 body: &bootstrap_body(),
537 author: "u",
538 url: "",
539 labels: &[],
540 origin: "github",
541 })
542 .await
543 .unwrap();
544 store.update_status(id, TaskStatus::Approved).await.unwrap();
545 store
546 .kv_set(&kv_key("o/r", "12"), KV_PENDING)
547 .await
548 .unwrap();
549
550 let gh = GhHttp::for_test(server.uri(), None);
551 apply_pending_with(&gh, &store, &task_manager, "o/r")
552 .await
553 .unwrap();
554
555 let stored = store.get(id).await.unwrap();
556 assert_eq!(stored.status, TaskStatus::Done);
557 assert_eq!(
558 store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
559 Some(KV_APPLIED)
560 );
561 }
562
563 #[tokio::test]
564 async fn apply_pending_comments_and_holds_when_github_refuses_the_ruleset() {
565 let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
566 let server = MockServer::start().await;
567 Mock::given(method("GET"))
568 .and(path("/repos/o/r"))
569 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
570 "default_branch": "main"
571 })))
572 .mount(&server)
573 .await;
574 Mock::given(method("GET"))
575 .and(path("/repos/o/r/branches/main/protection"))
576 .respond_with(
577 ResponseTemplate::new(404)
578 .set_body_string("{\"message\":\"Branch not protected\"}"),
579 )
580 .mount(&server)
581 .await;
582 Mock::given(method("GET"))
583 .and(path("/repos/o/r/rules/branches/main"))
584 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
585 .mount(&server)
586 .await;
587 Mock::given(method("GET"))
588 .and(path("/repos/o/r/branches/main"))
589 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
590 "commit": { "sha": "deadbeef" }
591 })))
592 .mount(&server)
593 .await;
594 Mock::given(method("GET"))
595 .and(path("/repos/o/r/commits/deadbeef/check-runs"))
596 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
597 "total_count": 1,
598 "check_runs": [{
599 "id": 1,
600 "name": "test",
601 "status": "completed",
602 "conclusion": "success",
603 "app": { "id": 15368 }
604 }]
605 })))
606 .mount(&server)
607 .await;
608 Mock::given(method("GET"))
609 .and(path("/repos/o/r/commits/deadbeef/status"))
610 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
611 "state": "success",
612 "total_count": 0,
613 "statuses": []
614 })))
615 .mount(&server)
616 .await;
617 Mock::given(method("POST"))
618 .and(path("/repos/o/r/rulesets"))
619 .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
620 "message": "Upgrade to GitHub Pro or make this repository public to enable this feature."
621 })))
622 .mount(&server)
623 .await;
624 Mock::given(method("POST"))
625 .and(path("/repos/o/r/issues/12/comments"))
626 .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
627 "id": 1
628 })))
629 .expect(1)
630 .mount(&server)
631 .await;
632
633 let store = Arc::new(TaskStore::open_memory().await.unwrap());
634 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
635 let task_manager = Arc::new(TaskManager::with_store(
636 backend,
637 Arc::clone(&store),
638 "o/r".to_string(),
639 ));
640 let id = store
641 .upsert_external(&UpsertExternal {
642 repo: "o/r",
643 ext_id: "12",
644 title: "CI-01 Set up CI and tests",
645 body: &bootstrap_body(),
646 author: "u",
647 url: "",
648 labels: &[],
649 origin: "github",
650 })
651 .await
652 .unwrap();
653 store.update_status(id, TaskStatus::Approved).await.unwrap();
654 store
655 .kv_set(&kv_key("o/r", "12"), KV_PENDING)
656 .await
657 .unwrap();
658
659 let gh = GhHttp::for_test(server.uri(), None);
660 apply_pending_with(&gh, &store, &task_manager, "o/r")
661 .await
662 .unwrap();
663
664 let stored = store.get(id).await.unwrap();
665 assert_eq!(stored.status, TaskStatus::Approved);
666 assert_eq!(
667 store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
668 Some(KV_REFUSED)
669 );
670 }
671
672 #[tokio::test]
673 async fn apply_pending_reopens_a_closed_issue_and_creates_the_ruleset() {
674 let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
675 let server = MockServer::start().await;
676 Mock::given(method("GET"))
677 .and(path("/repos/o/r"))
678 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
679 "default_branch": "main"
680 })))
681 .mount(&server)
682 .await;
683 Mock::given(method("GET"))
684 .and(path("/repos/o/r/branches/main/protection"))
685 .respond_with(
686 ResponseTemplate::new(404)
687 .set_body_string("{\"message\":\"Branch not protected\"}"),
688 )
689 .mount(&server)
690 .await;
691 Mock::given(method("GET"))
692 .and(path("/repos/o/r/rules/branches/main"))
693 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
694 .mount(&server)
695 .await;
696 Mock::given(method("GET"))
697 .and(path("/repos/o/r/issues/12"))
698 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
699 "number": 12,
700 "id": 120,
701 "title": "CI-01 Set up CI and tests",
702 "body": "",
703 "state": "closed",
704 "labels": [],
705 "user": { "login": "u" },
706 "created_at": "",
707 "updated_at": "",
708 "html_url": ""
709 })))
710 .mount(&server)
711 .await;
712 Mock::given(method("PATCH"))
713 .and(path("/repos/o/r/issues/12"))
714 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
715 "number": 12,
716 "id": 120,
717 "title": "CI-01 Set up CI and tests",
718 "body": "",
719 "state": "open",
720 "labels": [],
721 "user": { "login": "u" },
722 "created_at": "",
723 "updated_at": "",
724 "html_url": ""
725 })))
726 .expect(1)
727 .mount(&server)
728 .await;
729 Mock::given(method("GET"))
730 .and(path("/repos/o/r/branches/main"))
731 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
732 "commit": { "sha": "deadbeef" }
733 })))
734 .mount(&server)
735 .await;
736 Mock::given(method("GET"))
737 .and(path("/repos/o/r/commits/deadbeef/check-runs"))
738 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
739 "total_count": 1,
740 "check_runs": [{
741 "id": 1,
742 "name": "test",
743 "status": "completed",
744 "conclusion": "success",
745 "app": { "id": 15368 }
746 }]
747 })))
748 .mount(&server)
749 .await;
750 Mock::given(method("GET"))
751 .and(path("/repos/o/r/commits/deadbeef/status"))
752 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
753 "state": "success",
754 "total_count": 0,
755 "statuses": []
756 })))
757 .mount(&server)
758 .await;
759 Mock::given(method("POST"))
760 .and(path("/repos/o/r/rulesets"))
761 .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
762 "id": 9,
763 "name": "orch required checks"
764 })))
765 .expect(1)
766 .mount(&server)
767 .await;
768
769 let store = Arc::new(TaskStore::open_memory().await.unwrap());
770 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
771 let task_manager = Arc::new(TaskManager::with_store(
772 backend,
773 Arc::clone(&store),
774 "o/r".to_string(),
775 ));
776 let id = store
777 .upsert_external(&UpsertExternal {
778 repo: "o/r",
779 ext_id: "12",
780 title: "CI-01 Set up CI and tests",
781 body: &bootstrap_body(),
782 author: "u",
783 url: "",
784 labels: &[],
785 origin: "github",
786 })
787 .await
788 .unwrap();
789 store.update_status(id, TaskStatus::Done).await.unwrap();
790 store
791 .kv_set(&kv_key("o/r", "12"), KV_PENDING)
792 .await
793 .unwrap();
794
795 let gh = GhHttp::for_test(server.uri(), None);
796 apply_pending_with(&gh, &store, &task_manager, "o/r")
797 .await
798 .unwrap();
799
800 let stored = store.get(id).await.unwrap();
801 assert_eq!(stored.status, TaskStatus::Done);
802 assert_eq!(
803 store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
804 Some(KV_APPLIED)
805 );
806 }
807}