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
use rustc_hash::FxHashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::OnceLock;
use tempfile::TempDir;

/// Build the sampo-github-action binary and return its path
fn get_action_binary() -> &'static Path {
    static BINARY: OnceLock<PathBuf> = OnceLock::new();

    BINARY
        .get_or_init(|| {
            let crate_dir = std::env::var("CARGO_MANIFEST_DIR")
                .expect("CARGO_MANIFEST_DIR should be set during tests");
            let workspace_root = std::path::Path::new(&crate_dir)
                .parent()
                .and_then(|p| p.parent())
                .expect("Expected to find workspace root")
                .to_path_buf();

            let output = Command::new("cargo")
                .args(["build", "--bin", "sampo-github-action"])
                .current_dir(&workspace_root)
                .output()
                .expect("Failed to build sampo-github-action");

            if !output.status.success() {
                panic!(
                    "Failed to build binary: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
            }

            let full_path = workspace_root.join("target/debug/sampo-github-action");
            if !full_path.exists() {
                panic!("Binary not found at expected path: {}", full_path.display());
            }

            full_path
        })
        .as_path()
}

/// Run the action binary with environment variables
fn run_action(args: &[&str], env_vars: &FxHashMap<String, String>, working_dir: &Path) -> Output {
    let binary = get_action_binary();
    let mut cmd = Command::new(binary);
    cmd.args(args).current_dir(working_dir);

    // Clear the environment and only set our specified variables
    cmd.env_clear();

    // Set minimal required environment variables for Rust/cargo to work
    if let Ok(path) = std::env::var("PATH") {
        cmd.env("PATH", path);
    }
    if let Ok(home) = std::env::var("HOME") {
        cmd.env("HOME", home);
    }
    if let Ok(cargo_home) = std::env::var("CARGO_HOME") {
        cmd.env("CARGO_HOME", cargo_home);
    }
    if let Ok(rustup_home) = std::env::var("RUSTUP_HOME") {
        cmd.env("RUSTUP_HOME", rustup_home);
    }

    // Add our test-specific environment variables
    cmd.envs(env_vars);

    cmd.output().expect("Failed to execute action binary")
}

struct TestWorkspace {
    temp: TempDir,
}

impl TestWorkspace {
    fn new() -> Self {
        Self {
            temp: TempDir::new().expect("Failed to create temp dir"),
        }
    }

    fn path(&self) -> &Path {
        self.temp.path()
    }

    fn file_path(&self, relative: impl AsRef<Path>) -> PathBuf {
        self.path().join(relative)
    }

    fn write_file(&self, relative: impl AsRef<Path>, contents: &str) {
        let path = self.file_path(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("failed to create parent directories");
        }
        fs::write(path, contents).expect("failed to write file");
    }

    fn read_file(&self, relative: impl AsRef<Path>) -> String {
        fs::read_to_string(self.file_path(relative)).expect("failed to read file")
    }

    fn exists(&self, relative: impl AsRef<Path>) -> bool {
        self.file_path(relative).exists()
    }
}

/// Builder for creating test workspaces with various configurations
struct WorkspaceBuilder {
    crate_name: String,
    crate_version: String,
    with_changesets: bool,
    publish_enabled: bool,
    with_git: bool,
}

impl WorkspaceBuilder {
    fn new() -> Self {
        Self {
            crate_name: "foo".to_string(),
            crate_version: "0.1.0".to_string(),
            with_changesets: false,
            publish_enabled: true,
            with_git: false,
        }
    }

    #[allow(dead_code)]
    fn crate_name(mut self, name: &str) -> Self {
        self.crate_name = name.to_string();
        self
    }

    #[allow(dead_code)]
    fn crate_version(mut self, version: &str) -> Self {
        self.crate_version = version.to_string();
        self
    }

    fn with_changesets(mut self) -> Self {
        self.with_changesets = true;
        self
    }

    fn publish_disabled(mut self) -> Self {
        self.publish_enabled = false;
        self
    }

    fn with_git(mut self) -> Self {
        self.with_git = true;
        self
    }

    fn build(self, ws: &TestWorkspace) {
        // Create .sampo/ directory (required for discover_workspace)
        fs::create_dir_all(ws.file_path(".sampo")).expect("failed to create .sampo directory");

        // Create workspace Cargo.toml
        ws.write_file(
            "Cargo.toml",
            &format!(
                r#"[workspace]
resolver = "2"
members = ["crates/{}"]
"#,
                self.crate_name
            ),
        );

        // Create crate Cargo.toml
        let publish_line = if self.publish_enabled {
            ""
        } else {
            "publish = false\n"
        };

        ws.write_file(
            format!("crates/{}/Cargo.toml", self.crate_name),
            &format!(
                r#"[package]
name = "{}"
version = "{}"
edition = "2021"
{}
[lib]
path = "src/lib.rs"
"#,
                self.crate_name, self.crate_version, publish_line
            ),
        );

        // Create source files
        ws.write_file(
            format!("crates/{}/src/lib.rs", self.crate_name),
            &format!("pub fn {}() {{}}\n", self.crate_name.replace('-', "_")),
        );

        ws.write_file(
            format!("crates/{}/CHANGELOG.md", self.crate_name),
            "# Changelog\n\n## Unreleased\n\n",
        );

        // Add changesets if requested
        if self.with_changesets {
            ws.write_file(
                ".sampo/changesets/add-feature.md",
                &format!("---\n{}: minor\n---\n\n- add feature\n", self.crate_name),
            );
        }

        // Initialize git if requested
        if self.with_git {
            init_git_repo(ws.path());

            let add_status = Command::new("git")
                .args(["add", "."])
                .current_dir(ws.path())
                .status()
                .expect("failed to run git add");
            assert!(add_status.success(), "git add failed: {:?}", add_status);

            let commit_status = Command::new("git")
                .args(["commit", "-m", "Initial commit"])
                .current_dir(ws.path())
                .status()
                .expect("failed to run git commit");
            assert!(
                commit_status.success(),
                "git commit failed: {:?}",
                commit_status
            );
        }
    }
}

fn init_git_repo(path: &Path) {
    let status = Command::new("git")
        .arg("init")
        .current_dir(path)
        .status()
        .expect("failed to run git init");
    assert!(status.success(), "git init failed: {:?}", status);

    let email_status = Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(path)
        .status()
        .expect("failed to configure git user email");
    assert!(
        email_status.success(),
        "git config user.email failed: {:?}",
        email_status
    );

    let name_status = Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(path)
        .status()
        .expect("failed to configure git user name");
    assert!(
        name_status.success(),
        "git config user.name failed: {:?}",
        name_status
    );
}

fn parse_outputs(path: &Path) -> FxHashMap<String, String> {
    let mut outputs = FxHashMap::default();
    if !path.exists() {
        return outputs;
    }
    let content = fs::read_to_string(path).expect("failed to read outputs file");
    for line in content.lines() {
        if let Some((key, value)) = line.split_once('=') {
            outputs.insert(key.trim().to_string(), value.trim().to_string());
        }
    }
    outputs
}

fn setup_release_workspace(ws: &TestWorkspace) {
    WorkspaceBuilder::new().with_changesets().build(ws);
}

fn setup_publish_workspace(ws: &TestWorkspace) {
    WorkspaceBuilder::new()
        .publish_disabled()
        .with_git()
        .build(ws);
}

fn write_git_config(ws: &TestWorkspace, contents: &str) {
    let path = ws.file_path(".sampo/config.toml");
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("failed to create .sampo directory");
    }
    fs::write(path, contents).expect("failed to write config");
}

#[test]
fn test_missing_workspace_fails() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Don't set GITHUB_WORKSPACE environment variable
    let mut env_vars = FxHashMap::default();
    env_vars.insert("INPUT_COMMAND".to_string(), "release".to_string());

    let output = run_action(&[], &env_vars, temp_dir.path());

    // Should fail with specific exit code
    assert_eq!(
        output.status.code(),
        Some(1),
        "Action should fail with exit code 1"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Error: NoWorkingDirectory")
            || stderr.contains("No working directory provided"),
        "Should indicate missing workspace error, got: {}",
        stderr
    );
}

#[test]
fn test_default_command_is_auto() {
    let ws = TestWorkspace::new();
    WorkspaceBuilder::new().with_git().build(&ws);

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    // Don't set INPUT_COMMAND - should default to "auto"
    env_vars.insert("INPUT_DRY_RUN".to_string(), "true".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "main".to_string());

    let output = run_action(&[], &env_vars, ws.path());

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "Default mode should succeed in dry-run"
    );

    let outputs = parse_outputs(&output_file);
    assert_eq!(outputs.get("released").map(String::as_str), Some("false"));
    assert_eq!(outputs.get("published").map(String::as_str), Some("false"));

    assert!(
        stdout.contains("Publish plan:"),
        "Expected auto mode to trigger publish path, got stdout: {}",
        stdout
    );
}

#[test]
fn test_release_updates_versions_and_outputs() {
    let ws = TestWorkspace::new();
    setup_release_workspace(&ws);

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "release".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "main".to_string());

    let output = run_action(&[], &env_vars, ws.path());
    assert!(output.status.success(), "release command should succeed");

    let outputs = parse_outputs(&output_file);
    assert!(outputs.contains_key("released"));
    assert!(outputs.contains_key("published"));

    let manifest = ws.read_file("crates/foo/Cargo.toml");
    assert!(manifest.contains("version = \"0.2.0\""));
    assert!(manifest.contains("name = \"foo\""));

    let changelog = ws.read_file("crates/foo/CHANGELOG.md");
    assert!(changelog.contains("## 0.2.0"));
    assert!(!ws.exists(".sampo/changesets/add-feature.md"));
}

#[test]
fn test_publish_dry_run_with_private_packages() {
    let ws = TestWorkspace::new();
    setup_publish_workspace(&ws);

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "publish".to_string());
    env_vars.insert("INPUT_DRY_RUN".to_string(), "true".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "main".to_string());

    let output = run_action(&[], &env_vars, ws.path());
    assert!(output.status.success(), "publish command should succeed");

    // With private packages (publish = false), sampo publish should still work
    // and create tags for these packages in non-dry-run mode
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Dry-run complete."),
        "Expected dry-run to complete successfully"
    );

    let outputs = parse_outputs(&output_file);
    assert_eq!(outputs.get("released").map(String::as_str), Some("false"));
    assert_eq!(outputs.get("published").map(String::as_str), Some("false"));
}

#[test]
fn test_publish_private_packages_creates_tags_and_reports_published() {
    let ws = TestWorkspace::new();
    setup_publish_workspace(&ws);

    // Create a bare git repository to act as the "origin" remote
    let remote_dir = TempDir::new().expect("Failed to create remote dir");
    Command::new("git")
        .args(["init", "--bare"])
        .current_dir(remote_dir.path())
        .status()
        .expect("failed to init bare remote repo");

    // Add the bare repo as a remote origin
    Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            remote_dir.path().to_str().unwrap(),
        ])
        .current_dir(ws.path())
        .status()
        .expect("failed to add remote origin");

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "publish".to_string());
    // Non-dry-run mode to actually create tags
    env_vars.insert("INPUT_DRY_RUN".to_string(), "false".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "main".to_string());

    let output = run_action(&[], &env_vars, ws.path());
    if !output.status.success() {
        eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
    }
    assert!(output.status.success(), "publish command should succeed");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Publish complete."),
        "Expected non-dry-run publish to complete, got stdout: {}",
        stdout
    );

    // Verify outputs - this is the regression test for the original bug
    let outputs = parse_outputs(&output_file);
    assert_eq!(outputs.get("released").map(String::as_str), Some("false"));
    assert_eq!(
        outputs.get("published").map(String::as_str),
        Some("true"),
        "published should be true when private packages are versioned and tagged"
    );

    // Verify that git tags were actually created for the private package
    let tag_output = Command::new("git")
        .args(["tag", "--list", "foo-v*"])
        .current_dir(ws.path())
        .output()
        .expect("failed to list git tags");

    let tags = String::from_utf8_lossy(&tag_output.stdout);
    assert!(
        tags.contains("foo-v0.1.0"),
        "Expected git tag for private package foo@0.1.0, got tags: {}",
        tags
    );
}

/// Regression test: dry-run mode should NOT push tags or create GitHub releases.
/// This prevents accidental side effects when validating publish commands.
#[test]
fn test_publish_dry_run_does_not_push_tags() {
    let ws = TestWorkspace::new();
    setup_publish_workspace(&ws);

    let remote_dir = TempDir::new().expect("Failed to create remote dir");
    Command::new("git")
        .args(["init", "--bare"])
        .current_dir(remote_dir.path())
        .status()
        .expect("failed to init bare remote repo");

    Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            remote_dir.path().to_str().unwrap(),
        ])
        .current_dir(ws.path())
        .status()
        .expect("failed to add remote origin");

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "publish".to_string());
    env_vars.insert("INPUT_DRY_RUN".to_string(), "true".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "main".to_string());

    let output = run_action(&[], &env_vars, ws.path());
    assert!(
        output.status.success(),
        "publish dry-run command should succeed"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains("Dry-run complete."),
        "Expected dry-run to complete successfully, got stdout: {}",
        stdout
    );
    assert!(
        !stdout.contains("Pushing"),
        "Should not push tags in dry-run mode, got stdout: {}",
        stdout
    );

    let remote_tags = Command::new("git")
        .args(["tag", "--list"])
        .current_dir(remote_dir.path())
        .output()
        .expect("failed to list remote git tags");

    let tags = String::from_utf8_lossy(&remote_tags.stdout);
    assert!(
        tags.trim().is_empty(),
        "Remote should have no tags in dry-run mode, but found: {}",
        tags
    );

    let outputs = parse_outputs(&output_file);
    assert_eq!(
        outputs.get("published").map(String::as_str),
        Some("false"),
        "published should be false in dry-run mode"
    );
}

/// Regression test: dry-run mode should show informative messages about what would happen.
#[test]
fn test_publish_dry_run_shows_would_push_message() {
    let ws = TestWorkspace::new();

    // Package without existing tag triggers "Would push" message
    WorkspaceBuilder::new()
        .publish_disabled()
        .with_git()
        .build(&ws);

    let local_tags_before = Command::new("git")
        .args(["tag", "--list"])
        .current_dir(ws.path())
        .output()
        .expect("failed to list local tags");
    assert!(
        String::from_utf8_lossy(&local_tags_before.stdout)
            .trim()
            .is_empty(),
        "No tags should exist before dry-run"
    );

    let remote_dir = TempDir::new().expect("Failed to create remote dir");
    Command::new("git")
        .args(["init", "--bare"])
        .current_dir(remote_dir.path())
        .status()
        .expect("failed to init bare remote repo");

    Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            remote_dir.path().to_str().unwrap(),
        ])
        .current_dir(ws.path())
        .status()
        .expect("failed to add remote origin");

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "publish".to_string());
    env_vars.insert("INPUT_DRY_RUN".to_string(), "true".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "main".to_string());

    let output = run_action(&[], &env_vars, ws.path());
    assert!(
        output.status.success(),
        "publish dry-run command should succeed"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains("Would push") && stdout.contains("new tags"),
        "Expected 'Would push X new tags' message in dry-run output, got stdout: {}",
        stdout
    );
    assert!(
        stdout.contains("foo-v0.1.0"),
        "Expected tag name 'foo-v0.1.0' in would-push output, got stdout: {}",
        stdout
    );

    let local_tags_after = Command::new("git")
        .args(["tag", "--list"])
        .current_dir(ws.path())
        .output()
        .expect("failed to list local tags");
    assert!(
        String::from_utf8_lossy(&local_tags_after.stdout)
            .trim()
            .is_empty(),
        "No tags should be created in dry-run mode"
    );

    let remote_tags = Command::new("git")
        .args(["tag", "--list"])
        .current_dir(remote_dir.path())
        .output()
        .expect("failed to list remote git tags");

    let remote_tags_str = String::from_utf8_lossy(&remote_tags.stdout);
    assert!(
        remote_tags_str.trim().is_empty(),
        "Remote should have no tags after dry-run, but found: {}",
        remote_tags_str
    );

    let outputs = parse_outputs(&output_file);
    assert_eq!(
        outputs.get("published").map(String::as_str),
        Some("false"),
        "published should be false in dry-run mode"
    );
}

#[test]
fn test_auto_mode_detects_changesets() {
    let ws = TestWorkspace::new();
    WorkspaceBuilder::new().with_changesets().build(&ws);

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "auto".to_string());
    env_vars.insert("INPUT_DRY_RUN".to_string(), "true".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "main".to_string());

    let output = run_action(&[], &env_vars, ws.path());

    let stdout = String::from_utf8_lossy(&output.stdout);

    // In dry-run mode, auto should detect changesets and show planned releases
    assert!(
        stdout.contains("Detected") && stdout.contains("pending release package"),
        "Expected auto mode to announce pending releases, got stdout: {}",
        stdout
    );

    assert!(
        !output.status.success(),
        "Auto mode with changesets should fail without GitHub setup to avoid false positives"
    );
}

#[test]
fn test_action_rejects_non_release_branch() {
    let ws = TestWorkspace::new();
    WorkspaceBuilder::new().with_git().build(&ws);
    write_git_config(&ws, "[git]\nrelease_branches = [\"main\"]\n");

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "release".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "feature".to_string());

    let output = run_action(&[], &env_vars, ws.path());
    assert!(
        !output.status.success(),
        "action should fail on disallowed branch"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("not listed in git.release_branches")
            || stderr.contains("not configured for releases"),
        "expected branch guard error, got stderr: {}",
        stderr
    );
}

#[test]
fn test_action_accepts_configured_release_branch() {
    let ws = TestWorkspace::new();
    setup_release_workspace(&ws);
    write_git_config(&ws, "[git]\nrelease_branches = [\"main\", \"3.x\"]\n");

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "release".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "3.x".to_string());

    let output = run_action(&[], &env_vars, ws.path());
    assert!(
        output.status.success(),
        "action should allow configured branch"
    );

    let outputs = parse_outputs(&output_file);
    assert_eq!(outputs.get("released").map(String::as_str), Some("true"));
    assert_eq!(outputs.get("published").map(String::as_str), Some("false"));

    let manifest = ws.read_file("crates/foo/Cargo.toml");
    assert!(
        manifest.contains("version = \"0.2.0\"") || manifest.contains("version=\"0.2.0\""),
        "release should bump version, manifest was:\n{}",
        manifest
    );
    assert!(
        !ws.exists(".sampo/changesets/add-feature.md"),
        "release should consume the pending changeset"
    );
}

#[test]
fn test_action_accepts_configured_pre_release_branch() {
    let ws = TestWorkspace::new();
    setup_release_workspace(&ws);
    write_git_config(&ws, "[git]\nrelease_branches = [\"main\", \"next\"]\n");

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "release".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "next".to_string());

    let output = run_action(&[], &env_vars, ws.path());
    assert!(
        output.status.success(),
        "action should allow pre-release branch"
    );

    let outputs = parse_outputs(&output_file);
    assert_eq!(outputs.get("released").map(String::as_str), Some("true"));
    assert_eq!(outputs.get("published").map(String::as_str), Some("false"));
}

#[test]
fn test_auto_mode_without_changesets_attempts_publish() {
    let ws = TestWorkspace::new();
    WorkspaceBuilder::new().with_git().build(&ws);

    let output_file = ws.file_path("github_output");
    let mut env_vars = FxHashMap::default();
    env_vars.insert(
        "GITHUB_WORKSPACE".to_string(),
        ws.path().to_string_lossy().to_string(),
    );
    env_vars.insert(
        "GITHUB_OUTPUT".to_string(),
        output_file.to_string_lossy().to_string(),
    );
    env_vars.insert("INPUT_COMMAND".to_string(), "auto".to_string());
    env_vars.insert("INPUT_DRY_RUN".to_string(), "true".to_string());
    env_vars.insert("SAMPO_RELEASE_BRANCH".to_string(), "main".to_string());

    let output = run_action(&[], &env_vars, ws.path());

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should succeed in dry-run mode and show expected behavior
    assert!(
        output.status.success(),
        "Auto mode should succeed in dry-run without changesets"
    );

    /*
    Should follow the "no changesets -> try publish" logic path
    */
    assert!(
        stdout.contains("Publish plan:"),
        "Expected auto mode to attempt publish path, got stdout: {}",
        stdout
    );

    let outputs = parse_outputs(&output_file);
    assert_eq!(outputs.get("released").map(String::as_str), Some("false"));
    assert_eq!(outputs.get("published").map(String::as_str), Some("false"));
}