monochange_github 0.1.0

GitHub release payload rendering and publishing for monochange
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
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
#![forbid(clippy::indexing_slicing)]

//! # `monochange_github`
//!
//! <!-- {=monochangeGithubCrateDocs|trim|linePrefix:"//! ":true} -->
//! `monochange_github` turns `monochange` release manifests into GitHub automation requests.
//!
//! Reach for this crate when you want to preview or publish GitHub releases and release pull requests using the same structured release data that powers changelog files and release manifests.
//!
//! ## Why use it?
//!
//! - derive GitHub release payloads and release-PR bodies from `monochange`'s structured release manifest
//! - keep GitHub automation aligned with changelog rendering and release targets
//! - reuse one publishing path for dry-run previews and real repository updates
//!
//! ## Best for
//!
//! - building GitHub release automation on top of `mc release`
//! - previewing would-be GitHub releases and release PRs in CI before publishing
//! - converting grouped or package release targets into repository automation payloads
//!
//! ## Public entry points
//!
//! - `build_release_requests(config, manifest)` converts a release manifest into GitHub release requests
//! - `publish_release_requests(requests)` publishes requests through the GitHub API via `octocrab`
//! - `build_release_pull_request_request(config, manifest)` converts a release manifest into a GitHub release-PR request
//! - `publish_release_pull_request(root, request, tracked_paths)` creates or updates a release PR through `git` and the GitHub API
//!
//! ## Example
//!
//! ```rust
//! use monochange_core::ProviderBotSettings;
//! use monochange_core::ProviderMergeRequestSettings;
//! use monochange_core::ProviderReleaseSettings;
//! use monochange_core::SourceConfiguration;
//! use monochange_core::SourceProvider;
//! use monochange_core::ReleaseManifest;
//! use monochange_core::ReleaseManifestPlan;
//! use monochange_core::ReleaseManifestTarget;
//! use monochange_core::ReleaseOwnerKind;
//! use monochange_core::VersionFormat;
//! use monochange_github::build_release_requests;
//!
//! let manifest = ReleaseManifest {
//!     command: "release".to_string(),
//!     dry_run: true,
//!     version: Some("1.2.0".to_string()),
//!     group_version: Some("1.2.0".to_string()),
//!     release_targets: vec![ReleaseManifestTarget {
//!         id: "sdk".to_string(),
//!         kind: ReleaseOwnerKind::Group,
//!         version: "1.2.0".to_string(),
//!         tag: true,
//!         release: true,
//!         version_format: VersionFormat::Primary,
//!         tag_name: "v1.2.0".to_string(),
//!         members: vec!["core".to_string(), "app".to_string()],
//!         rendered_title: "1.2.0 (2026-04-06)".to_string(),
//!         rendered_changelog_title: "[1.2.0](https://example.com) (2026-04-06)".to_string(),
//!     }],
//!     released_packages: vec!["workflow-core".to_string(), "workflow-app".to_string()],
//!     changed_files: Vec::new(),
//!     changesets: Vec::new(),
//!     changelogs: Vec::new(),
//!     deleted_changesets: Vec::new(),
//!     plan: ReleaseManifestPlan {
//!         workspace_root: std::path::PathBuf::from("."),
//!         decisions: Vec::new(),
//!         groups: Vec::new(),
//!         warnings: Vec::new(),
//!         unresolved_items: Vec::new(),
//!         compatibility_evidence: Vec::new(),
//!     },
//! };
//! let github = SourceConfiguration {
//!     provider: SourceProvider::GitHub,
//!     owner: "ifiokjr".to_string(),
//!     repo: "monochange".to_string(),
//!     host: None,
//!     api_url: None,
//!     releases: ProviderReleaseSettings::default(),
//!     pull_requests: ProviderMergeRequestSettings::default(),
//!     bot: ProviderBotSettings::default(),
//! };
//!
//! let requests = build_release_requests(&github, &manifest);
//!
//! assert_eq!(requests.len(), 1);
//! assert_eq!(requests[0].tag_name, "v1.2.0");
//! assert_eq!(requests[0].repository, "ifiokjr/monochange");
//! ```
//! <!-- {/monochangeGithubCrateDocs} -->

use std::env;
use std::fmt::Write as _;
use std::path::Path;
use std::path::PathBuf;
use std::sync::OnceLock;
use std::thread;

use monochange_core::CommitMessage;
use monochange_core::HostedActorRef;
use monochange_core::HostedActorSourceKind;
use monochange_core::HostedIssueCommentOperation;
use monochange_core::HostedIssueCommentOutcome;
use monochange_core::HostedIssueCommentPlan;
use monochange_core::HostedIssueRef;
use monochange_core::HostedIssueRelationshipKind;
use monochange_core::HostedReviewRequestKind;
use monochange_core::HostedReviewRequestRef;
use monochange_core::HostedSourceAdapter;
use monochange_core::HostedSourceFeatures;
use monochange_core::HostingCapabilities;
use monochange_core::HostingProviderKind;
use monochange_core::MonochangeError;
use monochange_core::MonochangeResult;
use monochange_core::PreparedChangeset;
use monochange_core::ProviderReleaseNotesSource;
use monochange_core::ReleaseManifest;
use monochange_core::ReleaseManifestTarget;
use monochange_core::ReleaseOwnerKind;
use monochange_core::RetargetOperation;
use monochange_core::RetargetProviderOperation;
use monochange_core::RetargetProviderResult;
use monochange_core::RetargetTagResult;
use monochange_core::SourceCapabilities;
use monochange_core::SourceChangeRequest;
use monochange_core::SourceChangeRequestOperation;
use monochange_core::SourceChangeRequestOutcome;
use monochange_core::SourceConfiguration;
use monochange_core::SourceProvider;
use monochange_core::SourceReleaseOperation;
use monochange_core::SourceReleaseOutcome;
use monochange_core::SourceReleaseRequest;
use monochange_core::git::git_checkout_branch_command;
use monochange_core::git::git_command_output;
use monochange_core::git::git_commit_paths_command;
use monochange_core::git::git_current_branch;
use monochange_core::git::git_error_detail;
use monochange_core::git::git_head_commit;
use monochange_core::git::git_push_branch_command;
use monochange_core::git::git_stage_paths_command;
use monochange_core::git::run_command;
use monochange_core::git::run_commit_command_allow_nothing_to_commit;
use octocrab::Octocrab;
use regex::Regex;
use serde::Deserialize;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::json;
use tokio::runtime::Builder as RuntimeBuilder;
use urlencoding::encode;

pub type GitHubReleaseRequest = SourceReleaseRequest;
pub type GitHubReleaseOperation = SourceReleaseOperation;
pub type GitHubReleaseOutcome = SourceReleaseOutcome;
pub type GitHubPullRequestRequest = SourceChangeRequest;
pub type GitHubPullRequestOperation = SourceChangeRequestOperation;
pub type GitHubPullRequestOutcome = SourceChangeRequestOutcome;

/// Return the hosted-source capabilities supported by the GitHub provider.
#[must_use]
pub const fn source_capabilities() -> SourceCapabilities {
	SourceCapabilities {
		draft_releases: true,
		prereleases: true,
		generated_release_notes: true,
		auto_merge_change_requests: true,
		released_issue_comments: true,
		requires_host: false,
	}
}

/// Validate that a source configuration is compatible with the GitHub provider.
#[must_use = "the validation result must be checked"]
pub fn validate_source_configuration(source: &SourceConfiguration) -> MonochangeResult<()> {
	if source.releases.generate_notes
		&& matches!(
			source.releases.source,
			ProviderReleaseNotesSource::Monochange
		) {
		return Err(MonochangeError::Config(
			"[source.releases].generate_notes cannot be true when `source = \"monochange\"`; choose one release-note source"
				.to_string(),
		));
	}

	Ok(())
}

/// Shared issue-comment planning type for GitHub issue release comments.
pub type GitHubIssueCommentPlan = HostedIssueCommentPlan;
/// Shared issue-comment operation type for GitHub issue release comments.
pub type GitHubIssueCommentOperation = HostedIssueCommentOperation;
/// Shared issue-comment outcome type for GitHub issue release comments.
pub type GitHubIssueCommentOutcome = HostedIssueCommentOutcome;

/// Shared GitHub hosted-source adapter instance used by the workspace.
pub static HOSTED_SOURCE_ADAPTER: GitHubHostedSourceAdapter = GitHubHostedSourceAdapter;

/// Hosted-source adapter for GitHub repositories.
pub struct GitHubHostedSourceAdapter;

impl HostedSourceAdapter for GitHubHostedSourceAdapter {
	fn provider(&self) -> SourceProvider {
		SourceProvider::GitHub
	}

	fn features(&self) -> HostedSourceFeatures {
		HostedSourceFeatures {
			batched_changeset_context_lookup: true,
			released_issue_comments: true,
			release_retarget_sync: true,
		}
	}

	fn annotate_changeset_context(
		&self,
		source: &SourceConfiguration,
		changesets: &mut [PreparedChangeset],
	) {
		annotate_changeset_context(source, changesets);
	}

	fn enrich_changeset_context(
		&self,
		source: &SourceConfiguration,
		changesets: &mut [PreparedChangeset],
	) {
		enrich_changeset_context(source, changesets);
	}

	fn plan_released_issue_comments(
		&self,
		source: &SourceConfiguration,
		manifest: &ReleaseManifest,
	) -> Vec<HostedIssueCommentPlan> {
		plan_released_issue_comments(source, manifest)
	}

	fn comment_released_issues(
		&self,
		source: &SourceConfiguration,
		manifest: &ReleaseManifest,
	) -> MonochangeResult<Vec<HostedIssueCommentOutcome>> {
		comment_released_issues(source, manifest)
	}

	fn sync_retargeted_releases(
		&self,
		source: &SourceConfiguration,
		tag_results: &[RetargetTagResult],
		dry_run: bool,
	) -> MonochangeResult<Vec<RetargetProviderResult>> {
		sync_retargeted_releases(source, tag_results, dry_run)
	}
}

#[derive(Debug, Clone, Eq, PartialEq)]
struct GitHubRelatedReviewRequest {
	review_request: HostedReviewRequestRef,
	issues: Vec<HostedIssueRef>,
}

#[derive(Debug, Serialize)]
struct GitHubReleasePayload<'a> {
	tag_name: &'a str,
	name: &'a str,
	body: Option<&'a str>,
	draft: bool,
	prerelease: bool,
	generate_release_notes: bool,
}

#[derive(Debug, Serialize)]
struct GitHubPullRequestPayload<'a> {
	title: &'a str,
	head: &'a str,
	base: &'a str,
	body: &'a str,
	draft: bool,
}

#[derive(Debug, Serialize)]
struct GitHubPullRequestUpdatePayload<'a> {
	title: &'a str,
	body: &'a str,
	base: &'a str,
}

#[derive(Debug, Serialize)]
struct GitHubLabelsPayload<'a> {
	labels: &'a [String],
}

#[derive(Debug, Deserialize)]
struct GitHubExistingPullRequestLabel {
	name: String,
}

#[derive(Debug, Deserialize)]
struct GitHubExistingPullRequestBase {
	#[serde(rename = "ref")]
	ref_name: String,
}

#[derive(Debug, Deserialize)]
struct GitHubExistingPullRequestHead {
	sha: Option<String>,
}

#[derive(Debug, Deserialize)]
struct GitHubExistingPullRequest {
	number: u64,
	html_url: Option<String>,
	node_id: String,
	title: String,
	body: Option<String>,
	base: GitHubExistingPullRequestBase,
	head: GitHubExistingPullRequestHead,
	#[serde(default)]
	labels: Vec<GitHubExistingPullRequestLabel>,
}

#[derive(Debug, Deserialize)]
struct GitHubExistingRelease {
	id: u64,
	html_url: Option<String>,
	target_commitish: Option<String>,
}

#[derive(Debug, Deserialize)]
struct GitHubReleaseResponse {
	html_url: Option<String>,
}

#[derive(Debug, Serialize)]
struct GitHubReleaseRetargetPayload<'a> {
	target_commitish: &'a str,
}

#[derive(Debug, Deserialize)]
struct GitHubPullRequestResponse {
	number: u64,
	html_url: Option<String>,
	node_id: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GraphqlEnableAutoMergeResponse {
	enable_pull_request_auto_merge: Option<GraphqlPullRequestMutation>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GraphqlPullRequestMutation {
	pull_request: Option<GraphqlPullRequestNode>,
}

#[derive(Debug, Deserialize)]
struct GraphqlPullRequestNode {
	#[serde(rename = "number")]
	_number: u64,
}

#[derive(Debug, Deserialize)]
struct GitHubIssueCommentResponse {
	html_url: Option<String>,
	body: Option<String>,
}

/// Return the hosting metadata features available from GitHub changeset context.
#[must_use]
pub fn github_hosting_capabilities() -> HostingCapabilities {
	HostingCapabilities {
		commit_web_urls: true,
		actor_profiles: true,
		review_request_lookup: true,
		related_issues: true,
		issue_comments: true,
	}
}

/// Return the GitHub web base URL for building browser links.
#[must_use]
pub fn github_web_base_url() -> String {
	env::var("GITHUB_SERVER_URL").unwrap_or_else(|_| "https://github.com".to_string())
}

/// Extract the host name used for rendered GitHub links.
#[must_use]
pub fn github_host() -> Option<String> {
	let base_url = github_web_base_url();
	let without_scheme = base_url
		.trim_start_matches("https://")
		.trim_start_matches("http://");
	let host = without_scheme.split('/').next().unwrap_or_default().trim();
	if host.is_empty() {
		None
	} else {
		Some(host.to_string())
	}
}

/// Build a web URL for a commit on the configured GitHub repository.
#[must_use]
pub fn github_commit_url(source: &SourceConfiguration, sha: &str) -> String {
	format!(
		"{}/{}/{}/commit/{}",
		github_web_base_url().trim_end_matches('/'),
		source.owner,
		source.repo,
		sha
	)
}

/// Build a web URL for a pull request on the configured GitHub repository.
#[must_use]
pub fn github_pull_request_url(source: &SourceConfiguration, number: u64) -> String {
	format!(
		"{}/{}/{}/pull/{}",
		github_web_base_url().trim_end_matches('/'),
		source.owner,
		source.repo,
		number
	)
}

/// Build a web URL for an issue on the configured GitHub repository.
#[must_use]
pub fn github_issue_url(source: &SourceConfiguration, number: u64) -> String {
	format!(
		"{}/{}/{}/issues/{}",
		github_web_base_url().trim_end_matches('/'),
		source.owner,
		source.repo,
		number
	)
}

/// URL to a specific tag on the GitHub repository.
#[must_use]
pub fn tag_url(source: &SourceConfiguration, tag_name: &str) -> String {
	let base = github_web_base_url();
	let base = source.host.as_deref().unwrap_or(base.trim_end_matches('/'));
	format!(
		"{}/{}/{}/releases/tag/{tag_name}",
		base.trim_end_matches('/'),
		source.owner,
		source.repo
	)
}

/// URL comparing two tags on the GitHub repository.
#[must_use]
pub fn compare_url(source: &SourceConfiguration, previous_tag: &str, current_tag: &str) -> String {
	let base = github_web_base_url();
	let base = source.host.as_deref().unwrap_or(base.trim_end_matches('/'));
	format!(
		"{}/{}/{}/compare/{previous_tag}...{current_tag}",
		base.trim_end_matches('/'),
		source.owner,
		source.repo
	)
}

fn apply_github_changeset_annotations(
	source: &SourceConfiguration,
	changesets: &mut [PreparedChangeset],
) {
	let host = github_host();
	let capabilities = github_hosting_capabilities();
	for changeset in changesets.iter_mut() {
		let Some(context) = changeset.context.as_mut() else {
			continue;
		};
		context.provider = HostingProviderKind::GitHub;
		context.host.clone_from(&host);
		context.capabilities = capabilities.clone();
		for revision in [&mut context.introduced, &mut context.last_updated] {
			let Some(revision) = revision.as_mut() else {
				continue;
			};
			if let Some(commit) = revision.commit.as_mut() {
				commit.provider = HostingProviderKind::GitHub;
				commit.host.clone_from(&host);
				commit.url = Some(github_commit_url(source, &commit.sha));
			}
			if let Some(actor) = revision.actor.as_mut() {
				actor.provider = HostingProviderKind::GitHub;
				actor.host.clone_from(&host);
			}
		}
	}
}

/// Apply GitHub URLs and provider metadata without making remote API calls.
///
/// Performance note:
/// `mc release --dry-run` should stay local and fast. The old path always went
/// on to look up PRs and related issues for every changeset commit whenever a
/// GitHub token was present, which turned a local preview into tens of seconds
/// of serialized network traffic. The dry-run release path now uses this helper
/// so the changelog context still gets stable GitHub commit links while the
/// expensive hosted lookups remain reserved for commands that truly need them.
pub fn annotate_changeset_context(
	source: &SourceConfiguration,
	changesets: &mut [PreparedChangeset],
) {
	apply_github_changeset_annotations(source, changesets);
}

/// Enrich changeset context with remote GitHub review-request and issue data.
#[tracing::instrument(skip_all)]
pub fn enrich_changeset_context(
	source: &SourceConfiguration,
	changesets: &mut [PreparedChangeset],
) {
	apply_github_changeset_annotations(source, changesets);

	let Ok(token) = env::var("GITHUB_TOKEN").or_else(|_| env::var("GH_TOKEN")) else {
		tracing::debug!("skipping GitHub enrichment: no GITHUB_TOKEN or GH_TOKEN found");
		return;
	};
	let Ok(runtime) = github_runtime() else {
		return;
	};
	let api_base_url = env::var("GITHUB_API_URL").ok();
	runtime.block_on(async {
		let Ok(client) = build_github_client(&token, api_base_url.as_deref()) else {
			return;
		};
		enrich_changeset_context_with_client(&client, source, changesets).await;
	});
}

/// Convert releasable targets into provider-specific GitHub release requests.
#[must_use]
pub fn build_release_requests(
	source: &SourceConfiguration,
	manifest: &ReleaseManifest,
) -> Vec<GitHubReleaseRequest> {
	manifest
		.release_targets
		.iter()
		.filter(|target| target.release)
		.map(|target| {
			GitHubReleaseRequest {
				provider: SourceProvider::GitHub,
				repository: format!("{}/{}", source.owner, source.repo),
				owner: source.owner.clone(),
				repo: source.repo.clone(),
				target_id: target.id.clone(),
				target_kind: target.kind,
				tag_name: target.tag_name.clone(),
				name: target.rendered_title.clone(),
				body: release_body(source, manifest, target),
				draft: source.releases.draft,
				prerelease: source.releases.prerelease,
				generate_release_notes: source.releases.generate_notes,
			}
		})
		.collect()
}

/// Build the release pull request request for the configured GitHub repository.
#[must_use]
pub fn build_release_pull_request_request(
	source: &SourceConfiguration,
	manifest: &ReleaseManifest,
) -> GitHubPullRequestRequest {
	let repository = format!("{}/{}", source.owner, source.repo);
	let title = source.pull_requests.title.clone();
	GitHubPullRequestRequest {
		provider: SourceProvider::GitHub,
		repository: repository.clone(),
		owner: source.owner.clone(),
		repo: source.repo.clone(),
		base_branch: source.pull_requests.base.clone(),
		head_branch: release_pull_request_branch(
			&source.pull_requests.branch_prefix,
			&manifest.command,
		),
		title: title.clone(),
		body: release_pull_request_body(manifest),
		labels: source.pull_requests.labels.clone(),
		auto_merge: source.pull_requests.auto_merge,
		commit_message: CommitMessage {
			subject: title,
			body: None,
		},
	}
}

async fn enrich_changeset_context_with_client(
	client: &Octocrab,
	source: &SourceConfiguration,
	changesets: &mut [PreparedChangeset],
) {
	let host = github_host();
	let capabilities = github_hosting_capabilities();
	for changeset in changesets.iter_mut() {
		let Some(context) = changeset.context.as_mut() else {
			continue;
		};
		context.provider = HostingProviderKind::GitHub;
		context.host.clone_from(&host);
		context.capabilities = capabilities.clone();
		for revision in [&mut context.introduced, &mut context.last_updated] {
			let Some(revision) = revision.as_mut() else {
				continue;
			};
			if let Some(commit) = revision.commit.as_mut() {
				commit.provider = HostingProviderKind::GitHub;
				commit.host.clone_from(&host);
				commit.url = Some(github_commit_url(source, &commit.sha));
			}
			if let Some(actor) = revision.actor.as_mut() {
				actor.provider = HostingProviderKind::GitHub;
				actor.host.clone_from(&host);
			}
		}
	}
	let review_request_lookup_shas = collect_review_request_lookup_shas(changesets);
	let review_requests_by_sha =
		load_review_requests_for_commits_with_client(client, source, &review_request_lookup_shas)
			.await
			.unwrap_or_else(|error| {
				#[rustfmt::skip]
				tracing::warn!(commits = review_request_lookup_shas.len(), %error, "failed to batch load GitHub review requests; continuing with commit annotations only");
				std::collections::BTreeMap::new()
			});

	for changeset in changesets.iter_mut() {
		let Some(context) = changeset.context.as_mut() else {
			continue;
		};

		let mut issues_by_id = std::collections::BTreeMap::<String, HostedIssueRef>::new();

		for revision in [&mut context.introduced, &mut context.last_updated] {
			let Some(revision) = revision.as_mut() else {
				continue;
			};

			let Some(commit) = revision.commit.as_ref() else {
				continue;
			};

			if let Some(related_review_request) = review_requests_by_sha
				.get(&commit.sha)
				.and_then(Clone::clone)
			{
				for issue in related_review_request.issues {
					issues_by_id.entry(issue.id.clone()).or_insert(issue);
				}
				revision.review_request = Some(related_review_request.review_request.clone());
				if let Some(author) = related_review_request.review_request.author.clone() {
					revision.actor = Some(author);
				}
			}

			if let Some(actor) = revision.actor.as_mut() {
				actor.provider = HostingProviderKind::GitHub;
				actor.host.clone_from(&host);
			}
		}

		context.related_issues = issues_by_id.into_values().collect();
	}
}

fn collect_review_request_lookup_shas(changesets: &[PreparedChangeset]) -> Vec<String> {
	let mut shas = changesets
		.iter()
		.filter_map(|changeset| changeset.context.as_ref())
		.flat_map(|context| [&context.introduced, &context.last_updated])
		.filter_map(|revision| revision.as_ref())
		.filter_map(|revision| revision.commit.as_ref())
		.map(|commit| commit.sha.clone())
		.collect::<Vec<_>>();

	shas.sort();
	shas.dedup();

	shas
}

async fn load_review_requests_for_commits_with_client(
	client: &Octocrab,
	source: &SourceConfiguration,
	shas: &[String],
) -> MonochangeResult<std::collections::BTreeMap<String, Option<GitHubRelatedReviewRequest>>> {
	if shas.is_empty() {
		return Ok(std::collections::BTreeMap::new());
	}

	#[rustfmt::skip]
	tracing::info!(commits = shas.len(), requests = 1, "loading GitHub review requests");

	let review_requests_by_sha =
		load_review_request_batch_with_client(client, source, shas).await?;

	let review_requests_found = review_requests_by_sha
		.values()
		.filter(|review_request| review_request.is_some())
		.count();

	#[rustfmt::skip]
	tracing::debug!(commits = shas.len(), review_requests = review_requests_found, "resolved GitHub review requests");

	Ok(review_requests_by_sha)
}

async fn load_review_request_batch_with_client(
	client: &Octocrab,
	source: &SourceConfiguration,
	shas: &[String],
) -> MonochangeResult<std::collections::BTreeMap<String, Option<GitHubRelatedReviewRequest>>> {
	let query = build_review_request_batch_query(&source.owner, &source.repo, shas);

	let response = client
		.graphql::<serde_json::Value>(&json!({ "query": query }))
		.await
		.map_err(|error| {
			MonochangeError::Config(format!(
				"failed to batch load GitHub review requests for {} commit(s): {error}",
				shas.len()
			))
		})?;

	let repository = response
		.get("repository")
		.or_else(|| response.get("data").and_then(|data| data.get("repository")))
		.and_then(serde_json::Value::as_object)
		.ok_or_else(|| {
			MonochangeError::Config(
				"GitHub review-request lookup returned no repository payload".to_string(),
			)
		})?;

	let mut review_requests_by_sha =
		std::collections::BTreeMap::<String, Option<GitHubRelatedReviewRequest>>::new();

	for (index, sha) in shas.iter().enumerate() {
		let alias = format!("commit_{index}");
		let review_request = repository
			.get(&alias)
			.and_then(|commit| {
				commit
					.get("associatedPullRequests")
					.and_then(|pull_requests| pull_requests.get("nodes"))
					.and_then(serde_json::Value::as_array)
					.and_then(|pull_requests| pull_requests.first())
			})
			.and_then(|pull_request| parse_review_request_from_graphql(source, pull_request));
		review_requests_by_sha.insert(sha.clone(), review_request);
	}

	Ok(review_requests_by_sha)
}

fn build_review_request_batch_query(owner: &str, repo: &str, shas: &[String]) -> String {
	let mut query = format!("query {{ repository(owner: \"{owner}\", name: \"{repo}\") {{");
	for (index, sha) in shas.iter().enumerate() {
		let alias = format!("commit_{index}");
		let _ = write!(
			query,
			" {alias}: object(expression: \"{sha}\") {{ ... on Commit {{ associatedPullRequests(first: 1) {{ nodes {{ number title url body author {{ login url }} }} }} }} }}"
		);
	}
	query.push_str(" } }");
	query
}

fn parse_review_request_from_graphql(
	source: &SourceConfiguration,
	pull_request: &serde_json::Value,
) -> Option<GitHubRelatedReviewRequest> {
	let number = pull_request.get("number")?.as_u64()?;
	let title = pull_request
		.get("title")
		.and_then(serde_json::Value::as_str)?
		.to_string();
	let body = pull_request
		.get("body")
		.and_then(serde_json::Value::as_str)
		.map(str::to_string);
	let author = pull_request
		.get("author")
		.and_then(serde_json::Value::as_object)
		.map(|author| {
			HostedActorRef {
				provider: HostingProviderKind::GitHub,
				host: github_host(),
				id: None,
				login: author
					.get("login")
					.and_then(serde_json::Value::as_str)
					.map(str::to_string),
				display_name: author
					.get("login")
					.and_then(serde_json::Value::as_str)
					.map(str::to_string),
				url: author
					.get("url")
					.and_then(serde_json::Value::as_str)
					.map(str::to_string),
				source: HostedActorSourceKind::ReviewRequestAuthor,
			}
		});
	let review_request = HostedReviewRequestRef {
		provider: HostingProviderKind::GitHub,
		host: github_host(),
		kind: HostedReviewRequestKind::PullRequest,
		id: format!("#{number}"),
		title: Some(title),
		url: pull_request
			.get("url")
			.and_then(serde_json::Value::as_str)
			.map(str::to_string)
			.or_else(|| Some(github_pull_request_url(source, number))),
		author,
	};
	let mut issues_by_id = std::collections::BTreeMap::<String, HostedIssueRef>::new();
	for issue_number in body
		.as_deref()
		.map(extract_closing_issue_numbers)
		.unwrap_or_default()
	{
		issues_by_id.insert(
			format!("#{issue_number}"),
			HostedIssueRef {
				provider: HostingProviderKind::GitHub,
				host: github_host(),
				id: format!("#{issue_number}"),
				title: None,
				url: Some(github_issue_url(source, issue_number)),
				relationship: HostedIssueRelationshipKind::ClosedByReviewRequest,
			},
		);
	}
	for issue_number in body
		.as_deref()
		.map(extract_issue_numbers)
		.unwrap_or_default()
	{
		issues_by_id
			.entry(format!("#{issue_number}"))
			.or_insert_with(|| {
				HostedIssueRef {
					provider: HostingProviderKind::GitHub,
					host: github_host(),
					id: format!("#{issue_number}"),
					title: None,
					url: Some(github_issue_url(source, issue_number)),
					relationship: HostedIssueRelationshipKind::ReferencedByReviewRequest,
				}
			});
	}
	Some(GitHubRelatedReviewRequest {
		review_request,
		issues: issues_by_id.into_values().collect(),
	})
}

fn issue_reference_regex() -> &'static Regex {
	static ISSUE_REFERENCE_RE: OnceLock<Regex> = OnceLock::new();
	ISSUE_REFERENCE_RE.get_or_init(|| {
		Regex::new(r"(?:[\w.-]+/[\w.-]+)?#(?P<number>\d+)")
			.unwrap_or_else(|error| panic!("issue reference regex should compile: {error}"))
	})
}

fn closing_issue_reference_regex() -> &'static Regex {
	static CLOSING_ISSUE_REFERENCE_RE: OnceLock<Regex> = OnceLock::new();
	CLOSING_ISSUE_REFERENCE_RE.get_or_init(|| {
		Regex::new(r"(?i)\b(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)\b[:\s]*(?P<refs>(?:[\w.-]+/[\w.-]+)?#\d+(?:\s*(?:,|and)\s*(?:[\w.-]+/[\w.-]+)?#\d+)*)")
		.unwrap_or_else(|error| panic!("closing issue regex should compile: {error}"))
	})
}

fn extract_closing_issue_numbers(text: &str) -> std::collections::BTreeSet<u64> {
	let mut issue_numbers = std::collections::BTreeSet::new();
	for captures in closing_issue_reference_regex().captures_iter(text) {
		let Some(references) = captures.name("refs") else {
			continue;
		};
		issue_numbers.extend(extract_issue_numbers(references.as_str()));
	}
	issue_numbers
}

fn extract_issue_numbers(text: &str) -> std::collections::BTreeSet<u64> {
	issue_reference_regex()
		.captures_iter(text)
		.filter_map(|captures| captures.name("number"))
		.filter_map(|number| number.as_str().parse::<u64>().ok())
		.collect()
}

/// Plan release comments for issues that are closed by the manifest's review requests.
#[must_use]
pub fn plan_released_issue_comments(
	source: &SourceConfiguration,
	manifest: &ReleaseManifest,
) -> Vec<GitHubIssueCommentPlan> {
	let release_tags = manifest
		.release_targets
		.iter()
		.filter(|target| target.release)
		.map(|target| target.tag_name.clone())
		.collect::<Vec<_>>();
	if release_tags.is_empty() {
		return Vec::new();
	}
	let marker = release_comment_marker(&release_tags);
	let body = release_issue_comment_body(&release_tags, &marker);
	let mut plans_by_issue = std::collections::BTreeMap::<String, GitHubIssueCommentPlan>::new();
	for issue in manifest
		.changesets
		.iter()
		.filter_map(|changeset| changeset.context.as_ref())
		.flat_map(|context| context.related_issues.iter())
		.filter(|issue| issue.relationship == HostedIssueRelationshipKind::ClosedByReviewRequest)
	{
		plans_by_issue.entry(issue.id.clone()).or_insert_with(|| {
			GitHubIssueCommentPlan {
				repository: format!("{}/{}", source.owner, source.repo),
				issue_id: issue.id.clone(),
				issue_url: issue.url.clone(),
				body: body.clone(),
			}
		});
	}
	plans_by_issue.into_values().collect()
}

/// Create release comments on linked GitHub issues when they have not been posted yet.
#[tracing::instrument(skip_all)]
#[must_use = "the comment result must be checked"]
pub fn comment_released_issues(
	source: &SourceConfiguration,
	manifest: &ReleaseManifest,
) -> MonochangeResult<Vec<GitHubIssueCommentOutcome>> {
	let plans = plan_released_issue_comments(source, manifest);
	if plans.is_empty() {
		return Ok(Vec::new());
	}
	let runtime = github_runtime()?;
	runtime.block_on(async {
		let client = github_client_from_env(source)?;

		comment_released_issues_with_client(&client, source, &plans).await
	})
}

async fn comment_released_issues_with_client(
	client: &Octocrab,
	source: &SourceConfiguration,
	plans: &[GitHubIssueCommentPlan],
) -> MonochangeResult<Vec<GitHubIssueCommentOutcome>> {
	let mut outcomes = Vec::with_capacity(plans.len());
	for plan in plans {
		let issue_number = plan
			.issue_id
			.trim_start_matches('#')
			.parse::<u64>()
			.map_err(|error| {
				MonochangeError::Config(format!(
					"invalid issue id `{}` for release comment: {error}",
					plan.issue_id
				))
			})?;
		let path = format!(
			"/repos/{}/{}/issues/{}/comments",
			source.owner, source.repo, issue_number
		);
		let existing_comments = get_json::<Vec<GitHubIssueCommentResponse>>(client, &path).await?;
		if existing_comments.iter().any(|comment| {
			comment
				.body
				.as_deref()
				.is_some_and(|body| body.contains(&plan.body))
		}) {
			outcomes.push(GitHubIssueCommentOutcome {
				repository: plan.repository.clone(),
				issue_id: plan.issue_id.clone(),
				operation: GitHubIssueCommentOperation::SkippedExisting,
				url: plan.issue_url.clone(),
			});
			continue;
		}
		let response = post_json::<_, GitHubIssueCommentResponse>(
			client,
			&path,
			&json!({ "body": plan.body }),
		)
		.await?;
		outcomes.push(GitHubIssueCommentOutcome {
			repository: plan.repository.clone(),
			issue_id: plan.issue_id.clone(),
			operation: GitHubIssueCommentOperation::Created,
			url: response.html_url.or_else(|| plan.issue_url.clone()),
		});
	}
	Ok(outcomes)
}

fn release_comment_marker(release_tags: &[String]) -> String {
	format!("<!-- monochange:released-in:{} -->", release_tags.join("|"))
}

fn release_issue_comment_body(release_tags: &[String], marker: &str) -> String {
	if let Some(release_tag) = release_tags.first().filter(|_| release_tags.len() == 1) {
		format!("Released in {release_tag}.\n\n{marker}")
	} else {
		format!("Released in {}.\n\n{marker}", release_tags.join(", "))
	}
}

/// Publish or update all planned GitHub releases for a manifest.
#[tracing::instrument(skip_all)]
#[must_use = "the publish result must be checked"]
pub fn publish_release_requests(
	source: &SourceConfiguration,
	requests: &[GitHubReleaseRequest],
) -> MonochangeResult<Vec<GitHubReleaseOutcome>> {
	let runtime = github_runtime()?;
	runtime.block_on(async {
		let client = github_client_from_env(source)?;

		publish_release_requests_with_client(&client, requests).await
	})
}

/// Commit, push, and publish the release pull request against GitHub.
#[tracing::instrument(skip_all)]
#[must_use = "the pull request result must be checked"]
pub fn publish_release_pull_request(
	source: &SourceConfiguration,
	root: &Path,
	request: &GitHubPullRequestRequest,
	tracked_paths: &[PathBuf],
) -> MonochangeResult<GitHubPullRequestOutcome> {
	let lookup_source = source.clone();
	let lookup_request = request.clone();
	let existing_pull_request =
		thread::spawn(move || lookup_existing_pull_request(&lookup_source, &lookup_request));
	git_checkout_branch(root, &request.head_branch)?;
	git_stage_paths(root, tracked_paths)?;
	git_commit_paths(root, &request.commit_message)?;
	let head_commit = git_head_commit(root)?;
	let existing = join_existing_pull_request_lookup(existing_pull_request)?;
	let head_matches_existing = existing
		.as_ref()
		.and_then(|pull_request| pull_request.head.sha.as_deref())
		== Some(head_commit.as_str());
	if !head_matches_existing {
		git_push_branch(root, &request.head_branch)?;
	}

	let runtime = github_runtime()?;
	runtime.block_on(async {
		let client = github_client_from_env(source)?;

		publish_release_pull_request_with_existing_pull_request(
			&client,
			request,
			existing.as_ref(),
			&head_commit,
		)
		.await
	})
}

/// Sync existing GitHub releases so retargeted tags point at the new commits.
#[tracing::instrument(skip_all)]
#[must_use = "the sync result must be checked"]
pub fn sync_retargeted_releases(
	source: &SourceConfiguration,
	tag_updates: &[RetargetTagResult],
	dry_run: bool,
) -> MonochangeResult<Vec<RetargetProviderResult>> {
	let runtime = github_runtime()?;
	runtime.block_on(async {
		let client = github_client_from_env(source)?;
		let outcomes =
			sync_retargeted_releases_with_client(&client, source, tag_updates, dry_run).await?;
		Ok(outcomes)
	})
}

async fn publish_release_requests_with_client(
	client: &Octocrab,
	requests: &[GitHubReleaseRequest],
) -> MonochangeResult<Vec<GitHubReleaseOutcome>> {
	let mut outcomes = Vec::with_capacity(requests.len());
	for request in requests {
		outcomes.push(publish_release_request_with_client(client, request).await?);
	}
	Ok(outcomes)
}

async fn publish_release_request_with_client(
	client: &Octocrab,
	request: &GitHubReleaseRequest,
) -> MonochangeResult<GitHubReleaseOutcome> {
	tracing::info!(tag = %request.tag_name, repository = %request.repository, "publishing GitHub release");
	let payload = GitHubReleasePayload {
		tag_name: &request.tag_name,
		name: &request.name,
		body: request.body.as_deref(),
		draft: request.draft,
		prerelease: request.prerelease,
		generate_release_notes: request.generate_release_notes,
	};
	let existing = lookup_existing_release_with_client(client, request).await?;
	let (operation, response) = match existing {
		Some(existing) => {
			(
				GitHubReleaseOperation::Updated,
				patch_json::<_, GitHubReleaseResponse>(
					client,
					&format!(
						"/repos/{}/{}/releases/{}",
						request.owner, request.repo, existing.id
					),
					&payload,
				)
				.await?,
			)
		}
		None => {
			(
				GitHubReleaseOperation::Created,
				post_json::<_, GitHubReleaseResponse>(
					client,
					&format!("/repos/{}/{}/releases", request.owner, request.repo),
					&payload,
				)
				.await?,
			)
		}
	};
	Ok(GitHubReleaseOutcome {
		provider: SourceProvider::GitHub,
		repository: request.repository.clone(),
		tag_name: request.tag_name.clone(),
		operation,
		url: response.html_url,
	})
}

#[cfg_attr(not(test), allow(dead_code))]
async fn publish_release_pull_request_with_client(
	client: &Octocrab,
	request: &GitHubPullRequestRequest,
) -> MonochangeResult<GitHubPullRequestOutcome> {
	let existing = lookup_existing_pull_request_with_client(client, request).await?;
	publish_release_pull_request_with_existing_pull_request(client, request, existing.as_ref(), "")
		.await
}

async fn publish_release_pull_request_with_existing_pull_request(
	client: &Octocrab,
	request: &GitHubPullRequestRequest,
	existing: Option<&GitHubExistingPullRequest>,
	head_commit: &str,
) -> MonochangeResult<GitHubPullRequestOutcome> {
	let labels_match = existing.is_some_and(|pull_request| {
		request.labels.iter().all(|label| {
			pull_request
				.labels
				.iter()
				.any(|existing_label| existing_label.name == *label)
		})
	});
	let content_matches = existing.is_some_and(|pull_request| {
		pull_request.title == request.title
			&& pull_request.body.as_deref().unwrap_or_default() == request.body
			&& pull_request.base.ref_name == request.base_branch
	});
	let head_matches_existing =
		existing.and_then(|pull_request| pull_request.head.sha.as_deref()) == Some(head_commit);
	let (operation, pull_request) = match existing {
		Some(existing_pull_request) if content_matches => {
			(
				if head_matches_existing && labels_match && !request.auto_merge {
					GitHubPullRequestOperation::Skipped
				} else {
					GitHubPullRequestOperation::Updated
				},
				GitHubPullRequestResponse {
					number: existing_pull_request.number,
					html_url: existing_pull_request.html_url.clone(),
					node_id: existing_pull_request.node_id.clone(),
				},
			)
		}
		Some(existing_pull_request) => {
			(
				GitHubPullRequestOperation::Updated,
				patch_json::<_, GitHubPullRequestResponse>(
					client,
					&format!(
						"/repos/{}/{}/pulls/{}",
						request.owner, request.repo, existing_pull_request.number
					),
					&GitHubPullRequestUpdatePayload {
						title: &request.title,
						body: &request.body,
						base: &request.base_branch,
					},
				)
				.await?,
			)
		}
		None => {
			(
				GitHubPullRequestOperation::Created,
				post_json::<_, GitHubPullRequestResponse>(
					client,
					&format!("/repos/{}/{}/pulls", request.owner, request.repo),
					&GitHubPullRequestPayload {
						title: &request.title,
						head: &request.head_branch,
						base: &request.base_branch,
						body: &request.body,
						draft: false,
					},
				)
				.await?,
			)
		}
	};
	if !request.labels.is_empty() && !labels_match {
		let _: serde_json::Value = post_json(
			client,
			&format!(
				"/repos/{}/{}/issues/{}/labels",
				request.owner, request.repo, pull_request.number
			),
			&GitHubLabelsPayload {
				labels: &request.labels,
			},
		)
		.await?;
	}
	if request.auto_merge {
		enable_pull_request_auto_merge_with_client(client, &pull_request.node_id).await?;
	}
	Ok(GitHubPullRequestOutcome {
		provider: SourceProvider::GitHub,
		repository: request.repository.clone(),
		number: pull_request.number,
		head_branch: request.head_branch.clone(),
		operation,
		url: pull_request.html_url,
	})
}

async fn sync_retargeted_releases_with_client(
	client: &Octocrab,
	source: &SourceConfiguration,
	tag_updates: &[RetargetTagResult],
	dry_run: bool,
) -> MonochangeResult<Vec<RetargetProviderResult>> {
	let mut results = Vec::with_capacity(tag_updates.len());
	for update in tag_updates {
		if dry_run {
			results.push(RetargetProviderResult {
				provider: SourceProvider::GitHub,
				tag_name: update.tag_name.clone(),
				target_commit: update.to_commit.clone(),
				operation: RetargetProviderOperation::Planned,
				url: None,
				message: None,
			});
			continue;
		}
		let path = format!(
			"/repos/{}/{}/releases/tags/{}",
			source.owner, source.repo, update.tag_name
		);
		let Some(existing) = get_optional_json::<GitHubExistingRelease>(client, &path).await?
		else {
			return Err(MonochangeError::Config(format!(
				"GitHub release for tag `{}` could not be found",
				update.tag_name
			)));
		};
		if existing.target_commitish.as_deref() == Some(update.to_commit.as_str())
			|| update.operation == RetargetOperation::AlreadyUpToDate
		{
			results.push(RetargetProviderResult {
				provider: SourceProvider::GitHub,
				tag_name: update.tag_name.clone(),
				target_commit: update.to_commit.clone(),
				operation: RetargetProviderOperation::AlreadyAligned,
				url: existing.html_url,
				message: None,
			});
			continue;
		}
		let response = patch_json::<_, GitHubReleaseResponse>(
			client,
			&format!(
				"/repos/{}/{}/releases/{}",
				source.owner, source.repo, existing.id
			),
			&GitHubReleaseRetargetPayload {
				target_commitish: &update.to_commit,
			},
		)
		.await?;
		results.push(RetargetProviderResult {
			provider: SourceProvider::GitHub,
			tag_name: update.tag_name.clone(),
			target_commit: update.to_commit.clone(),
			operation: RetargetProviderOperation::Synced,
			url: response.html_url,
			message: None,
		});
	}
	Ok(results)
}

async fn lookup_existing_release_with_client(
	client: &Octocrab,
	request: &GitHubReleaseRequest,
) -> MonochangeResult<Option<GitHubExistingRelease>> {
	get_optional_json(
		client,
		&format!(
			"/repos/{}/{}/releases/tags/{}",
			request.owner,
			request.repo,
			encode(&request.tag_name)
		),
	)
	.await
}

async fn lookup_existing_pull_request_with_client(
	client: &Octocrab,
	request: &GitHubPullRequestRequest,
) -> MonochangeResult<Option<GitHubExistingPullRequest>> {
	let path = format!(
		"/repos/{}/{}/pulls?state=open&head={}:{}&base={}&per_page=1",
		request.owner,
		request.repo,
		encode(&request.owner),
		encode(&request.head_branch),
		encode(&request.base_branch)
	);
	let pull_requests = get_json::<Vec<GitHubExistingPullRequest>>(client, &path).await?;
	Ok(pull_requests.into_iter().next())
}

fn lookup_existing_pull_request(
	source: &SourceConfiguration,
	request: &GitHubPullRequestRequest,
) -> MonochangeResult<Option<GitHubExistingPullRequest>> {
	let runtime = github_runtime()?;
	runtime.block_on(async {
		let client = github_client_from_env(source)?;
		lookup_existing_pull_request_with_client(&client, request).await
	})
}

async fn enable_pull_request_auto_merge_with_client(
	client: &Octocrab,
	node_id: &str,
) -> MonochangeResult<()> {
	let response = client
		.graphql::<GraphqlEnableAutoMergeResponse>(&json!({
			"query": "mutation($pullRequestId: ID!) { enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: SQUASH }) { pullRequest { number } } }",
			"variables": {
				"pullRequestId": node_id,
			},
		}))
		.await
		.map_err(|error| {
			MonochangeError::Config(format!(
				"failed to enable GitHub pull request auto merge: {error}"
			))
		})?;
	if response
		.enable_pull_request_auto_merge
		.and_then(|payload| payload.pull_request)
		.is_none()
	{
		return Err(MonochangeError::Config(
			"GitHub pull request auto merge returned no pull request payload".to_string(),
		));
	}
	Ok(())
}

fn github_runtime() -> MonochangeResult<tokio::runtime::Runtime> {
	RuntimeBuilder::new_current_thread()
		.enable_all()
		.build()
		.map_err(|error| MonochangeError::Io(format!("failed to build GitHub runtime: {error}")))
}

fn github_client_from_env(source: &SourceConfiguration) -> MonochangeResult<Octocrab> {
	let token = env::var("GITHUB_TOKEN")
		.or_else(|_| env::var("GH_TOKEN"))
		.map_err(|_| {
			MonochangeError::Config(
				"set `GITHUB_TOKEN` (or `GH_TOKEN`) before running GitHub automation".to_string(),
			)
		})?;
	let env_api_url = env::var("GITHUB_API_URL").ok();
	let api_url = source.api_url.as_deref().or(env_api_url.as_deref());
	build_github_client(&token, api_url)
}

fn build_github_client(token: &str, base_uri: Option<&str>) -> MonochangeResult<Octocrab> {
	let builder = Octocrab::builder().personal_token(token.to_string());
	let builder = if let Some(base_uri) = base_uri {
		builder.base_uri(base_uri).map_err(|error| {
			MonochangeError::Config(format!(
				"failed to configure GitHub base URL `{base_uri}`: {error}"
			))
		})?
	} else {
		builder
	};
	builder.build().map_err(|error| {
		MonochangeError::Config(format!("failed to build GitHub API client: {error}"))
	})
}

async fn get_optional_json<T>(client: &Octocrab, path: &str) -> MonochangeResult<Option<T>>
where
	T: DeserializeOwned,
{
	match client.get::<T, _, _>(path, None::<&()>).await {
		Ok(value) => Ok(Some(value)),
		Err(octocrab::Error::GitHub { source, .. }) if source.status_code.as_u16() == 404 => {
			Ok(None)
		}
		Err(error) => {
			Err(MonochangeError::Config(format!(
				"GitHub API GET `{path}` failed: {error}"
			)))
		}
	}
}

async fn get_json<T>(client: &Octocrab, path: &str) -> MonochangeResult<T>
where
	T: DeserializeOwned,
{
	match client.get::<T, _, _>(path, None::<&()>).await {
		Ok(value) => Ok(value),
		Err(error) => {
			Err(MonochangeError::Config(format!(
				"GitHub API GET `{path}` failed: {error}"
			)))
		}
	}
}

async fn post_json<Body, Response>(
	client: &Octocrab,
	path: &str,
	body: &Body,
) -> MonochangeResult<Response>
where
	Body: Serialize + ?Sized,
	Response: DeserializeOwned,
{
	client.post(path, Some(body)).await.map_err(|error| {
		MonochangeError::Config(format!("GitHub API POST `{path}` failed: {error}"))
	})
}

async fn patch_json<Body, Response>(
	client: &Octocrab,
	path: &str,
	body: &Body,
) -> MonochangeResult<Response>
where
	Body: Serialize + ?Sized,
	Response: DeserializeOwned,
{
	client.patch(path, Some(body)).await.map_err(|error| {
		MonochangeError::Config(format!("GitHub API PATCH `{path}` failed: {error}"))
	})
}

fn join_existing_pull_request_lookup(
	handle: thread::JoinHandle<MonochangeResult<Option<GitHubExistingPullRequest>>>,
) -> MonochangeResult<Option<GitHubExistingPullRequest>> {
	handle.join().map_err(|_| {
		MonochangeError::Config("failed to join GitHub pull request lookup thread".to_string())
	})?
}

fn git_checkout_branch(root: &Path, branch: &str) -> MonochangeResult<()> {
	if matches!(git_current_branch(root).as_deref(), Ok(current) if current == branch) {
		return Ok(());
	}
	run_command(
		git_checkout_branch_command(root, branch),
		"prepare release pull request branch",
	)
}

fn git_stage_paths(root: &Path, tracked_paths: &[PathBuf]) -> MonochangeResult<()> {
	let stageable_paths = resolve_stageable_release_paths(root, tracked_paths)?;
	if stageable_paths.is_empty() {
		return Ok(());
	}
	run_command(
		git_stage_paths_command(root, &stageable_paths),
		"stage release pull request files",
	)
}

fn resolve_stageable_release_paths(
	root: &Path,
	tracked_paths: &[PathBuf],
) -> MonochangeResult<Vec<PathBuf>> {
	let mut stageable_paths = Vec::with_capacity(tracked_paths.len());
	for path in tracked_paths {
		if release_path_requires_staging(root, path)? {
			stageable_paths.push(path.clone());
		}
	}
	Ok(stageable_paths)
}

fn release_path_requires_staging(root: &Path, path: &Path) -> MonochangeResult<bool> {
	let absolute_path = root.join(path);
	if absolute_path.exists() {
		if git_path_is_tracked(root, path)? {
			return Ok(true);
		}
		return Ok(!git_path_is_ignored(root, path)?);
	}
	git_path_is_tracked(root, path)
}

fn git_path_is_tracked(root: &Path, path: &Path) -> MonochangeResult<bool> {
	let relative = path.to_string_lossy();
	let output = git_command_output(root, &["ls-files", "--error-unmatch", "--", &relative])
		.map_err(|error| {
			MonochangeError::Config(format!(
				"failed to inspect tracked git path {}: {error}",
				path.display()
			))
		})?;
	match output.status.code() {
		Some(0) => Ok(true),
		Some(1) => Ok(false),
		_ => {
			Err(MonochangeError::Config(format!(
				"failed to inspect tracked git path {}: {}",
				path.display(),
				git_error_detail(&output)
			)))
		}
	}
}

fn git_path_is_ignored(root: &Path, path: &Path) -> MonochangeResult<bool> {
	let relative = path.to_string_lossy();
	let output =
		git_command_output(root, &["check-ignore", "-q", "--", &relative]).map_err(|error| {
			MonochangeError::Config(format!(
				"failed to inspect ignored git path {}: {error}",
				path.display()
			))
		})?;
	match output.status.code() {
		Some(0) => Ok(true),
		Some(1) => Ok(false),
		_ => {
			Err(MonochangeError::Config(format!(
				"failed to inspect ignored git path {}: {}",
				path.display(),
				git_error_detail(&output)
			)))
		}
	}
}

fn git_commit_paths(root: &Path, message: &CommitMessage) -> MonochangeResult<()> {
	run_commit_command_allow_nothing_to_commit(
		git_commit_paths_command(root, message),
		"commit release pull request changes",
	)
}

fn git_push_branch(root: &Path, branch: &str) -> MonochangeResult<()> {
	run_command(
		git_push_branch_command(root, branch),
		"push release pull request branch",
	)
}

fn release_body(
	github: &SourceConfiguration,
	manifest: &ReleaseManifest,
	target: &ReleaseManifestTarget,
) -> Option<String> {
	match github.releases.source {
		ProviderReleaseNotesSource::GitHubGenerated => None,
		ProviderReleaseNotesSource::Monochange => {
			manifest
				.changelogs
				.iter()
				.find(|changelog| {
					changelog.owner_id == target.id && changelog.owner_kind == target.kind
				})
				.map(|changelog| changelog.rendered.clone())
				.or_else(|| Some(minimal_release_body(manifest, target)))
		}
	}
}

fn release_pull_request_branch(branch_prefix: &str, command: &str) -> String {
	let command = command
		.chars()
		.map(|character| {
			if character.is_ascii_alphanumeric() {
				character.to_ascii_lowercase()
			} else {
				'-'
			}
		})
		.collect::<String>()
		.trim_matches('-')
		.to_string();
	let command = if command.is_empty() {
		"release".to_string()
	} else {
		command
	};
	format!("{}/{}", branch_prefix.trim_end_matches('/'), command)
}

fn release_pull_request_body(manifest: &ReleaseManifest) -> String {
	let mut lines = vec!["## Prepared release".to_string(), String::new()];
	lines.push(format!("- command: `{}`", manifest.command));
	for target in manifest
		.release_targets
		.iter()
		.filter(|target| target.release)
	{
		lines.push(format!(
			"- {} `{}` -> `{}`",
			target.kind, target.id, target.tag_name
		));
	}
	if !manifest.release_targets.iter().any(|target| target.release) {
		lines.push("- no outward release targets".to_string());
	}
	lines.push(String::new());
	lines.push("## Release notes".to_string());
	for target in manifest
		.release_targets
		.iter()
		.filter(|target| target.release)
	{
		lines.push(String::new());
		lines.push(format!("### {} {}", target.id, target.version));
		if let Some(changelog) = manifest.changelogs.iter().find(|changelog| {
			changelog.owner_id == target.id && changelog.owner_kind == target.kind
		}) {
			for paragraph in &changelog.notes.summary {
				lines.push(String::new());
				lines.push(paragraph.clone());
			}
			for section in &changelog.notes.sections {
				if section.entries.is_empty() {
					continue;
				}
				lines.push(String::new());
				lines.push(format!("#### {}", section.title));
				lines.push(String::new());
				push_body_entries(&mut lines, &section.entries);
			}
		} else {
			lines.push(String::new());
			lines.push(minimal_release_body(manifest, target));
		}
	}
	if !manifest.changed_files.is_empty() {
		lines.push(String::new());
		lines.push("## Changed files".to_string());
		lines.push(String::new());
		for path in &manifest.changed_files {
			lines.push(format!("- {}", path.display()));
		}
	}
	lines.join("\n")
}

fn push_body_entries(lines: &mut Vec<String>, entries: &[String]) {
	for (index, entry) in entries.iter().enumerate() {
		let trimmed = entry.trim();
		if trimmed.contains('\n') {
			lines.extend(trimmed.lines().map(ToString::to_string));
			if index + 1 < entries.len() {
				lines.push(String::new());
			}
			continue;
		}
		if trimmed.starts_with("- ") || trimmed.starts_with("* ") || trimmed.starts_with('#') {
			lines.push(trimmed.to_string());
		} else {
			lines.push(format!("- {trimmed}"));
		}
	}
}

fn minimal_release_body(manifest: &ReleaseManifest, target: &ReleaseManifestTarget) -> String {
	let mut lines = vec![format!("Release target `{}`", target.id), String::new()];
	if !target.members.is_empty() {
		lines.push(format!("Members: {}", target.members.join(", ")));
		lines.push(String::new());
	}
	let reasons = manifest
		.plan
		.decisions
		.iter()
		.filter(|decision| {
			target.kind == ReleaseOwnerKind::Package || target.members.contains(&decision.package)
		})
		.flat_map(|decision| decision.reasons.iter().cloned())
		.collect::<Vec<_>>();
	if reasons.is_empty() {
		lines.push("- prepare release".to_string());
	} else {
		for reason in reasons {
			lines.push(format!("- {reason}"));
		}
	}
	lines.join("\n")
}

#[cfg(test)]
mod __tests;