sampo-github-action 0.15.4

GitHub Action runner for Sampo CLI (release/publish orchestrator)
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
mod error;
mod git;
mod github;
mod sampo;

use crate::error::{ActionError, Result};
use crate::sampo::ReleasePlan;
use glob::glob;
use sampo_core::errors::SampoError;
use sampo_core::workspace::discover_workspace;
use sampo_core::{Config as SampoConfig, PublishExtraArgs, current_branch};
use semver::Version;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

// Error type and Result are provided by sampo-core::errors

#[derive(Debug, Clone)]
struct GitHubReleaseOptions {
    /// Create GitHub releases for newly created tags during publish
    create_github_release: bool,
    /// Filter for which packages should have GitHub Discussions opened
    open_discussion: DiscussionFilter,
    /// Preferred Discussions category slug (e.g., "announcements")
    discussion_category: Option<String>,
    /// Release asset patterns provided by the workflow (already-built artifacts)
    asset_specs: Vec<AssetSpec>,
}

impl GitHubReleaseOptions {
    fn from_config(config: &Config) -> Self {
        Self {
            create_github_release: config.create_github_release,
            open_discussion: config.open_discussion.clone(),
            discussion_category: config.discussion_category.clone(),
            asset_specs: parse_asset_specs(config.release_assets.as_deref()),
        }
    }
}

#[derive(Debug, Clone)]
struct AssetSpec {
    pattern: String,
    rename: Option<String>,
}

#[derive(Debug)]
struct ResolvedAsset {
    path: PathBuf,
    asset_name: String,
}

#[derive(Debug, Clone, Copy)]
enum Mode {
    Auto,
    Release,
    Publish,
}

impl Mode {
    fn parse(s: &str) -> Self {
        match s.to_ascii_lowercase().as_str() {
            "auto" | "automatic" => Mode::Auto,
            "release" => Mode::Release,
            "publish" => Mode::Publish,
            _ => Mode::Auto,
        }
    }
}

/// Filter for which packages should have GitHub Discussions opened.
///
/// Supports:
/// - `All`: Open discussions for all packages (when input is "true")
/// - `None`: Never open discussions (when input is "false" or empty)
/// - `Packages`: Only open discussions for specific packages (comma-separated list)
#[derive(Debug, Clone)]
enum DiscussionFilter {
    /// Open discussions for all released packages
    All,
    /// Never open discussions
    None,
    /// Open discussions only for these specific package names
    Packages(Vec<String>),
}

impl DiscussionFilter {
    /// Parse the INPUT_OPEN_DISCUSSION environment variable value.
    ///
    /// Accepts:
    /// - "true" -> All
    /// - "false" or empty -> None
    /// - "pkg1,pkg2,pkg3" -> Packages(["pkg1", "pkg2", "pkg3"])
    fn parse(input: &str) -> Self {
        let trimmed = input.trim();
        if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("false") {
            DiscussionFilter::None
        } else if trimmed.eq_ignore_ascii_case("true") {
            DiscussionFilter::All
        } else {
            let packages: Vec<String> = trimmed
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            if packages.is_empty() {
                DiscussionFilter::None
            } else {
                DiscussionFilter::Packages(packages)
            }
        }
    }

    /// Check if a discussion should be opened for a given package name.
    fn should_open_for(&self, package_name: &str) -> bool {
        match self {
            DiscussionFilter::All => true,
            DiscussionFilter::None => false,
            DiscussionFilter::Packages(packages) => packages.iter().any(|p| p == package_name),
        }
    }
}

/// Sampo GitHub Action configuration
///
/// This configuration reads inputs from GitHub Actions environment variables.
/// GitHub Actions inputs are exposed as INPUT_* environment variables.
#[derive(Debug)]
struct Config {
    /// Which operation to run (release, publish, or both)
    mode: Mode,

    /// Simulate actions without changing files or publishing artifacts
    dry_run: bool,

    /// Path to the repository root (defaults to GITHUB_WORKSPACE)
    working_directory: Option<PathBuf>,

    /// Optional crates.io token (exported to child processes)
    cargo_token: Option<String>,

    /// Extra args passed through to `sampo publish` (after `--`)
    /// Accepts a single string that will be split on whitespace.
    args: Option<String>,

    /// Extra arguments forwarded only to `cargo publish`
    cargo_args: Option<String>,

    /// Extra arguments forwarded only to npm/pnpm/yarn/bun publish
    npm_args: Option<String>,

    /// Extra arguments forwarded only to `mix hex.publish`
    hex_args: Option<String>,

    /// Extra arguments forwarded only to PyPI/twine upload
    pypi_args: Option<String>,

    /// Extra arguments forwarded only to Packagist/Composer
    packagist_args: Option<String>,

    /// Base branch for the Release PR (default: current ref name or 'main')
    base_branch: Option<String>,

    /// Branch name to use for the Release PR (default: 'release/sampo')
    pr_branch: Option<String>,

    /// Title to use for the Release PR (default: 'Release')
    pr_title: Option<String>,

    /// Branch name to use for the Stabilize PR (default: 'stabilize/<branch>')
    stabilize_pr_branch: Option<String>,

    /// Title to use for the Stabilize PR (default: 'Release stable (<branch>)')
    stabilize_pr_title: Option<String>,

    /// Create GitHub releases for newly created tags during publish
    create_github_release: bool,

    /// Filter for which packages should have GitHub Discussions opened
    open_discussion: DiscussionFilter,

    /// Preferred Discussions category slug (e.g., "announcements")
    discussion_category: Option<String>,

    /// Paths or glob patterns to upload as release assets (comma or newline separated)
    release_assets: Option<String>,
}

impl Config {
    /// Load configuration from GitHub Actions environment variables
    fn from_environment() -> Self {
        let mode = std::env::var("INPUT_COMMAND")
            .ok()
            .filter(|v| !v.is_empty())
            .map(|v| Mode::parse(&v))
            .unwrap_or(Mode::Auto);

        let dry_run = std::env::var("INPUT_DRY_RUN")
            .map(|v| v.eq_ignore_ascii_case("true") || v.trim() == "1")
            .unwrap_or(false);

        let working_directory = std::env::var("INPUT_WORKING_DIRECTORY")
            .ok()
            .filter(|v| !v.is_empty())
            .map(PathBuf::from);

        let cargo_token = std::env::var("INPUT_CARGO_TOKEN")
            .ok()
            .filter(|v| !v.is_empty());

        let args = std::env::var("INPUT_ARGS").ok().filter(|v| !v.is_empty());

        let cargo_args = std::env::var("INPUT_CARGO_ARGS")
            .ok()
            .filter(|v| !v.is_empty());

        let npm_args = std::env::var("INPUT_NPM_ARGS")
            .ok()
            .filter(|v| !v.is_empty());

        let hex_args = std::env::var("INPUT_HEX_ARGS")
            .ok()
            .filter(|v| !v.is_empty());

        let pypi_args = std::env::var("INPUT_PYPI_ARGS")
            .ok()
            .filter(|v| !v.is_empty());

        let packagist_args = std::env::var("INPUT_PACKAGIST_ARGS")
            .ok()
            .filter(|v| !v.is_empty());

        let base_branch = std::env::var("INPUT_BASE_BRANCH")
            .ok()
            .filter(|v| !v.is_empty());

        let pr_branch = std::env::var("INPUT_PR_BRANCH")
            .ok()
            .filter(|v| !v.is_empty());

        let pr_title = std::env::var("INPUT_PR_TITLE")
            .ok()
            .filter(|v| !v.is_empty());

        let stabilize_pr_branch = std::env::var("INPUT_STABILIZE_PR_BRANCH")
            .ok()
            .filter(|v| !v.is_empty());

        let stabilize_pr_title = std::env::var("INPUT_STABILIZE_PR_TITLE")
            .ok()
            .filter(|v| !v.is_empty());

        let create_github_release = std::env::var("INPUT_CREATE_GITHUB_RELEASE")
            .map(|v| v.eq_ignore_ascii_case("true") || v.trim() == "1")
            .unwrap_or(false);

        let open_discussion = std::env::var("INPUT_OPEN_DISCUSSION")
            .map(|v| DiscussionFilter::parse(&v))
            .unwrap_or(DiscussionFilter::None);

        let discussion_category = std::env::var("INPUT_DISCUSSION_CATEGORY")
            .ok()
            .filter(|v| !v.is_empty());

        let release_assets = std::env::var("INPUT_RELEASE_ASSETS")
            .ok()
            .filter(|v| !v.is_empty());

        Self {
            mode,
            dry_run,
            working_directory,
            cargo_token,
            args,
            cargo_args,
            npm_args,
            hex_args,
            pypi_args,
            packagist_args,
            base_branch,
            pr_branch,
            pr_title,
            stabilize_pr_branch,
            stabilize_pr_title,
            create_github_release,
            open_discussion,
            discussion_category,
            release_assets,
        }
    }
}

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("Error: {}", e);
            ExitCode::FAILURE
        }
    }
}

fn run() -> Result<()> {
    let config = Config::from_environment();

    let workspace = determine_workspace(&config)?;

    let repo_config = SampoConfig::load(&workspace).unwrap_or_default();

    let branch = current_branch()?;
    if !repo_config.is_release_branch(&branch) {
        return Err(SampoError::Release(format!(
            "Branch '{}' is not listed in git.release_branches (allowed: {:?})",
            branch,
            repo_config
                .release_branches()
                .into_iter()
                .collect::<Vec<_>>()
        ))
        .into());
    }

    unsafe {
        std::env::set_var("SAMPO_RELEASE_BRANCH", &branch);
    }

    // Execute the requested operations
    let (released, published) = execute_operations(&config, &workspace, &repo_config, &branch)?;

    // Emit outputs for the workflow
    emit_github_output("released", released)?;
    emit_github_output("published", published)?;

    Ok(())
}

/// Determine the workspace root directory
fn determine_workspace(config: &Config) -> Result<PathBuf> {
    config
        .working_directory
        .clone()
        .or_else(|| std::env::var("GITHUB_WORKSPACE").ok().map(PathBuf::from))
        .ok_or(ActionError::NoWorkingDirectory)
}

/// Execute the requested operations and return (released, published) status
///
/// In `auto` mode we always run a dry `sampo release` first (`capture_release_plan`).
/// If there are pending changesets we prepare/update the release PR (which runs a
/// real `sampo release`). Otherwise we fall back to `post_merge_publish`, which
/// reuses the same publish pipeline as the explicit `publish` mode. That pipeline
/// only publishes crates that still need it (via `sampo_core::run_publish`) and
/// reports `published = true` exclusively when fresh git tags were produced, so a
/// plain commit without changesets will exit cleanly without pushing anything.
fn execute_operations(
    config: &Config,
    workspace: &Path,
    repo_config: &SampoConfig,
    branch: &str,
) -> Result<(bool, bool)> {
    let mut released = false;
    let mut published = false;

    match config.mode {
        Mode::Auto => {
            let plan = sampo::capture_release_plan(workspace)?;
            if plan.has_changes {
                println!(
                    "Detected {} pending release package(s); preparing release PR.",
                    plan.releases.len()
                );
                let plan_requires_stabilize = plan_includes_prerelease(&plan.releases);
                let github_client = create_github_client()?;
                let release_prepared = prepare_release_pr(
                    workspace,
                    config,
                    repo_config,
                    branch,
                    &github_client,
                    Some(plan),
                )?;
                let stabilize_prepared = if release_prepared && plan_requires_stabilize {
                    prepare_stabilize_pr(workspace, config, repo_config, branch, &github_client)?
                } else {
                    if plan_requires_stabilize && !release_prepared {
                        println!(
                            "Skipped stabilize PR because release PR preparation did not complete."
                        );
                    }
                    false
                };
                released = release_prepared || stabilize_prepared;
            } else {
                // Prerelease packages with preserved changesets need a stabilize PR even
                // when there are no pending changesets in the regular changesets directory.
                let prerelease_packages = collect_prerelease_packages(workspace)?;
                if !prerelease_packages.is_empty() {
                    println!(
                        "No pending changesets but prerelease packages exist on branch '{}'; checking for stabilize PR.",
                        branch
                    );
                    let github_client = create_github_client()?;
                    released = prepare_stabilize_pr(
                        workspace,
                        config,
                        repo_config,
                        branch,
                        &github_client,
                    )?;
                }
                println!(
                    "No pending changesets found on branch '{}'. Checking for merged releases to publish.",
                    branch
                );
                let github_options = GitHubReleaseOptions::from_config(config);
                let github_client = if github_options.create_github_release {
                    Some(create_github_client()?)
                } else {
                    None
                };
                let extra_args = build_publish_extra_args(config);
                published = post_merge_publish(
                    workspace,
                    config.dry_run,
                    &extra_args,
                    config.cargo_token.as_deref(),
                    &github_options,
                    github_client.as_ref(),
                )?;
            }
        }
        Mode::Release => {
            sampo::run_release(workspace, config.dry_run, config.cargo_token.as_deref())?;
            released = true;
        }
        Mode::Publish => {
            let github_options = GitHubReleaseOptions::from_config(config);
            let github_client = if github_options.create_github_release {
                Some(create_github_client()?)
            } else {
                None
            };
            let extra_args = build_publish_extra_args(config);
            published = post_merge_publish(
                workspace,
                config.dry_run,
                &extra_args,
                config.cargo_token.as_deref(),
                &github_options,
                github_client.as_ref(),
            )?;
        }
    }

    Ok((released, published))
}

/// Emit a GitHub Actions output
fn emit_github_output(key: &str, value: bool) -> Result<()> {
    let value_str = if value { "true" } else { "false" };

    if let Some(path) = std::env::var_os("GITHUB_OUTPUT") {
        let mut file = OpenOptions::new().create(true).append(true).open(path)?;
        writeln!(file, "{}={}", key, value_str)?;
    }

    Ok(())
}

/// Create a GitHub client if credentials are available
fn create_github_client() -> Result<github::GitHubClient> {
    let repo = std::env::var("GITHUB_REPOSITORY")
        .map_err(|_| ActionError::GitHubCredentialsNotAvailable)?;
    let token =
        std::env::var("GITHUB_TOKEN").map_err(|_| ActionError::GitHubCredentialsNotAvailable)?;

    if repo.is_empty() || token.is_empty() {
        return Err(ActionError::GitHubCredentialsNotAvailable);
    }

    github::GitHubClient::new(repo, token)
}

fn prepare_release_pr(
    workspace: &Path,
    config: &Config,
    repo_config: &SampoConfig,
    branch: &str,
    github_client: &github::GitHubClient,
    provided_plan: Option<ReleasePlan>,
) -> Result<bool> {
    let plan = match provided_plan {
        Some(plan) => plan,
        None => sampo::capture_release_plan(workspace)?,
    };

    if !plan.has_changes {
        println!("No changesets detected. Skipping PR preparation.");
        return Ok(false);
    }

    let releases = &plan.releases;

    // Configuration
    let base_branch = config
        .base_branch
        .clone()
        .unwrap_or_else(|| branch.to_string());
    let is_prerelease = plan_includes_prerelease(releases);
    let pr_branch = config
        .pr_branch
        .clone()
        .unwrap_or_else(|| default_pr_branch(branch, is_prerelease));
    let pr_title = config
        .pr_title
        .clone()
        .unwrap_or_else(|| default_pr_title(branch, is_prerelease));

    // Build PR body BEFORE running release (release will consume changesets)
    let pr_body = {
        // Load configuration for dependency explanations
        let body = sampo::build_release_pr_body(workspace, releases, repo_config)?;
        if body.trim().is_empty() {
            println!("No applicable package changes for PR body. Skipping PR creation.");
            return Ok(false);
        }
        body
    };

    // Setup git
    git::setup_bot_user(workspace)?;
    git::git(&["fetch", "origin", "--prune"], Some(workspace))?;

    // Create release branch
    git::git(
        &[
            "checkout",
            "-B",
            &pr_branch,
            &format!("origin/{}", base_branch),
        ],
        Some(workspace),
    )?;

    // Apply release (no tags)
    sampo::run_release(workspace, false, config.cargo_token.as_deref())?;

    // Check for changes and commit
    if !git::has_changes(workspace)? {
        println!("No file changes after release. Skipping commit/PR.");
        git::git(&["checkout", branch], Some(workspace))?;
        return Ok(false);
    }

    git::git(&["add", "-A"], Some(workspace))?;
    git::git(
        &[
            "commit",
            "-m",
            "chore(release): bump versions and changelogs",
        ],
        Some(workspace),
    )?;

    // Force push to release branch (overwrites any existing branch)
    git::git(
        &["push", "origin", &format!("HEAD:{}", pr_branch), "--force"],
        Some(workspace),
    )?;

    // Create PR
    github_client.ensure_pull_request(&pr_branch, &base_branch, &pr_title, &pr_body)?;

    // Switch back to the release branch's base to keep the workspace ready for subsequent steps
    git::git(&["checkout", branch], Some(workspace))?;

    println!(
        "Prepared release PR with {} pending package(s).",
        releases.len()
    );

    Ok(true)
}

fn prepare_stabilize_pr(
    workspace: &Path,
    config: &Config,
    repo_config: &SampoConfig,
    branch: &str,
    github_client: &github::GitHubClient,
) -> Result<bool> {
    let prerelease_packages = collect_prerelease_packages(workspace)?;
    if prerelease_packages.is_empty() {
        println!("Workspace packages are already stable. Skipping stabilize PR.");
        return Ok(false);
    }

    let base_branch = config
        .base_branch
        .clone()
        .unwrap_or_else(|| branch.to_string());
    let pr_branch = config
        .stabilize_pr_branch
        .clone()
        .unwrap_or_else(|| default_stabilize_pr_branch(branch));
    let pr_title = config
        .stabilize_pr_title
        .clone()
        .unwrap_or_else(|| default_stabilize_pr_title(branch));

    git::setup_bot_user(workspace)?;
    git::git(&["fetch", "origin", "--prune"], Some(workspace))?;
    git::git(
        &[
            "checkout",
            "-B",
            &pr_branch,
            &format!("origin/{}", base_branch),
        ],
        Some(workspace),
    )?;

    let plan = sampo::capture_stabilize_plan(workspace)?;
    if !plan.has_changes {
        println!("No stable release changes detected. Skipping stabilize PR.");
        git::git(
            &["reset", "--hard", &format!("origin/{}", base_branch)],
            Some(workspace),
        )?;
        git::git(&["checkout", branch], Some(workspace))?;
        return Ok(false);
    }

    let pr_body = {
        let body = sampo::build_release_pr_body(workspace, &plan.releases, repo_config)?;
        if body.trim().is_empty() {
            println!("No applicable package changes for stabilize PR body. Skipping PR creation.",);
            git::git(
                &["reset", "--hard", &format!("origin/{}", base_branch)],
                Some(workspace),
            )?;
            git::git(&["checkout", branch], Some(workspace))?;
            return Ok(false);
        }
        body
    };

    sampo::run_stabilize_release(workspace, false, config.cargo_token.as_deref())?;

    if !git::has_changes(workspace)? {
        println!("No file changes after stabilize release. Skipping commit/PR.");
        git::git(
            &["reset", "--hard", &format!("origin/{}", base_branch)],
            Some(workspace),
        )?;
        git::git(&["checkout", branch], Some(workspace))?;
        return Ok(false);
    }

    git::git(&["add", "-A"], Some(workspace))?;
    git::git(
        &[
            "commit",
            "-m",
            "chore(release): stabilize versions and changelogs",
        ],
        Some(workspace),
    )?;

    git::git(
        &["push", "origin", &format!("HEAD:{}", pr_branch), "--force"],
        Some(workspace),
    )?;

    github_client.ensure_pull_request(&pr_branch, &base_branch, &pr_title, &pr_body)?;
    git::git(&["checkout", branch], Some(workspace))?;

    println!(
        "Prepared stabilize PR with {} pending package(s).",
        plan.releases.len()
    );

    Ok(true)
}

fn sanitized_branch_name(branch: &str) -> String {
    branch.replace('/', "-")
}

fn plan_includes_prerelease(releases: &BTreeMap<String, (String, String, String)>) -> bool {
    releases.values().any(|(_, _, new_version)| {
        Version::parse(new_version)
            .map(|version| !version.pre.is_empty())
            .unwrap_or(false)
    })
}

fn collect_prerelease_packages(workspace: &Path) -> Result<Vec<String>> {
    let ws = discover_workspace(workspace).map_err(|e| ActionError::SampoCommandFailed {
        operation: "workspace-discovery".to_string(),
        message: e.to_string(),
    })?;

    let mut names: Vec<String> = ws
        .members
        .iter()
        .filter(|info| info.version.contains('-'))
        .map(|info| info.identifier.clone())
        .collect();
    names.sort();
    names.dedup();
    Ok(names)
}

fn default_pr_branch(branch: &str, is_prerelease: bool) -> String {
    let suffix = sanitized_branch_name(branch);
    if is_prerelease {
        format!("pre-release/{}", suffix)
    } else {
        format!("release/{}", suffix)
    }
}

fn default_pr_title(branch: &str, is_prerelease: bool) -> String {
    if is_prerelease {
        format!("Pre-release ({})", branch)
    } else {
        format!("Release ({})", branch)
    }
}

fn default_stabilize_pr_branch(branch: &str) -> String {
    format!("stabilize/{}", sanitized_branch_name(branch))
}

fn default_stabilize_pr_title(branch: &str) -> String {
    format!("Release stable ({})", branch)
}

fn parse_args_string(s: Option<&str>) -> Vec<String> {
    s.map(|a| a.split_whitespace().map(String::from).collect())
        .unwrap_or_default()
}

fn build_publish_extra_args(config: &Config) -> PublishExtraArgs {
    PublishExtraArgs {
        universal: parse_args_string(config.args.as_deref()),
        cargo: parse_args_string(config.cargo_args.as_deref()),
        npm: parse_args_string(config.npm_args.as_deref()),
        hex: parse_args_string(config.hex_args.as_deref()),
        pypi: parse_args_string(config.pypi_args.as_deref()),
        packagist: parse_args_string(config.packagist_args.as_deref()),
    }
}

/// Run `sampo publish` and handle the post-merge duties (tag push, GitHub releases).
/// Returns true only when new tags were created/pushed, so the workflow can tell if a
/// real publish happened. Combined with `sampo_core::run_publish` (which skips crates
/// already published or marked `publish = false`), this prevents accidental publishes
/// on commits sans changesets: the action simply logs "No new tags" and exits.
fn post_merge_publish(
    workspace: &Path,
    dry_run: bool,
    extra_args: &PublishExtraArgs,
    cargo_token: Option<&str>,
    github_options: &GitHubReleaseOptions,
    github_client: Option<&github::GitHubClient>,
) -> Result<bool> {
    // Setup git identity for tag creation
    git::setup_bot_user(workspace)?;

    // Publish and get information about tags created/would-be-created
    let publish_output = sampo::run_publish(workspace, dry_run, extra_args, cargo_token)?;
    let new_tags = publish_output.tags;

    if !dry_run && !new_tags.is_empty() {
        println!("Pushing {} new tags", new_tags.len());
        for tag in &new_tags {
            git::git(&["push", "origin", tag], Some(workspace))?;
        }
    } else if dry_run && !new_tags.is_empty() {
        println!(
            "Would push {} new tags (skipped in dry-run mode)",
            new_tags.len()
        );
        for tag in &new_tags {
            println!("  - {}", tag);
        }
    }

    if !dry_run
        && github_options.create_github_release
        && !new_tags.is_empty()
        && let Some(client) = github_client
    {
        for tag in &new_tags {
            println!("Creating GitHub release for {}", tag);
            create_github_release_for_tag(client, tag, workspace, github_options)?;
        }
    } else if dry_run && github_options.create_github_release && !new_tags.is_empty() {
        println!(
            "Would create {} GitHub releases (skipped in dry-run mode)",
            new_tags.len()
        );
        for tag in &new_tags {
            println!("  - {}", tag);
        }
    }

    let published = !dry_run && !new_tags.is_empty();
    if !published && !dry_run {
        println!("No new tags were created during publish.");
    }

    Ok(published)
}

fn create_github_release_for_tag(
    github_client: &github::GitHubClient,
    tag: &str,
    workspace: &Path,
    github_options: &GitHubReleaseOptions,
) -> Result<()> {
    let config = SampoConfig::load(workspace).ok();

    let body = match build_release_body_from_changelog(workspace, tag) {
        Some(body) => body,
        None => format!("Automated release for tag {}", tag),
    };

    let upload_url = match github_client.create_release(
        tag,
        &body,
        tag_is_prerelease_with_config(tag, config.as_ref()),
    ) {
        Ok(upload_url) => upload_url,
        Err(e) => {
            eprintln!(
                "Warning: Failed to create GitHub release for {}: {}",
                tag, e
            );
            return Ok(());
        }
    };

    if !upload_url.is_empty() {
        let assets = resolve_release_assets(workspace, tag, &github_options.asset_specs)?;
        if assets.is_empty() {
            if !github_options.asset_specs.is_empty() {
                eprintln!(
                    "Warning: No release assets matched the configured patterns for {}.",
                    tag
                );
            }
        } else {
            for asset in assets {
                match github_client.upload_release_asset(
                    &upload_url,
                    &asset.path,
                    &asset.asset_name,
                ) {
                    Ok(()) => {
                        println!(
                            "Uploaded release asset '{}' from {}",
                            asset.asset_name,
                            asset.path.display()
                        );
                    }
                    Err(error) => {
                        eprintln!(
                            "Warning: Failed to upload release asset '{}' for {} ({}): {}",
                            asset.asset_name,
                            tag,
                            asset.path.display(),
                            error
                        );
                    }
                }
            }
        }
    }

    // Optionally open a Discussion for this release (based on filter)
    if let Some((package_name, _version)) = parse_tag_with_config(tag, config.as_ref())
        && github_options
            .open_discussion
            .should_open_for(&package_name)
        && let Err(e) = github_client.create_discussion(
            tag,
            &body,
            github_options.discussion_category.as_deref(),
        )
    {
        eprintln!("Warning: Failed to create discussion for {}: {}", tag, e);
    }

    Ok(())
}

/// Build a release body by extracting the matching section from the crate's CHANGELOG.md
fn build_release_body_from_changelog(workspace: &Path, tag: &str) -> Option<String> {
    let config = SampoConfig::load(workspace).ok();
    let (crate_name, version) = parse_tag_with_config(tag, config.as_ref())?;

    // Find crate directory by name using the workspace API
    let ws = discover_workspace(workspace).ok()?;
    let crate_dir = ws
        .members
        .iter()
        .find(|c| c.name == crate_name)
        .map(|c| c.path.clone())
        // Fallback to a conventional path if discovery failed to find it
        .unwrap_or_else(|| workspace.join("crates").join(&crate_name));

    let changelog = crate_dir.join("CHANGELOG.md");
    extract_changelog_section(&changelog, &version)
}

/// Parse tag using config for short tag support, falling back to standard format.
fn parse_tag_with_config(tag: &str, config: Option<&SampoConfig>) -> Option<(String, String)> {
    if let Some(cfg) = config {
        cfg.parse_tag(tag)
    } else {
        // Fallback to standard format only when no config is available
        parse_tag(tag)
    }
}

/// Parse tags in standard format `<crate>-v<version>`.
fn parse_tag(tag: &str) -> Option<(String, String)> {
    let idx = tag.rfind("-v")?;
    let (name, ver) = tag.split_at(idx);
    let version = ver.trim_start_matches("-v").to_string();
    if name.is_empty() || version.is_empty() {
        return None;
    }
    Some((name.to_string(), version))
}

fn tag_is_prerelease_with_config(tag: &str, config: Option<&SampoConfig>) -> bool {
    parse_tag_with_config(tag, config)
        .and_then(|(_name, version)| Version::parse(&version).ok())
        .map(|parsed| !parsed.pre.is_empty())
        .unwrap_or_else(|| {
            // Fallback: try to parse version directly from short tag format
            if tag.starts_with('v') {
                Version::parse(tag.trim_start_matches('v'))
                    .map(|v| !v.pre.is_empty())
                    .unwrap_or(false)
            } else {
                false
            }
        })
}

/// Extract the section that follows the first `##` heading until the next `##` or EOF.
///
/// The leading heading itself is stripped because the GitHub release title already
/// conveys the version.
fn extract_changelog_section(path: &Path, _version: &str) -> Option<String> {
    let text = std::fs::read_to_string(path).ok()?;
    let mut collecting = false;
    let mut collected = Vec::new();

    for line in text.lines() {
        let trimmed = line.trim_start();
        if trimmed.starts_with("## ") {
            if collecting {
                break;
            }
            collecting = true;
            continue;
        }

        if collecting {
            collected.push(line);
        }
    }

    let body = collected.join("\n").trim().to_string();
    if body.is_empty() { None } else { Some(body) }
}

fn parse_asset_specs(input: Option<&str>) -> Vec<AssetSpec> {
    input
        .map(|raw| {
            raw.lines()
                .flat_map(|line| line.split(','))
                .filter_map(|entry| {
                    let trimmed = entry.trim();
                    if trimmed.is_empty() {
                        return None;
                    }
                    let mut parts = trimmed.splitn(2, "=>");
                    let pattern = parts.next().unwrap().trim();
                    if pattern.is_empty() {
                        return None;
                    }
                    let rename = parts
                        .next()
                        .map(|r| r.trim().to_string())
                        .filter(|r| !r.is_empty());
                    Some(AssetSpec {
                        pattern: pattern.to_string(),
                        rename,
                    })
                })
                .collect()
        })
        .unwrap_or_default()
}

fn resolve_release_assets(
    workspace: &Path,
    tag: &str,
    specs: &[AssetSpec],
) -> Result<Vec<ResolvedAsset>> {
    if specs.is_empty() {
        return Ok(Vec::new());
    }

    let config = SampoConfig::load(workspace).ok();
    let parsed_tag = parse_tag_with_config(tag, config.as_ref());
    let crate_name = parsed_tag.as_ref().map(|(name, _)| name.as_str());
    let version = parsed_tag.as_ref().map(|(_, ver)| ver.as_str());

    let mut resolved = Vec::new();
    let mut used_names = BTreeSet::new();

    for spec in specs {
        let rendered_pattern = render_asset_template(&spec.pattern, tag, crate_name, version);
        let rename_template = spec
            .rename
            .as_deref()
            .map(|value| render_asset_template(value, tag, crate_name, version));

        let pattern_path = {
            let base = Path::new(&rendered_pattern);
            if base.is_absolute() {
                base.to_path_buf()
            } else {
                workspace.join(base)
            }
        };
        let pattern_string = pattern_path.to_string_lossy().into_owned();

        let entries = glob(&pattern_string).map_err(|e| ActionError::SampoCommandFailed {
            operation: "release-asset-discovery".to_string(),
            message: format!(
                "Invalid release asset pattern '{}': {}",
                rendered_pattern, e
            ),
        })?;

        let mut matched = false;
        for entry in entries {
            match entry {
                Ok(path) => {
                    if path.is_dir() {
                        println!(
                            "Skipping directory match for pattern '{}': {}",
                            spec.pattern,
                            path.display()
                        );
                        continue;
                    }

                    matched = true;
                    let asset_name = rename_template
                        .as_deref()
                        .map(|name| name.to_string())
                        .unwrap_or_else(|| {
                            path.file_name()
                                .and_then(|name| name.to_str())
                                .unwrap_or(tag)
                                .to_string()
                        });

                    if asset_name.trim().is_empty() {
                        println!(
                            "Skipping asset with empty name for pattern '{}' (path: {})",
                            spec.pattern,
                            path.display()
                        );
                        continue;
                    }

                    if !used_names.insert(asset_name.clone()) {
                        println!(
                            "Skipping asset '{}' because another file already uses that name",
                            asset_name
                        );
                        continue;
                    }

                    resolved.push(ResolvedAsset { path, asset_name });
                }
                Err(err) => {
                    println!(
                        "Warning: Failed to read a path for pattern '{}': {}",
                        rendered_pattern, err
                    );
                }
            }
        }

        if !matched {
            println!(
                "No files matched release asset pattern '{}' (rendered: '{}')",
                spec.pattern, rendered_pattern
            );
        }
    }

    Ok(resolved)
}

fn render_asset_template(
    template: &str,
    tag: &str,
    crate_name: Option<&str>,
    version: Option<&str>,
) -> String {
    let mut rendered = template.replace("{{tag}}", tag);
    if let Some(name) = crate_name {
        rendered = rendered.replace("{{crate}}", name);
    } else {
        rendered = rendered.replace("{{crate}}", "");
    }
    if let Some(ver) = version {
        rendered = rendered.replace("{{version}}", ver);
    } else {
        rendered = rendered.replace("{{version}}", "");
    }
    rendered
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tag_is_prerelease(tag: &str) -> bool {
        tag_is_prerelease_with_config(tag, None)
    }

    #[test]
    fn default_branch_slugifies_path_segments() {
        assert_eq!(default_pr_branch("main", false), "release/main");
        assert_eq!(default_pr_branch("3.x", false), "release/3.x");
        assert_eq!(
            default_pr_branch("feature/foo", false),
            "release/feature-foo"
        );
    }

    #[test]
    fn default_title_includes_branch_name() {
        assert_eq!(default_pr_title("main", false), "Release (main)");
        assert_eq!(default_pr_title("3.x", false), "Release (3.x)");
    }

    #[test]
    fn stabilize_branch_uses_dedicated_prefix() {
        assert_eq!(default_stabilize_pr_branch("main"), "stabilize/main");
        assert_eq!(
            default_stabilize_pr_branch("feature/foo"),
            "stabilize/feature-foo"
        );
    }

    #[test]
    fn stabilize_title_includes_branch_name() {
        assert_eq!(default_stabilize_pr_title("main"), "Release stable (main)");
        assert_eq!(
            default_stabilize_pr_title("release-branch"),
            "Release stable (release-branch)"
        );
    }

    #[test]
    fn collect_prerelease_packages_detects_members() {
        use std::fs;
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();

        // Create .sampo/ directory (required for discover_workspace)
        fs::create_dir_all(root.join(".sampo")).unwrap();

        fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers=[\"crates/foo\", \"crates/bar\"]\n",
        )
        .unwrap();

        let foo_dir = root.join("crates/foo");
        let bar_dir = root.join("crates/bar");
        fs::create_dir_all(&foo_dir).unwrap();
        fs::create_dir_all(&bar_dir).unwrap();

        fs::write(
            foo_dir.join("Cargo.toml"),
            "[package]\nname=\"foo\"\nversion=\"0.2.0-beta.3\"\n",
        )
        .unwrap();

        fs::write(
            bar_dir.join("Cargo.toml"),
            "[package]\nname=\"bar\"\nversion=\"1.4.0\"\n",
        )
        .unwrap();

        let packages = collect_prerelease_packages(root).unwrap();
        assert_eq!(packages, vec!["cargo/foo".to_string()]);
    }

    #[test]
    fn collect_prerelease_packages_disambiguates_same_name() {
        use std::fs;
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();

        fs::create_dir_all(root.join(".sampo")).unwrap();

        fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers=[\"crates/foo\"]\n",
        )
        .unwrap();

        let foo_dir = root.join("crates/foo");
        fs::create_dir_all(&foo_dir).unwrap();

        fs::write(
            foo_dir.join("Cargo.toml"),
            "[package]\nname=\"foo\"\nversion=\"0.2.0-beta.3\"\n",
        )
        .unwrap();

        fs::write(
            root.join("package.json"),
            r#"{"name":"foo","version":"1.0.0-rc.1","workspaces":["packages/*"]}"#,
        )
        .unwrap();

        let packages = collect_prerelease_packages(root).unwrap();

        assert!(packages.contains(&"cargo/foo".to_string()));
        assert!(packages.contains(&"npm/foo".to_string()));
        assert_eq!(packages.len(), 2);
    }

    #[test]
    fn pre_release_branch_has_dedicated_prefix_and_title() {
        assert_eq!(default_pr_branch("next", true), "pre-release/next");
        assert_eq!(default_pr_title("next", true), "Pre-release (next)");
    }

    #[test]
    fn tag_pre_release_detection() {
        assert!(tag_is_prerelease("sampo-v1.2.0-alpha.1"));
        assert!(!tag_is_prerelease("sampo-v1.2.0"));
        assert!(!tag_is_prerelease("invalid"));
    }

    #[test]
    fn test_mode_parsing() {
        assert!(matches!(Mode::parse("auto"), Mode::Auto));
        assert!(matches!(Mode::parse("release"), Mode::Release));
        assert!(matches!(Mode::parse("publish"), Mode::Publish));
        assert!(matches!(Mode::parse("unknown"), Mode::Auto));
    }

    #[test]
    fn test_determine_workspace_with_config_override() {
        let config = Config {
            working_directory: Some(PathBuf::from("/test/path")),
            mode: Mode::Auto,
            dry_run: false,
            cargo_token: None,
            args: None,
            cargo_args: None,
            npm_args: None,
            hex_args: None,
            pypi_args: None,
            packagist_args: None,
            base_branch: None,
            pr_branch: None,
            pr_title: None,
            stabilize_pr_branch: None,
            stabilize_pr_title: None,
            create_github_release: false,
            open_discussion: DiscussionFilter::None,
            discussion_category: None,
            release_assets: None,
        };
        let result = determine_workspace(&config).unwrap();
        assert_eq!(result, PathBuf::from("/test/path"));
    }

    #[test]
    fn test_create_github_client() {
        // Test without environment variables
        unsafe {
            std::env::remove_var("GITHUB_REPOSITORY");
            std::env::remove_var("GITHUB_TOKEN");
        }
        assert!(create_github_client().is_err());

        // Test with empty values
        unsafe {
            std::env::set_var("GITHUB_REPOSITORY", "");
            std::env::set_var("GITHUB_TOKEN", "token");
        }
        assert!(create_github_client().is_err());

        // Test with valid values
        unsafe {
            std::env::set_var("GITHUB_REPOSITORY", "owner/repo");
            std::env::set_var("GITHUB_TOKEN", "valid_token");
        }
        assert!(create_github_client().is_ok());

        // Clean up
        unsafe {
            std::env::remove_var("GITHUB_REPOSITORY");
            std::env::remove_var("GITHUB_TOKEN");
        }
    }

    #[test]
    fn test_emit_github_output() {
        // This test would need mocking for real testing
        assert!(emit_github_output("test", true).is_ok());
    }

    #[test]
    fn parse_asset_specs_supports_patterns_and_rename() {
        let specs = parse_asset_specs(Some("dist/*.zip => package.zip,extra.bin"));
        assert_eq!(specs.len(), 2);
        assert_eq!(specs[0].pattern, "dist/*.zip");
        assert_eq!(specs[0].rename.as_deref(), Some("package.zip"));
        assert_eq!(specs[1].pattern, "extra.bin");
        assert!(specs[1].rename.is_none());
    }

    #[test]
    fn render_asset_template_substitutes_known_placeholders() {
        let rendered = render_asset_template(
            "artifacts/{{crate}}-{{version}}/{{tag}}.tar.gz",
            "my-crate-v1.0.0",
            Some("my-crate"),
            Some("1.0.0"),
        );
        assert_eq!(rendered, "artifacts/my-crate-1.0.0/my-crate-v1.0.0.tar.gz");
    }

    #[test]
    fn resolve_release_assets_matches_files() {
        use std::fs;
        let temp = tempfile::tempdir().unwrap();
        let workspace = temp.path();
        let dist_dir = workspace.join("dist");
        fs::create_dir_all(&dist_dir).unwrap();
        let artifact_path = dist_dir.join("my-crate-v1.0.0-x86_64.tar.gz");
        fs::write(&artifact_path, b"dummy").unwrap();

        let specs = vec![AssetSpec {
            pattern: "dist/{{crate}}-v{{version}}-*.tar.gz".to_string(),
            rename: Some("{{crate}}-{{version}}.tar.gz".to_string()),
        }];

        let assets = resolve_release_assets(workspace, "my-crate-v1.0.0", &specs)
            .expect("asset resolution should succeed");
        assert_eq!(assets.len(), 1);
        assert_eq!(assets[0].asset_name, "my-crate-1.0.0.tar.gz");
        assert_eq!(assets[0].path, artifact_path);
    }

    #[test]
    fn test_parse_tag() {
        assert_eq!(
            parse_tag("my-crate-v1.2.3"),
            Some(("my-crate".into(), "1.2.3".into()))
        );
        assert_eq!(
            parse_tag("sampo-v0.9.0"),
            Some(("sampo".into(), "0.9.0".into()))
        );
        assert_eq!(
            parse_tag("sampo-github-action-v0.8.2"),
            Some(("sampo-github-action".into(), "0.8.2".into()))
        );
        assert_eq!(parse_tag("nope"), None);
        assert_eq!(parse_tag("-v1.0.0"), None);
    }

    #[test]
    fn parse_tag_with_config_handles_short_format() {
        use std::fs;
        let temp = tempfile::tempdir().unwrap();
        fs::create_dir_all(temp.path().join(".sampo")).unwrap();
        fs::write(
            temp.path().join(".sampo/config.toml"),
            "[git]\nshort_tags = \"my-package\"\n",
        )
        .unwrap();

        let config = SampoConfig::load(temp.path()).unwrap();

        assert_eq!(
            parse_tag_with_config("v1.2.3", Some(&config)),
            Some(("my-package".to_string(), "1.2.3".to_string()))
        );

        assert_eq!(
            parse_tag_with_config("v1.2.3-alpha.1", Some(&config)),
            Some(("my-package".to_string(), "1.2.3-alpha.1".to_string()))
        );

        // Standard format still works for other packages
        assert_eq!(
            parse_tag_with_config("other-package-v2.0.0", Some(&config)),
            Some(("other-package".to_string(), "2.0.0".to_string()))
        );

        assert_eq!(parse_tag_with_config("v1.2", Some(&config)), None);
        assert_eq!(parse_tag_with_config("vfoo", Some(&config)), None);
    }

    #[test]
    fn parse_tag_with_config_falls_back_without_config() {
        assert_eq!(
            parse_tag_with_config("my-crate-v1.2.3", None),
            Some(("my-crate".to_string(), "1.2.3".to_string()))
        );

        assert_eq!(parse_tag_with_config("v1.2.3", None), None);
    }

    #[test]
    fn tag_is_prerelease_with_config_detects_short_format_prereleases() {
        use std::fs;
        let temp = tempfile::tempdir().unwrap();
        fs::create_dir_all(temp.path().join(".sampo")).unwrap();
        fs::write(
            temp.path().join(".sampo/config.toml"),
            "[git]\nshort_tags = \"my-package\"\n",
        )
        .unwrap();

        let config = SampoConfig::load(temp.path()).unwrap();

        assert!(tag_is_prerelease_with_config(
            "v1.0.0-alpha.1",
            Some(&config)
        ));
        assert!(tag_is_prerelease_with_config("v2.0.0-beta", Some(&config)));
        assert!(tag_is_prerelease_with_config("v1.0.0-rc.1", Some(&config)));

        assert!(!tag_is_prerelease_with_config("v1.0.0", Some(&config)));
        assert!(!tag_is_prerelease_with_config("v2.3.4", Some(&config)));

        assert!(tag_is_prerelease_with_config(
            "other-v1.0.0-alpha.1",
            Some(&config)
        ));
        assert!(!tag_is_prerelease_with_config(
            "other-v1.0.0",
            Some(&config)
        ));
    }

    #[test]
    fn resolve_release_assets_with_short_tags() {
        use std::fs;
        let temp = tempfile::tempdir().unwrap();
        let workspace = temp.path();

        fs::create_dir_all(workspace.join(".sampo")).unwrap();
        fs::write(
            workspace.join(".sampo/config.toml"),
            "[git]\nshort_tags = \"my-package\"\n",
        )
        .unwrap();

        let dist_dir = workspace.join("dist");
        fs::create_dir_all(&dist_dir).unwrap();
        let artifact_path = dist_dir.join("my-package-1.0.0-x86_64.tar.gz");
        fs::write(&artifact_path, b"dummy").unwrap();

        let specs = vec![AssetSpec {
            pattern: "dist/{{crate}}-{{version}}-*.tar.gz".to_string(),
            rename: Some("{{crate}}-{{version}}-release.tar.gz".to_string()),
        }];

        // Short tag format: v1.0.0 -> crate=my-package, version=1.0.0
        let assets = resolve_release_assets(workspace, "v1.0.0", &specs)
            .expect("asset resolution should succeed with short tags");

        assert_eq!(assets.len(), 1);
        assert_eq!(assets[0].asset_name, "my-package-1.0.0-release.tar.gz");
        assert_eq!(assets[0].path, artifact_path);
    }

    #[test]
    fn resolve_release_assets_short_tags_with_prerelease() {
        use std::fs;
        let temp = tempfile::tempdir().unwrap();
        let workspace = temp.path();

        fs::create_dir_all(workspace.join(".sampo")).unwrap();
        fs::write(
            workspace.join(".sampo/config.toml"),
            "[git]\nshort_tags = \"my-package\"\n",
        )
        .unwrap();

        let dist_dir = workspace.join("dist");
        fs::create_dir_all(&dist_dir).unwrap();
        let artifact_path = dist_dir.join("my-package-1.0.0-alpha.1-linux.tar.gz");
        fs::write(&artifact_path, b"dummy").unwrap();

        let specs = vec![AssetSpec {
            pattern: "dist/{{crate}}-{{version}}-linux.tar.gz".to_string(),
            rename: None,
        }];

        let assets = resolve_release_assets(workspace, "v1.0.0-alpha.1", &specs)
            .expect("asset resolution should succeed with short tag prerelease");

        assert_eq!(assets.len(), 1);
        // When no rename, asset_name is the original filename
        assert_eq!(
            assets[0].asset_name,
            "my-package-1.0.0-alpha.1-linux.tar.gz"
        );
    }

    #[test]
    fn test_asset_filtering_per_crate() {
        use std::fs;
        let temp = tempfile::tempdir().unwrap();
        let workspace = temp.path();
        let dist_dir = workspace.join("dist");
        fs::create_dir_all(&dist_dir).unwrap();

        // Create binaries for both sampo and sampo-github-action
        fs::write(
            dist_dir.join("sampo-x86_64-unknown-linux-gnu.tar.gz"),
            b"sampo-linux",
        )
        .unwrap();
        fs::write(
            dist_dir.join("sampo-x86_64-apple-darwin.tar.gz"),
            b"sampo-macos",
        )
        .unwrap();
        fs::write(
            dist_dir.join("sampo-github-action-x86_64-unknown-linux-gnu.tar.gz"),
            b"action-linux",
        )
        .unwrap();
        fs::write(
            dist_dir.join("sampo-github-action-x86_64-apple-darwin.tar.gz"),
            b"action-macos",
        )
        .unwrap();

        // Asset specs using {{crate}} template
        let specs = vec![
            AssetSpec {
                pattern: "dist/{{crate}}-x86_64-unknown-linux-gnu.tar.gz".to_string(),
                rename: Some("{{crate}}-{{version}}-x86_64-unknown-linux-gnu.tar.gz".to_string()),
            },
            AssetSpec {
                pattern: "dist/{{crate}}-x86_64-apple-darwin.tar.gz".to_string(),
                rename: Some("{{crate}}-{{version}}-x86_64-apple-darwin.tar.gz".to_string()),
            },
        ];

        // Test with sampo tag - should only match sampo binaries
        let sampo_assets = resolve_release_assets(workspace, "sampo-v0.9.0", &specs)
            .expect("sampo asset resolution should succeed");
        assert_eq!(
            sampo_assets.len(),
            2,
            "Should find exactly 2 sampo binaries"
        );
        assert!(
            sampo_assets
                .iter()
                .all(|a| a.asset_name.starts_with("sampo-0.9.0-"))
        );
        assert!(sampo_assets.iter().any(|a| a.asset_name.contains("linux")));
        assert!(sampo_assets.iter().any(|a| a.asset_name.contains("darwin")));

        // Test with sampo-github-action tag - should only match action binaries
        let action_assets = resolve_release_assets(workspace, "sampo-github-action-v0.8.2", &specs)
            .expect("action asset resolution should succeed");
        assert_eq!(
            action_assets.len(),
            2,
            "Should find exactly 2 action binaries"
        );
        assert!(
            action_assets
                .iter()
                .all(|a| a.asset_name.starts_with("sampo-github-action-0.8.2-"))
        );
        assert!(action_assets.iter().any(|a| a.asset_name.contains("linux")));
        assert!(
            action_assets
                .iter()
                .any(|a| a.asset_name.contains("darwin"))
        );
    }

    #[test]
    fn test_extract_changelog_section_with_timestamp() {
        use std::fs;
        use tempfile::TempDir;

        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("CHANGELOG.md");
        let content = "# my-crate\n\n## 1.2.3 — 2024-06-17\n\n### Patch changes\n\n- Fix: foo\n\n## 1.2.2\n\n- Older";
        fs::write(&file, content).unwrap();

        let got = extract_changelog_section(&file, "1.2.3").unwrap();
        assert!(got.starts_with("### Patch changes"));
        assert!(!got.contains("## 1.2.3"));
        assert!(got.contains("Fix: foo"));
        assert!(!got.contains("1.2.2"));
    }

    #[test]
    fn test_extract_changelog_section_without_timestamp() {
        use std::fs;
        use tempfile::TempDir;

        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("CHANGELOG.md");
        let content =
            "# my-crate\n\n## 2.0.0\n\n- New feature\n\n## 1.9.0 — 2023-12-01\n\n- Previous";
        fs::write(&file, content).unwrap();

        let got = extract_changelog_section(&file, "2.0.0").unwrap();
        assert!(got.starts_with("- New feature"));
        assert!(!got.contains("## 2.0.0"));
        assert!(!got.contains("1.9.0"));
    }

    #[test]
    fn test_discussion_filter_parsing() {
        // "false" or empty -> None
        assert!(matches!(
            DiscussionFilter::parse("false"),
            DiscussionFilter::None
        ));
        assert!(matches!(
            DiscussionFilter::parse("FALSE"),
            DiscussionFilter::None
        ));
        assert!(matches!(
            DiscussionFilter::parse(""),
            DiscussionFilter::None
        ));
        assert!(matches!(
            DiscussionFilter::parse("  "),
            DiscussionFilter::None
        ));

        // "true" -> All
        assert!(matches!(
            DiscussionFilter::parse("true"),
            DiscussionFilter::All
        ));
        assert!(matches!(
            DiscussionFilter::parse("TRUE"),
            DiscussionFilter::All
        ));
        assert!(matches!(
            DiscussionFilter::parse("True"),
            DiscussionFilter::All
        ));

        // Package list
        match DiscussionFilter::parse("sampo,sampo-github-action") {
            DiscussionFilter::Packages(pkgs) => {
                assert_eq!(pkgs, vec!["sampo", "sampo-github-action"]);
            }
            _ => panic!("Expected Packages variant"),
        }

        // Package list with whitespace
        match DiscussionFilter::parse("  pkg-a , pkg-b  , pkg-c  ") {
            DiscussionFilter::Packages(pkgs) => {
                assert_eq!(pkgs, vec!["pkg-a", "pkg-b", "pkg-c"]);
            }
            _ => panic!("Expected Packages variant"),
        }

        // Single package
        match DiscussionFilter::parse("my-crate") {
            DiscussionFilter::Packages(pkgs) => {
                assert_eq!(pkgs, vec!["my-crate"]);
            }
            _ => panic!("Expected Packages variant"),
        }
    }

    #[test]
    fn test_discussion_filter_should_open_for() {
        // All opens for any package
        let all = DiscussionFilter::All;
        assert!(all.should_open_for("sampo"));
        assert!(all.should_open_for("any-package"));

        // None never opens
        let none = DiscussionFilter::None;
        assert!(!none.should_open_for("sampo"));
        assert!(!none.should_open_for("any-package"));

        // Packages only opens for listed packages
        let packages = DiscussionFilter::Packages(vec![
            "sampo".to_string(),
            "sampo-github-action".to_string(),
        ]);
        assert!(packages.should_open_for("sampo"));
        assert!(packages.should_open_for("sampo-github-action"));
        assert!(!packages.should_open_for("sampo-core"));
        assert!(!packages.should_open_for("sampo-github-bot"));
    }
}