cursus 0.5.2

Library crate for the cursus release management CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
//! [`SignedCommitGit`] decorator that creates verified commits via the GitHub Git Data API.
//!
//! See ADR-050 for the full design rationale.

use std::path::{Path, PathBuf};

use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};

// Encodes characters that would corrupt a URL path segment: space, ?, #, %.
// Control characters are already rejected by validate_branch_name.
// `/` is intentionally left unencoded — hierarchical refs like
// `cursus-release/main` map correctly to the GitHub API path.
// Unicode bytes are encoded by utf8_percent_encode automatically.
const BRANCH_PATH: &AsciiSet = &CONTROLS.add(b' ').add(b'?').add(b'#').add(b'%');
use std::sync::Arc;

use anyhow::Context as _;
use async_trait::async_trait;
use octocrab::Octocrab;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;

use crate::command::CommandRunner;
use crate::filesystem::Filesystem;
use crate::git::Git;
use crate::git::ref_format::validate_branch_name;
use crate::path::AbsolutePath;
use crate::redact::redact_credentials;

// ── GitHub API request / response types ──────────────────────────────────────

#[derive(Serialize)]
struct CreateBlobRequest<'a> {
	content: &'a str,
	encoding: &'a str,
}

#[derive(Deserialize)]
struct CreateBlobResponse {
	sha: String,
}

#[derive(Serialize)]
struct TreeItem {
	path: String,
	mode: &'static str,
	r#type: &'static str,
	sha: Option<String>,
}

#[derive(Serialize)]
struct CreateTreeRequest<'a> {
	base_tree: &'a str,
	tree: Vec<TreeItem>,
}

#[derive(Deserialize)]
struct CreateTreeResponse {
	sha: String,
}

#[derive(Serialize)]
struct CreateCommitRequest<'a> {
	message: &'a str,
	tree: &'a str,
	parents: Vec<&'a str>,
}

#[derive(Deserialize)]
struct CreateCommitResponse {
	sha: String,
}

#[derive(Serialize)]
struct UpdateRefRequest<'a> {
	sha: &'a str,
	force: bool,
}

#[derive(Serialize)]
struct CreateRefRequest<'a> {
	r#ref: &'a str,
	sha: &'a str,
}

// ── Internal state ────────────────────────────────────────────────────────────

struct PendingCommit {
	branch: String,
	sha: String,
}

struct State {
	staged: Vec<PathBuf>,
	pending: Option<PendingCommit>,
}

// ── Decorator ─────────────────────────────────────────────────────────────────

/// A [`Git`] decorator that produces Verified commits via the GitHub Git Data API.
///
/// When [`Git::commit`] is called, blobs, a tree, and a commit object are created
/// through GitHub's REST API. Omitting `author` and `committer` from the commit
/// request causes GitHub to fill them with the App's bot identity and sign the commit
/// with the web-flow GPG key, producing a Verified commit with no long-lived key
/// custody (ADR-050).
///
/// [`Git::push`] and [`Git::force_push_branch`] update the remote branch ref via
/// `PATCH /repos/{owner}/{repo}/git/refs/heads/{branch}` (using `force: false` and
/// `force: true` respectively), then run `git fetch origin {branch}` and
/// `git reset --hard FETCH_HEAD` to download the new commit object into the local
/// object store and sync the local branch ref, index, and working tree.
///
/// All other [`Git`] methods delegate to the wrapped inner implementation.
pub struct SignedCommitGit {
	inner: Arc<dyn Git>,
	fs: Arc<dyn Filesystem>,
	octocrab: Arc<Octocrab>,
	runner: Arc<dyn CommandRunner>,
	owner: String,
	repo: String,
	dry_run: bool,
	state: Mutex<State>,
}

impl std::fmt::Debug for SignedCommitGit {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("SignedCommitGit")
			.field("owner", &self.owner)
			.field("repo", &self.repo)
			.field("dry_run", &self.dry_run)
			.finish_non_exhaustive()
	}
}

impl SignedCommitGit {
	/// Creates a new `SignedCommitGit` decorator.
	///
	/// `runner` is used for the post-push `git fetch` / `git reset --hard` operations
	/// that sync the local working tree after a remote ref update.
	pub fn new(
		inner: Arc<dyn Git>,
		fs: Arc<dyn Filesystem>,
		octocrab: Arc<Octocrab>,
		runner: Arc<dyn CommandRunner>,
		owner: String,
		repo: String,
		dry_run: bool,
	) -> Self {
		Self {
			inner,
			fs,
			octocrab,
			runner,
			owner,
			repo,
			dry_run,
			state: Mutex::new(State {
				staged: Vec::new(),
				pending: None,
			}),
		}
	}

	async fn patch_ref_and_sync(&self, branch: &str, sha: &str, force: bool) -> anyhow::Result<()> {
		validate_branch_name(branch)?;
		upsert_branch_ref(&self.octocrab, &self.owner, &self.repo, branch, sha, force)
			.await
			.with_context(|| format!("failed to update remote ref for branch '{branch}'"))?;

		let cwd = self.inner.path().as_path();
		let fetch = self
			.runner
			.run_mut("git", &["fetch", "origin", branch], cwd)
			.await
			.context("git fetch failed after API ref update")?;
		if !fetch.status.success() {
			let raw = String::from_utf8_lossy(&fetch.stderr);
			let stderr = redact_credentials(&raw);
			anyhow::bail!("git fetch origin {branch} failed: {stderr}");
		}

		let reset = self
			.runner
			.run_mut("git", &["reset", "--hard", "FETCH_HEAD"], cwd)
			.await
			.context("git reset failed after API ref update")?;
		if !reset.status.success() {
			let raw = String::from_utf8_lossy(&reset.stderr);
			let stderr = redact_credentials(&raw);
			anyhow::bail!("git reset --hard FETCH_HEAD failed: {stderr}");
		}

		Ok(())
	}
}

// ── Low-level octocrab helpers ────────────────────────────────────────────────

async fn api_post<P: Serialize + ?Sized, R: serde::de::DeserializeOwned>(
	client: &Octocrab,
	url: String,
	body: &P,
) -> anyhow::Result<R> {
	let response = client
		._post(url, Some(body))
		.await
		.context("GitHub API POST failed")?;
	let status = response.status();
	let text = client
		.body_to_string(response)
		.await
		.context("failed to read GitHub API response body")?;
	if !status.is_success() {
		anyhow::bail!(
			"GitHub API returned {status}: {}",
			redact_credentials(&text)
		);
	}
	serde_json::from_str(&text).context("failed to deserialize GitHub API response")
}

async fn build_tree_items(
	client: &Octocrab,
	owner: &str,
	repo: &str,
	fs: &dyn Filesystem,
	staged: &[PathBuf],
	repo_root: &AbsolutePath,
) -> anyhow::Result<Vec<TreeItem>> {
	let mut items: Vec<TreeItem> = Vec::with_capacity(staged.len());
	for path in staged {
		let abs = AbsolutePath::new(path)
			.with_context(|| format!("staged path is not absolute: {}", path.display()))?;
		let rel = path.strip_prefix(repo_root.as_path()).with_context(|| {
			format!(
				"staged path {} is not under repo root {}",
				path.display(),
				repo_root.as_path().display()
			)
		})?;
		let rel_str = rel.to_string_lossy().into_owned();

		if fs.exists(&abs).await? {
			let bytes = fs.read(&abs).await?;
			let content = String::from_utf8(bytes).with_context(|| {
				format!(
					"staged file {} contains non-UTF-8 bytes and cannot be committed via \
					 the GitHub API in UTF-8 mode; set `[git].signed_commits = \"off\"` to \
					 use the local git binary instead",
					rel.display()
				)
			})?;
			let blob_req = CreateBlobRequest {
				content: &content,
				encoding: "utf-8",
			};
			let url = format!("/repos/{owner}/{repo}/git/blobs");
			let blob: CreateBlobResponse = api_post(client, url, &blob_req)
				.await
				.with_context(|| format!("failed to create blob for {}", rel.display()))?;
			items.push(TreeItem {
				path: rel_str,
				mode: "100644",
				r#type: "blob",
				sha: Some(blob.sha),
			});
		} else {
			// File was deleted (e.g. a consumed changeset) — null sha removes it.
			items.push(TreeItem {
				path: rel_str,
				mode: "100644",
				r#type: "blob",
				sha: None,
			});
		}
	}
	Ok(items)
}

/// Updates or creates a branch ref on the remote.
///
/// Tries `PATCH /git/refs/heads/{branch}` first. If GitHub returns 422
/// "Reference does not exist" (the branch is new), falls back to
/// `POST /git/refs` to create it. This handles both the initial prepare run
/// (branch does not exist on remote yet) and subsequent runs (branch already
/// exists and must be force-updated).
async fn upsert_branch_ref(
	client: &Octocrab,
	owner: &str,
	repo: &str,
	branch: &str,
	sha: &str,
	force: bool,
) -> anyhow::Result<()> {
	let encoded_branch = utf8_percent_encode(branch, BRANCH_PATH);
	let patch_url = format!("/repos/{owner}/{repo}/git/refs/heads/{encoded_branch}");
	let update_req = UpdateRefRequest { sha, force };
	let response = client
		._patch(patch_url, Some(&update_req))
		.await
		.context("GitHub API PATCH failed")?;
	let status = response.status();
	if status.is_success() {
		return Ok(());
	}
	let text = client.body_to_string(response).await.unwrap_or_default();
	// 422 "Reference does not exist" means the branch is new — create it instead.
	if status.as_u16() == 422 && text.contains("Reference does not exist") {
		let full_ref = format!("refs/heads/{branch}");
		let create_req = CreateRefRequest {
			r#ref: &full_ref,
			sha,
		};
		let post_url = format!("/repos/{owner}/{repo}/git/refs");
		let response = client
			._post(post_url, Some(&create_req))
			.await
			.context("GitHub API POST failed")?;
		let status = response.status();
		if !status.is_success() {
			let text = client.body_to_string(response).await.unwrap_or_default();
			anyhow::bail!(
				"GitHub API returned {status}: {}",
				redact_credentials(&text)
			);
		}
		return Ok(());
	}
	anyhow::bail!(
		"GitHub API returned {status}: {}",
		redact_credentials(&text)
	);
}

// ── Git trait impl ────────────────────────────────────────────────────────────

#[allow(clippy::too_many_lines)]
#[async_trait]
impl Git for SignedCommitGit {
	fn path(&self) -> &AbsolutePath {
		self.inner.path()
	}

	async fn head_sha(&self) -> anyhow::Result<String> {
		self.inner.head_sha().await
	}

	async fn is_dirty(&self) -> anyhow::Result<bool> {
		self.inner.is_dirty().await
	}

	async fn current_branch(&self) -> anyhow::Result<Option<String>> {
		self.inner.current_branch().await
	}

	async fn tag_exists(&self, tag: &str) -> anyhow::Result<bool> {
		self.inner.tag_exists(tag).await
	}

	async fn remote_origin_url(&self) -> anyhow::Result<Option<String>> {
		self.inner.remote_origin_url().await
	}

	async fn rev_list_count(&self, range: &str) -> anyhow::Result<usize> {
		self.inner.rev_list_count(range).await
	}

	async fn log_message(&self, rev: &str) -> anyhow::Result<String> {
		self.inner.log_message(rev).await
	}

	async fn log_subject(&self, rev: &str) -> anyhow::Result<String> {
		self.inner.log_subject(rev).await
	}

	async fn log_added_commit(&self, path: &Path) -> anyhow::Result<Option<String>> {
		self.inner.log_added_commit(path).await
	}

	async fn diff_tree_names(&self, commit: &str) -> anyhow::Result<Vec<String>> {
		self.inner.diff_tree_names(commit).await
	}

	async fn diff_names(&self, extra_args: &[&str]) -> anyhow::Result<Vec<String>> {
		self.inner.diff_names(extra_args).await
	}

	/// Stages files via the inner impl and records their paths for the API commit.
	async fn add(&self, files: &[PathBuf]) -> anyhow::Result<()> {
		self.inner.add(files).await?;
		let mut state = self.state.lock().await;
		state.staged.extend_from_slice(files);
		Ok(())
	}

	/// Creates a commit via the GitHub Git Data API.
	///
	/// Omitting `author` and `committer` from the request causes GitHub to sign
	/// the commit with the web-flow GPG key when authenticated via a GitHub App
	/// installation token.
	///
	/// In dry-run mode, logs the intended action and returns without making any
	/// API calls (explicit guard required because octocrab is not a
	/// [`CommandRunner`] and is not intercepted by [`crate::command::DryRunCommandRunner`]).
	async fn commit(&self, message: &str) -> anyhow::Result<()> {
		if self.dry_run {
			log::info!("(dry-run) would create API commit: {message}");
			return Ok(());
		}

		let staged = {
			let state = self.state.lock().await;
			if state.staged.is_empty() {
				return Ok(());
			}
			// Dedup while preserving order: a path may appear more than once if
			// `add()` is called multiple times with overlapping file lists.
			let mut seen = std::collections::HashSet::new();
			state
				.staged
				.iter()
				.filter(|p| seen.insert(p.as_path()))
				.cloned()
				.collect::<Vec<_>>()
		};

		let head = self.inner.head_sha().await?;
		let branch = self
			.inner
			.current_branch()
			.await?
			.context("cannot create API commit with a detached HEAD")?;
		let repo_root = self.inner.path();

		let tree_items = build_tree_items(
			&self.octocrab,
			&self.owner,
			&self.repo,
			&*self.fs,
			&staged,
			repo_root,
		)
		.await?;

		let tree_req = CreateTreeRequest {
			base_tree: &head,
			tree: tree_items,
		};
		let url = format!("/repos/{}/{}/git/trees", self.owner, self.repo);
		let tree_resp: CreateTreeResponse = api_post(&self.octocrab, url, &tree_req)
			.await
			.context("failed to create git tree")?;

		let commit_req = CreateCommitRequest {
			message,
			tree: &tree_resp.sha,
			parents: vec![&head],
		};
		let url = format!("/repos/{}/{}/git/commits", self.owner, self.repo);
		let commit_resp: CreateCommitResponse = api_post(&self.octocrab, url, &commit_req)
			.await
			.context("failed to create git commit")?;

		log::info!("Created API commit {}", commit_resp.sha);

		let mut state = self.state.lock().await;
		state.pending = Some(PendingCommit {
			branch,
			sha: commit_resp.sha,
		});
		state.staged.clear();

		Ok(())
	}

	async fn tag(&self, tag_name: &str, message: &str) -> anyhow::Result<()> {
		self.inner.tag(tag_name, message).await
	}

	/// Pushes to origin (non-forced) and syncs the local git state.
	///
	/// If a commit was made via the API, updates the remote ref with `force: false`
	/// and runs `git fetch` + `git reset --hard FETCH_HEAD` to bring the verified
	/// commit object into the local object store. Falls back to the inner push
	/// otherwise.
	async fn push(&self) -> anyhow::Result<()> {
		let pending = self.state.lock().await.pending.take();
		match pending {
			Some(p) => self.patch_ref_and_sync(&p.branch, &p.sha, false).await,
			None => self.inner.push().await,
		}
	}

	async fn checkout(&self, branch: &str) -> anyhow::Result<()> {
		self.inner.checkout(branch).await
	}

	async fn checkout_or_reset_branch(&self, branch: &str) -> anyhow::Result<()> {
		self.inner.checkout_or_reset_branch(branch).await
	}

	/// Force-pushes a named branch to origin and syncs the local git state.
	///
	/// If a commit was made via the API, updates the remote ref with `force: true`
	/// and runs `git fetch` + `git reset --hard FETCH_HEAD`. Falls back to the
	/// inner force-push otherwise.
	async fn force_push_branch(&self, branch: &str) -> anyhow::Result<()> {
		let pending = self.state.lock().await.pending.take();
		match pending {
			Some(p) => self.patch_ref_and_sync(branch, &p.sha, true).await,
			None => self.inner.force_push_branch(branch).await,
		}
	}

	async fn delete_tag(&self, tag: &str) -> anyhow::Result<()> {
		self.inner.delete_tag(tag).await
	}

	async fn push_tag(&self, tag: &str) -> anyhow::Result<()> {
		self.inner.push_tag(tag).await
	}
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
	use std::sync::Arc;

	use httpmock::MockServer;
	use octocrab::Octocrab;
	use serde_json::json;

	use crate::command::test_support::{DispatchingCommandRunner, RecordingCommandRunner};
	use crate::command::{CommandRunner, DryRunCommandRunner};
	use crate::filesystem::LocalFilesystem;
	use crate::git::{Git, GitWorkdir};
	use crate::path::AbsolutePath;

	use super::SignedCommitGit;

	fn make_git(runner: Arc<dyn CommandRunner>, root: &AbsolutePath) -> Arc<dyn Git> {
		Arc::new(GitWorkdir::new(runner, root.clone()))
	}

	fn make_octocrab(server: &MockServer) -> Arc<Octocrab> {
		Arc::new(
			Octocrab::builder()
				.base_uri(server.base_url())
				.unwrap()
				.build()
				.unwrap(),
		)
	}

	fn make_decorator(
		git: Arc<dyn Git>,
		octocrab: Arc<Octocrab>,
		runner: Arc<dyn CommandRunner>,
	) -> SignedCommitGit {
		SignedCommitGit::new(
			git,
			Arc::new(LocalFilesystem),
			octocrab,
			runner,
			"owner".to_string(),
			"repo".to_string(),
			false,
		)
	}

	fn make_decorator_dry_run(
		git: Arc<dyn Git>,
		octocrab: Arc<Octocrab>,
		runner: Arc<dyn CommandRunner>,
	) -> SignedCommitGit {
		SignedCommitGit::new(
			git,
			Arc::new(LocalFilesystem),
			octocrab,
			runner,
			"owner".to_string(),
			"repo".to_string(),
			true,
		)
	}

	/// Returns a [`DispatchingCommandRunner`] pre-configured so that
	/// `git rev-parse HEAD` returns `head_sha` and
	/// `git rev-parse --abbrev-ref HEAD` returns `branch`.
	fn git_runner(head_sha: &str, branch: &str) -> Arc<DispatchingCommandRunner> {
		Arc::new(
			DispatchingCommandRunner::new(0)
				.on_with_args_stdout(
					"git",
					vec![
						"rev-parse".to_string(),
						"--abbrev-ref".to_string(),
						"HEAD".to_string(),
					],
					0,
					format!("{branch}\n").into_bytes(),
				)
				.on_with_args_stdout(
					"git",
					vec!["rev-parse".to_string(), "HEAD".to_string()],
					0,
					format!("{head_sha}\n").into_bytes(),
				),
		)
	}

	#[tokio::test]
	async fn add_delegates_to_inner_and_records_paths() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = Arc::new(RecordingCommandRunner::new(0));
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();
		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);

		let file = dir.path().join("foo.txt");
		std::fs::write(&file, b"hello").unwrap();
		dec.add(std::slice::from_ref(&file)).await.unwrap();

		let calls = runner.invocations();
		assert!(calls.iter().any(|c| c.args.contains(&"add".to_string())));
		let state = dec.state.lock().await;
		assert_eq!(state.staged, vec![file]);
	}

	#[tokio::test]
	async fn commit_dry_run_makes_no_api_calls() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = Arc::new(RecordingCommandRunner::new(0));
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();
		// Register a catch-all mock so we can check it was never hit.
		let catch_all = server.mock(|when, then| {
			when.any_request();
			then.status(200).body("{}");
		});

		let dec = make_decorator_dry_run(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);

		let file = root.child("foo.txt");
		std::fs::write(file.as_path(), b"content").unwrap();
		dec.add(&[file.into_path_buf()]).await.unwrap();
		dec.commit("ci(release): version packages").await.unwrap();

		catch_all.assert_calls(0);
		assert!(dec.state.lock().await.pending.is_none());
	}

	#[tokio::test]
	async fn commit_with_no_staged_files_is_noop() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = Arc::new(RecordingCommandRunner::new(0));
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();
		let catch_all = server.mock(|when, then| {
			when.any_request();
			then.status(200).body("{}");
		});

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);

		dec.commit("ci(release): version packages").await.unwrap();
		catch_all.assert_calls(0);
	}

	#[tokio::test]
	async fn commit_creates_blob_tree_commit_and_stores_pending() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = git_runner("abc123", "main");
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		let blob_mock = server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/blobs");
			then.status(201).json_body(json!({ "sha": "blobsha" }));
		});
		let tree_mock = server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/trees");
			then.status(201).json_body(json!({ "sha": "treesha" }));
		});
		let commit_mock = server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/commits");
			then.status(201).json_body(json!({ "sha": "newsha" }));
		});

		let file = root.child("Cargo.toml");
		std::fs::write(file.as_path(), b"[package]").unwrap();

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);
		dec.add(&[file.into_path_buf()]).await.unwrap();
		dec.commit("ci(release): version packages").await.unwrap();

		blob_mock.assert();
		tree_mock.assert();
		commit_mock.assert();

		let state = dec.state.lock().await;
		assert!(
			state.staged.is_empty(),
			"staged should be cleared after commit"
		);
		let pending = state.pending.as_ref().expect("pending should be set");
		assert_eq!(pending.sha, "newsha");
		assert_eq!(pending.branch, "main");
	}

	#[tokio::test]
	async fn commit_fails_on_detached_head() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		// head_sha succeeds; current_branch returns None (detached HEAD).
		let runner = Arc::new(
			DispatchingCommandRunner::new(0)
				.on_with_args_stdout(
					"git",
					vec!["rev-parse".to_string(), "HEAD".to_string()],
					0,
					b"abc123\n".to_vec(),
				)
				.on_with_args_stdout(
					"git",
					vec![
						"rev-parse".to_string(),
						"--abbrev-ref".to_string(),
						"HEAD".to_string(),
					],
					0,
					b"HEAD\n".to_vec(), // "HEAD" means detached
				),
		);
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		let file = root.child("foo.txt");
		std::fs::write(file.as_path(), b"content").unwrap();

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);
		dec.add(&[file.into_path_buf()]).await.unwrap();
		let result = dec.commit("ci(release): version packages").await;

		assert!(result.is_err());
		assert!(
			result.unwrap_err().to_string().contains("detached HEAD"),
			"expected detached HEAD error"
		);
	}

	#[tokio::test]
	async fn commit_deduplicates_staged_paths() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = git_runner("abc123", "main");
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		// One blob POST expected even though the file is staged twice.
		let blob_mock = server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/blobs");
			then.status(201).json_body(json!({ "sha": "blobsha" }));
		});
		server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/trees");
			then.status(201).json_body(json!({ "sha": "treesha" }));
		});
		server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/commits");
			then.status(201).json_body(json!({ "sha": "newsha" }));
		});

		let file = root.child("Cargo.toml");
		std::fs::write(file.as_path(), b"[package]").unwrap();

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);
		// Add the same file twice.
		dec.add(&[file.as_path().to_path_buf()]).await.unwrap();
		dec.add(&[file.into_path_buf()]).await.unwrap();
		dec.commit("ci(release): version packages").await.unwrap();

		blob_mock.assert_calls(1);
	}

	#[tokio::test]
	async fn commit_handles_deleted_file() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = git_runner("abc123", "main");
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		// Deleted file should not trigger a blob POST.
		let blob_mock = server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/blobs");
			then.status(201).json_body(json!({ "sha": "blobsha" }));
		});
		let tree_mock = server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/trees");
			then.status(201).json_body(json!({ "sha": "treesha" }));
		});
		let commit_mock = server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/commits");
			then.status(201).json_body(json!({ "sha": "newsha" }));
		});

		// Deleted file — directory exists but file does not.
		let deleted = root.child(".cursus/some-changeset.md");
		std::fs::create_dir_all(deleted.as_path().parent().unwrap()).unwrap();

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);
		dec.add(&[deleted.into_path_buf()]).await.unwrap();
		dec.commit("ci(release): version packages").await.unwrap();

		blob_mock.assert_calls(0);
		tree_mock.assert();
		commit_mock.assert();
	}

	#[tokio::test]
	async fn push_with_pending_patches_ref_and_syncs_local() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = Arc::new(RecordingCommandRunner::new(0));
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		let patch_mock = server.mock(|when, then| {
			when.method(httpmock::Method::PATCH)
				.path("/repos/owner/repo/git/refs/heads/main")
				.json_body(json!({ "sha": "newsha", "force": false }));
			then.status(200).json_body(json!({}));
		});

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);

		{
			let mut state = dec.state.lock().await;
			state.pending = Some(super::PendingCommit {
				branch: "main".to_string(),
				sha: "newsha".to_string(),
			});
		}

		dec.push().await.unwrap();

		patch_mock.assert();
		let calls = runner.invocations();
		assert!(
			calls
				.iter()
				.any(|c| c.program == "git" && c.args.contains(&"fetch".to_string())),
			"expected git fetch call"
		);
		assert!(
			calls.iter().any(|c| c.program == "git"
				&& c.args.contains(&"reset".to_string())
				&& c.args.contains(&"FETCH_HEAD".to_string())),
			"expected git reset --hard FETCH_HEAD call"
		);
		assert!(dec.state.lock().await.pending.is_none());
	}

	#[tokio::test]
	async fn force_push_creates_branch_when_ref_does_not_exist() {
		// Simulates the first prepare run where the release branch doesn't exist
		// on the remote yet — PATCH returns 422, so we fall back to POST to create it.
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = Arc::new(RecordingCommandRunner::new(0));
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		// PATCH returns 422 "Reference does not exist".
		let patch_mock = server.mock(|when, then| {
			when.method(httpmock::Method::PATCH)
				.path("/repos/owner/repo/git/refs/heads/cursus-release/main");
			then.status(422)
				.json_body(json!({ "message": "Reference does not exist" }));
		});
		// POST creates the ref.
		let post_mock = server.mock(|when, then| {
			when.method(httpmock::Method::POST)
				.path("/repos/owner/repo/git/refs")
				.json_body(json!({
					"ref": "refs/heads/cursus-release/main",
					"sha": "newsha"
				}));
			then.status(201).json_body(json!({}));
		});

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);
		{
			let mut state = dec.state.lock().await;
			state.pending = Some(super::PendingCommit {
				branch: "cursus-release/main".to_string(),
				sha: "newsha".to_string(),
			});
		}

		dec.force_push_branch("cursus-release/main").await.unwrap();

		patch_mock.assert_calls(1);
		post_mock.assert_calls(1);
	}

	#[tokio::test]
	async fn push_without_pending_delegates_to_inner() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = Arc::new(RecordingCommandRunner::new(0));
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();
		let catch_all = server.mock(|when, then| {
			when.any_request();
			then.status(200).body("{}");
		});

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);

		dec.push().await.unwrap();

		catch_all.assert_calls(0);
		let calls = runner.invocations();
		assert!(
			calls
				.iter()
				.any(|c| c.program == "git" && c.args.contains(&"push".to_string())),
			"expected inner git push"
		);
	}

	#[tokio::test]
	async fn force_push_branch_with_pending_patches_ref_force_true() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = Arc::new(RecordingCommandRunner::new(0));
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		let patch_mock = server.mock(|when, then| {
			when.method(httpmock::Method::PATCH)
				.path("/repos/owner/repo/git/refs/heads/release-branch")
				.json_body(json!({ "sha": "newsha", "force": true }));
			then.status(200).json_body(json!({}));
		});

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);

		{
			let mut state = dec.state.lock().await;
			state.pending = Some(super::PendingCommit {
				branch: "main".to_string(),
				sha: "newsha".to_string(),
			});
		}

		dec.force_push_branch("release-branch").await.unwrap();
		patch_mock.assert();
	}

	#[tokio::test]
	async fn push_with_pending_clears_pending_even_on_api_error() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let runner = Arc::new(RecordingCommandRunner::new(0));
		let git = make_git(Arc::clone(&runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		server.mock(|when, then| {
			when.method(httpmock::Method::PATCH)
				.path("/repos/owner/repo/git/refs/heads/main");
			then.status(422).body("unprocessable entity");
		});

		let dec = make_decorator(
			git,
			make_octocrab(&server),
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
		);
		{
			let mut state = dec.state.lock().await;
			state.pending = Some(super::PendingCommit {
				branch: "main".to_string(),
				sha: "newsha".to_string(),
			});
		}

		let result = dec.push().await;
		assert!(result.is_err(), "expected error on 422");
		assert!(dec.state.lock().await.pending.is_none());
	}

	#[tokio::test]
	async fn dry_run_runner_suppresses_fetch_and_reset() {
		let dir = tempfile::tempdir().unwrap();
		let root = AbsolutePath::new(dir.path()).unwrap();
		std::fs::create_dir(dir.path().join(".git")).unwrap();

		let inner_runner = Arc::new(RecordingCommandRunner::new(0));
		let dry_runner = Arc::new(DryRunCommandRunner::new(
			Arc::clone(&inner_runner) as Arc<dyn CommandRunner>
		));

		let git = make_git(Arc::clone(&dry_runner) as Arc<dyn CommandRunner>, &root);
		let server = MockServer::start();

		server.mock(|when, then| {
			when.method(httpmock::Method::PATCH);
			then.status(200).json_body(json!({}));
		});

		let dec = SignedCommitGit::new(
			git,
			Arc::new(LocalFilesystem),
			make_octocrab(&server),
			Arc::clone(&dry_runner) as Arc<dyn CommandRunner>,
			"owner".to_string(),
			"repo".to_string(),
			false,
		);

		{
			let mut state = dec.state.lock().await;
			state.pending = Some(super::PendingCommit {
				branch: "main".to_string(),
				sha: "newsha".to_string(),
			});
		}

		dec.push().await.unwrap();

		assert!(
			inner_runner.invocations().is_empty(),
			"DryRunCommandRunner should suppress fetch and reset"
		);
	}
}