oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
//! Source-tool before-plan for `oakum migrate` (`okm-45t.1`).
//!
//! When knope / changesets / bumpy can supply a machine-readable plan, that is
//! the before fingerprint. When they cannot, the caller falls back to oakum
//! simulation and must exit unverified.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use super::{say_err, say_out};
use oakum::changeset::resolve_package_name;
use oakum::detect::ReleaseTool;
use oakum::discover::child::{deadline, find_program, output_within, said};
use oakum::discover::DiscoverError;
use oakum::plan::{PackageId, Workspace};
use semver::Version;
use serde::Deserialize;

#[derive(Debug)]
pub(super) enum SourceBeforePlan {
    Available {
        tool: ReleaseTool,
        fingerprint: BTreeMap<PackageId, (Version, Version)>,
        /// The child did not exit 0 and its output was read under a
        /// tool-specific convention rather than taken at face value. A
        /// difference measured against such a plan is not evidence the
        /// transform changed anything; only bumpy has such a convention.
        under_convention: bool,
    },
    /// Missing binary, failed run, or unusable output.
    Unavailable { tool: ReleaseTool, reason: String },
}

#[must_use]
pub(super) fn primary_plan_tool(knope: bool, bumpy: bool, changesets: bool) -> Option<ReleaseTool> {
    if knope {
        Some(ReleaseTool::Knope)
    } else if bumpy {
        Some(ReleaseTool::Bumpy)
    } else if changesets {
        Some(ReleaseTool::Changesets)
    } else {
        None
    }
}

pub(super) fn fetch_source_before_plan(
    tool: ReleaseTool,
    cwd: &Path,
    workspace: &Workspace,
) -> SourceBeforePlan {
    match tool {
        ReleaseTool::Bumpy => bumpy_status_json(cwd, workspace),
        ReleaseTool::Changesets => changesets_status_output(cwd, workspace),
        ReleaseTool::Knope => knope_release_dry_run(cwd, workspace),
        other => SourceBeforePlan::Unavailable {
            tool: other,
            reason: format!("{} has no migrate before-plan command", other.name()),
        },
    }
}

fn bumpy_status_json(cwd: &Path, workspace: &Workspace) -> SourceBeforePlan {
    let Some(bin) = resolve_tool_bin("bumpy", cwd) else {
        return SourceBeforePlan::Unavailable {
            tool: ReleaseTool::Bumpy,
            reason: not_found("bumpy"),
        };
    };
    let output = match run_tool(
        Command::new(&bin)
            .args(["status", "--json"])
            .current_dir(cwd),
        "bumpy",
        "bumpy status --json",
    ) {
        Ok(output) => output,
        Err(reason) => {
            return SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Bumpy,
                reason,
            };
        }
    };
    let stdout = String::from_utf8_lossy(&output.stdout);
    match parse_bumpy_status_json(&stdout, workspace) {
        Ok(fingerprint) => {
            // Exit 1 with nothing pending and nothing said is bumpy's "no
            // releases"; still a usable plan. Anything else that failed is a
            // tool that did not answer, and reading its empty output as an
            // authoritative empty plan would let a crashed bumpy certify the
            // migration — the changesets and knope arms already refuse it.
            let quiet_nothing_pending = output.status.code() == Some(1)
                && fingerprint.is_empty()
                && output.stderr.is_empty();
            // Taking the carve-out is worth a line: a crash that happens to
            // print parseable JSON with no releases is indistinguishable from
            // the convention, so a later divergence must be attributable to a
            // before-plan that came from a child which did not exit 0.
            if quiet_nothing_pending {
                say_out(
                    "plan comparison: `bumpy status --json` exited 1 with no releases, read as nothing pending"
                );
            }
            if !output.status.success() && !quiet_nothing_pending {
                let stderr = said(&output.stderr);
                return SourceBeforePlan::Unavailable {
                    tool: ReleaseTool::Bumpy,
                    reason: format!(
                        "`bumpy status --json` {}{}",
                        how_it_ended(output.status),
                        if stderr.is_empty() {
                            String::new()
                        } else {
                            format!(": {stderr}")
                        }
                    ),
                };
            }
            SourceBeforePlan::Available {
                tool: ReleaseTool::Bumpy,
                fingerprint,
                under_convention: quiet_nothing_pending,
            }
        }
        Err(reason) => {
            let stderr = said(&output.stderr);
            // How the child ended leads when it did not exit cleanly: a tool the
            // kernel killed writes nothing, and blaming the JSON for being empty
            // sends the reader after a parser rather than an OOM.
            let reason = if output.status.success() {
                reason
            } else {
                format!("{} ({reason})", how_it_ended(output.status))
            };
            let detail = if stderr.is_empty() {
                reason
            } else {
                format!("{reason}; stderr: {stderr}")
            };
            SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Bumpy,
                reason: detail,
            }
        }
    }
}

/// `releases` is required. With `#[serde(default)]` any JSON object at all
/// deserializes to zero releases, so a crashing bumpy's error envelope —
/// measured: `{"error":"database is locked","code":"EBUSY"}` at exit 1 — read
/// as an empty plan and was certified as the before-plan. The spec licenses
/// "exit 1 with no releases", which is not the same as "not a status document".
#[derive(Debug, Deserialize)]
struct BumpyStatusJson {
    releases: Vec<NamedRelease>,
}

#[derive(Debug, Deserialize)]
struct NamedRelease {
    name: String,
    #[serde(rename = "oldVersion")]
    old_version: String,
    #[serde(rename = "newVersion")]
    new_version: String,
    #[serde(rename = "type", default)]
    release_type: Option<String>,
}

fn parse_bumpy_status_json(
    json: &str,
    workspace: &Workspace,
) -> Result<BTreeMap<PackageId, (Version, Version)>, String> {
    let parsed: BumpyStatusJson =
        serde_json::from_str(json).map_err(|err| format!("bumpy JSON: {err}"))?;
    releases_to_fingerprint(
        parsed
            .releases
            .into_iter()
            .filter(|r| r.release_type.as_deref() != Some("none"))
            .map(|r| (r.name, r.old_version, r.new_version)),
        workspace,
        "bumpy",
    )
}

fn changesets_status_output(cwd: &Path, workspace: &Workspace) -> SourceBeforePlan {
    let Some(bin) = resolve_tool_bin("changeset", cwd) else {
        return SourceBeforePlan::Unavailable {
            tool: ReleaseTool::Changesets,
            reason: not_found("changeset"),
        };
    };
    let out_path = match exclusive_temp_json() {
        Ok(path) => path,
        Err(reason) => {
            return SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Changesets,
                reason,
            };
        }
    };
    let output = match run_tool(
        Command::new(&bin)
            .args(["status", "--output"])
            .arg(&out_path)
            .current_dir(cwd),
        "changeset",
        "changeset status --output",
    ) {
        Ok(output) => output,
        Err(reason) => {
            discard_temp(&out_path);
            return SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Changesets,
                reason,
            };
        }
    };
    if !output.status.success() {
        discard_temp(&out_path);
        // Non-success is not a verified plan, even when the file is parseable
        // (unlike bumpy's exit-1-with-empty-releases case).
        let stderr = said(&output.stderr);
        return SourceBeforePlan::Unavailable {
            tool: ReleaseTool::Changesets,
            reason: format!(
                "`changeset status` {}{}",
                how_it_ended(output.status),
                if stderr.is_empty() {
                    String::new()
                } else {
                    format!(": {stderr}")
                }
            ),
        };
    }
    let body = match fs::read_to_string(&out_path) {
        Ok(body) => {
            discard_temp(&out_path);
            body
        }
        Err(err) => {
            discard_temp(&out_path);
            let stderr = said(&output.stderr);
            return SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Changesets,
                reason: format!(
                    "changeset did not write `--output` file ({err}){}",
                    if stderr.is_empty() {
                        String::new()
                    } else {
                        format!("; stderr: {stderr}")
                    }
                ),
            };
        }
    };
    match parse_changesets_status_json(&body, workspace) {
        Ok(fingerprint) => SourceBeforePlan::Available {
            under_convention: false,
            tool: ReleaseTool::Changesets,
            fingerprint,
        },
        Err(reason) => SourceBeforePlan::Unavailable {
            tool: ReleaseTool::Changesets,
            reason,
        },
    }
}

#[derive(Debug, Deserialize)]
struct ChangesetsStatusJson {
    #[serde(default)]
    releases: Vec<ChangesetsRelease>,
}

#[derive(Debug, Deserialize)]
struct ChangesetsRelease {
    name: String,
    #[serde(rename = "type", default)]
    release_type: String,
    #[serde(rename = "oldVersion")]
    old_version: Option<String>,
    #[serde(rename = "newVersion")]
    new_version: Option<String>,
}

fn parse_changesets_status_json(
    json: &str,
    workspace: &Workspace,
) -> Result<BTreeMap<PackageId, (Version, Version)>, String> {
    let parsed: ChangesetsStatusJson =
        serde_json::from_str(json).map_err(|err| format!("changesets JSON: {err}"))?;
    let triples = parsed
        .releases
        .into_iter()
        .filter(|r| r.release_type != "none")
        .filter_map(|r| {
            let old = r.old_version?;
            let new = r.new_version?;
            Some((r.name, old, new))
        });
    releases_to_fingerprint(triples, workspace, "changesets")
}

fn knope_release_dry_run(cwd: &Path, workspace: &Workspace) -> SourceBeforePlan {
    let Some(bin) = resolve_tool_bin("knope", cwd) else {
        return SourceBeforePlan::Unavailable {
            tool: ReleaseTool::Knope,
            reason: not_found("knope"),
        };
    };
    let KnopeWorkflow {
        name: workflow,
        prepares_release,
    } = match knope_workflow(cwd) {
        Ok(workflow) => workflow,
        Err(reason) => {
            return SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Knope,
                reason,
            };
        }
    };
    let output = match run_tool(
        Command::new(&bin)
            .args([&workflow, "--dry-run"])
            .current_dir(cwd),
        "knope",
        &format!("knope {workflow} --dry-run"),
    ) {
        Ok(output) => output,
        Err(reason) => {
            return SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Knope,
                reason,
            };
        }
    };
    let combined = format!(
        "{}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    match parse_knope_dry_run(&combined, workspace) {
        Ok(fingerprint) if !fingerprint.is_empty() && output.status.success() => {
            SourceBeforePlan::Available {
                under_convention: false,
                tool: ReleaseTool::Knope,
                fingerprint,
            }
        }
        Ok(fingerprint) if !fingerprint.is_empty() => SourceBeforePlan::Unavailable {
            tool: ReleaseTool::Knope,
            reason: format!(
                "`knope {workflow} --dry-run` {} with version lines (not treated as verified evidence)",
                how_it_ended(output.status)
            ),
        },
        // A planning workflow prints nothing at all when nothing is pending
        // (measured on 0.23.1). Any other output with no version line is one
        // oakum did not recognise, not an empty plan.
        Ok(fingerprint)
            if prepares_release && output.status.success() && combined.trim().is_empty() =>
        {
            SourceBeforePlan::Available {
                under_convention: false,
                tool: ReleaseTool::Knope,
                fingerprint,
            }
        }
        Ok(_) if !prepares_release && output.status.success() && combined.trim().is_empty() => {
            SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Knope,
                reason: format!(
                    "`knope {workflow} --dry-run` printed nothing, and `knope.toml`'s `{workflow}` workflow has no `PrepareRelease` step, so knope did not plan"
                ),
            }
        }
        Ok(_) => {
            let first = combined.lines().map(str::trim).find(|line| !line.is_empty());
            SourceBeforePlan::Unavailable {
                tool: ReleaseTool::Knope,
                reason: match first {
                    Some(first) => format!(
                        "`knope {workflow} --dry-run` produced no usable version lines ({}; first line: {first:?})",
                        how_it_ended(output.status)
                    ),
                    None => format!(
                        "`knope {workflow} --dry-run` produced no usable version lines ({})",
                        how_it_ended(output.status)
                    ),
                },
            }
        }
        Err(reason) => SourceBeforePlan::Unavailable {
            tool: ReleaseTool::Knope,
            reason,
        },
    }
}

/// The workflow whose dry run states the before-plan, and whether it runs
/// `PrepareRelease`, or why oakum cannot say.
struct KnopeWorkflow {
    name: String,
    /// knope exits 0 silently both when nothing is pending and when the
    /// workflow never plans (measured on 0.22.4 and 0.23.2), so only a
    /// planning workflow's silence is an empty plan.
    prepares_release: bool,
}

fn knope_workflow(cwd: &Path) -> Result<KnopeWorkflow, String> {
    let body = match fs::read_to_string(cwd.join("knope.toml")) {
        Ok(body) => body,
        // Running `release` anyway would make a guess's output the evidence
        // behind a definitive "the release plan changed".
        Err(err) if err.kind() != std::io::ErrorKind::NotFound => {
            return Err(format!("could not read `knope.toml`: {err}"));
        }
        Err(_) => String::new(),
    };
    let config: toml::Value = toml::from_str(&body)
        .map_err(|err| format!("could not parse `knope.toml`: {}", err.message()))?;
    // knope rejects any other shape, so a run it reaches fails on its own.
    let declared: Vec<(&str, &toml::Value)> = config
        .get("workflows")
        .and_then(toml::Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|workflow| Some((workflow.get("name")?.as_str()?, workflow)))
        .collect();
    // No declared workflow runs knope's defaults, whose `release` plans.
    if declared.is_empty() {
        return Ok(KnopeWorkflow {
            name: String::from("release"),
            prepares_release: true,
        });
    }
    let (name, workflow) = declared
        .iter()
        .find(|(name, _)| *name == "prepare-release")
        .or_else(|| declared.iter().find(|(name, _)| *name == "release"))
        .copied()
        .unwrap_or(("release", &toml::Value::Boolean(false)));
    let prepares_release = workflow
        .get("steps")
        .and_then(toml::Value::as_array)
        .is_some_and(|steps| {
            steps.iter().any(|step| {
                step.get("type").and_then(toml::Value::as_str) == Some("PrepareRelease")
            })
        });
    Ok(KnopeWorkflow {
        name: name.to_owned(),
        prepares_release,
    })
}

/// Parse knope dry-run lines like `Would add the following to package.json: 1.0.1`,
/// `Would add the following to Cargo.toml: version = 1.1.0` (knope ≥0.23),
/// or `Would add the following to crates/core/Cargo.toml: 0.1.1`.
fn parse_knope_dry_run(
    text: &str,
    workspace: &Workspace,
) -> Result<BTreeMap<PackageId, (Version, Version)>, String> {
    let mut fingerprint = BTreeMap::new();
    let prefix = "Would add the following to ";
    for line in text.lines() {
        let Some(rest) = line.strip_prefix(prefix) else {
            continue;
        };
        let Some((path, version_text)) = rest.rsplit_once(':') else {
            continue;
        };
        let path = path.trim();
        let version_text = version_text.trim();
        if !path.ends_with("package.json") && !path.ends_with("Cargo.toml") {
            continue;
        }
        let to = parse_knope_version_payload(version_text)
            .map_err(|err| format!("knope dry-run version `{version_text}`: {err}"))?;
        let id = package_id_for_manifest_path(path, workspace).ok_or_else(|| {
            format!("knope dry-run named `{path}` which matches no workspace package")
        })?;
        let from = workspace
            .get(&id)
            .map(|pkg| pkg.version().clone())
            .ok_or_else(|| format!("workspace missing package for knope dry-run path `{path}`"))?;
        fingerprint.insert(id, (from, to));
    }
    Ok(fingerprint)
}

/// Accept bare `1.0.1` (documented tutorials) and `version = 1.1.0` / `version = "1.1.0"` (knope 0.23+).
fn parse_knope_version_payload(payload: &str) -> Result<Version, String> {
    let trimmed = payload.trim();
    let after_version = match trimmed.strip_prefix("version") {
        Some(rest) => {
            let rest = rest.trim_start();
            match rest.strip_prefix('=') {
                Some(value) => value.trim(),
                None => rest,
            }
            .trim_matches(|c| c == '"' || c == '\'')
        }
        None => trimmed,
    };
    // Extra assignments after the version (npm workspace dry-run noise): take the first token.
    let first = after_version
        .split_whitespace()
        .next()
        .unwrap_or(after_version)
        .trim_matches(|c| c == ',' || c == ';');
    Version::parse(first).map_err(|err| err.to_string())
}

fn package_id_for_manifest_path(path: &str, workspace: &Workspace) -> Option<PackageId> {
    let normalized = path.replace('\\', "/");
    let mut matches = Vec::new();
    for pkg in workspace.packages() {
        let expected = pkg.manifest_path().replace('\\', "/");
        if paths_equal_or_suffix(&normalized, &expected) {
            matches.push(pkg.id().clone());
        }
    }
    match matches.as_slice() {
        [only] => Some(only.clone()),
        _ => None,
    }
}

/// Exact match, or `…/<expected>` when `expected` is not a bare filename.
fn paths_equal_or_suffix(got: &str, expected: &str) -> bool {
    if got == expected {
        return true;
    }
    // Bare `Cargo.toml` / `package.json` only matches the repository-root package.
    if !expected.contains('/') {
        return false;
    }
    got.ends_with(&format!("/{expected}"))
}

fn releases_to_fingerprint(
    releases: impl IntoIterator<Item = (String, String, String)>,
    workspace: &Workspace,
    tool: &str,
) -> Result<BTreeMap<PackageId, (Version, Version)>, String> {
    let mut fingerprint = BTreeMap::new();
    for (name, old, new) in releases {
        let id = match resolve_package_name(&name, workspace) {
            Ok(id) => id,
            Err(oakum::changeset::UnknownReason::Missing) => {
                return Err(format!(
                    "{tool} release `{name}` matches no workspace package"
                ));
            }
            Err(oakum::changeset::UnknownReason::Ambiguous) => {
                return Err(format!(
                    "{tool} release `{name}` matches more than one workspace package"
                ));
            }
        };
        let from = Version::parse(&old)
            .map_err(|err| format!("{tool} oldVersion `{old}` for `{name}`: {err}"))?;
        let to = Version::parse(&new)
            .map_err(|err| format!("{tool} newVersion `{new}` for `{name}`: {err}"))?;
        fingerprint.insert(id, (from, to));
    }
    Ok(fingerprint)
}

/// Under the deadline every other child gets: a hung tool ends `migrate`
/// unverified instead of hanging it.
fn run_tool(command: &mut Command, tool: &'static str, shown: &str) -> Result<Output, String> {
    let limit = deadline()?;
    output_within(command, limit).map_err(|failure| {
        match DiscoverError::unanswered(tool, failure) {
            Ok(unanswered) => unanswered.to_string(),
            Err(err) => format!("failed to run `{shown}`: {err}"),
        }
    })
}

/// How a child ended, for a reason line. `code()` is `None` exactly when a
/// signal killed it, and `-1` is not a status any shell reports — a reader
/// debugging an OOM kill would go looking for the wrong thing.
fn how_it_ended(status: std::process::ExitStatus) -> String {
    match status.code() {
        Some(code) => format!("exited {code}"),
        None => String::from("was terminated by a signal"),
    }
}

/// The temp file is created with `create_new` and named by pid and nanos, so a
/// failed unlink leaves one behind per run rather than colliding. Naming it is
/// the difference between a reader cleaning up and never knowing.
fn discard_temp(path: &Path) {
    if let Err(err) = fs::remove_file(path) {
        if err.kind() != std::io::ErrorKind::NotFound {
            say_err(&format!("could not remove `{}`: {err}", path.display()));
        }
    }
}

/// The source tool's binary: this repository's own `node_modules/.bin` first,
/// then `PATH`.
///
/// The local directory is not a nicety. `npm i -g` and Homebrew put `oakum` on
/// `PATH` and a devDependency's binaries nowhere near it, so the install the
/// docs recommend leaves the source tool unrunnable and the parity check
/// unverified — on the one command whose whole job is comparing against that
/// tool (`okm-404.3`). Only `pnpm exec`, which prepends the directory, made the
/// verified path reachable.
///
/// Cargo and mise need no arm here: `cargo install` writes to `~/.cargo/bin`
/// and mise installs behind shims, and both are on `PATH` or the tool does not
/// run at all.
fn resolve_tool_bin(name: &str, cwd: &Path) -> Option<PathBuf> {
    let bin_dir = cwd.join("node_modules").join(".bin");
    for candidate in local_bin_names(name) {
        let local = bin_dir.join(candidate);
        if local.is_file() {
            return Some(local);
        }
    }
    find_program(name)
}

/// On Windows npm writes an extensionless shell script beside the `.cmd` shim,
/// and only the shim is executable: `CreateProcess` refuses a file with no
/// recognized extension. Listing the bare name there would find the script
/// first and fail the spawn, so Windows gets the shims alone.
///
/// Inferred, not measured — this host is not Windows.
fn local_bin_names(name: &str) -> Vec<String> {
    if cfg!(windows) {
        return Vec::from([format!("{name}.cmd"), format!("{name}.CMD")]);
    }
    Vec::from([name.to_owned()])
}

/// Where [`resolve_tool_bin`] looked, for a reason line that a reader can act
/// on: the two places differ in what installing differently would fix.
fn not_found(name: &str) -> String {
    format!("`{name}` not found (no local `node_modules/.bin/{name}`, none on PATH)")
}

fn exclusive_temp_json() -> Result<PathBuf, String> {
    use std::fs::OpenOptions;
    use std::time::{SystemTime, UNIX_EPOCH};

    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    let path = std::env::temp_dir().join(format!(
        "oakum-migrate-changeset-status-{}-{nanos}.json",
        std::process::id()
    ));
    OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
        .map_err(|err| {
            format!(
                "failed to create exclusive changeset status file {}: {err}",
                path.display()
            )
        })?;
    Ok(path)
}

#[cfg(test)]
mod local_shims {
    use super::local_bin_names;

    /// The Windows arm cannot be exercised on a unix host, so each platform
    /// pins its own list and the Windows CI job measures the branch this one
    /// cannot. `Command` there can launch the `.cmd` shim and not the
    /// extensionless script npm writes beside it, so the bare name must be
    /// absent rather than merely later in the list.
    #[test]
    fn each_platform_looks_for_the_names_it_can_execute() {
        let names = local_bin_names("changeset");
        #[cfg(windows)]
        assert_eq!(names, ["changeset.cmd", "changeset.CMD"]);
        #[cfg(not(windows))]
        assert_eq!(names, ["changeset"]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oakum::plan::{Ecosystem, Package, ResolvesDependenciesAt};

    fn cargo_ws(name: &str, version: &str) -> Workspace {
        let pkg = Package::new(
            PackageId::new(Ecosystem::Cargo, name),
            Version::parse(version).unwrap(),
            ResolvesDependenciesAt::Install,
            true,
            vec![],
        );
        Workspace::new(vec![pkg]).unwrap()
    }

    #[test]
    fn bumpy_json_parses_releases() {
        let ws = cargo_ws("core", "0.1.0");
        let json = r#"{
          "releases": [
            {"name": "core", "type": "minor", "oldVersion": "0.1.0", "newVersion": "0.2.0"}
          ],
          "packageNames": ["core"]
        }"#;
        let fp = parse_bumpy_status_json(json, &ws).unwrap();
        let id = PackageId::new(Ecosystem::Cargo, "core");
        assert_eq!(
            fp.get(&id),
            Some(&(Version::new(0, 1, 0), Version::new(0, 2, 0)))
        );
    }

    #[test]
    fn changesets_json_skips_none() {
        let ws = cargo_ws("core", "1.0.0");
        let json = r#"{
          "releases": [
            {"name": "other", "type": "none"},
            {"name": "core", "type": "patch", "oldVersion": "1.0.0", "newVersion": "1.0.1"}
          ]
        }"#;
        let fp = parse_changesets_status_json(json, &ws).unwrap();
        assert_eq!(fp.len(), 1);
    }

    #[test]
    fn knope_dry_run_root_manifest() {
        let ws = cargo_ws("core", "0.1.0");
        let text = "Would add the following to Cargo.toml: 0.1.1\nWould delete: .changeset/x.md\n";
        let fp = parse_knope_dry_run(text, &ws).unwrap();
        let id = PackageId::new(Ecosystem::Cargo, "core");
        assert_eq!(
            fp.get(&id),
            Some(&(Version::new(0, 1, 0), Version::new(0, 1, 1)))
        );
    }

    #[test]
    fn knope_dry_run_accepts_version_assignment() {
        let ws = cargo_ws("core", "0.1.0");
        let text = "Would add the following to Cargo.toml: version = 0.1.1\n";
        let fp = parse_knope_dry_run(text, &ws).unwrap();
        let id = PackageId::new(Ecosystem::Cargo, "core");
        assert_eq!(
            fp.get(&id),
            Some(&(Version::new(0, 1, 0), Version::new(0, 1, 1)))
        );
    }

    #[test]
    fn knope_path_does_not_suffix_match_sibling_names() {
        let core = Package::new(
            PackageId::new(Ecosystem::Cargo, "core"),
            Version::new(0, 1, 0),
            ResolvesDependenciesAt::Install,
            true,
            vec![],
        )
        .with_manifest_dir("core");
        let notcore = Package::new(
            PackageId::new(Ecosystem::Cargo, "notcore"),
            Version::new(0, 2, 0),
            ResolvesDependenciesAt::Install,
            true,
            vec![],
        )
        .with_manifest_dir("notcore");
        let ws = Workspace::new(vec![core, notcore]).unwrap();
        let text = "Would add the following to notcore/Cargo.toml: 0.2.1\n";
        let fp = parse_knope_dry_run(text, &ws).unwrap();
        assert_eq!(fp.len(), 1);
        assert!(fp.contains_key(&PackageId::new(Ecosystem::Cargo, "notcore")));
        assert!(!fp.contains_key(&PackageId::new(Ecosystem::Cargo, "core")));
    }

    #[test]
    fn knope_bare_manifest_rejects_when_no_root_package() {
        let left = Package::new(
            PackageId::new(Ecosystem::Cargo, "app"),
            Version::new(0, 1, 0),
            ResolvesDependenciesAt::Install,
            true,
            vec![],
        )
        .with_manifest_dir("app");
        let right = Package::new(
            PackageId::new(Ecosystem::Cargo, "aaa"),
            Version::new(0, 1, 0),
            ResolvesDependenciesAt::Install,
            true,
            vec![],
        )
        .with_manifest_dir("aaa");
        let ws = Workspace::new(vec![left, right]).unwrap();
        let text = "Would add the following to Cargo.toml: 0.1.1\n";
        let err = parse_knope_dry_run(text, &ws).unwrap_err();
        assert!(err.contains("Cargo.toml"), "{err}");
    }

    #[test]
    fn primary_prefers_knope() {
        assert_eq!(
            primary_plan_tool(true, true, true),
            Some(ReleaseTool::Knope)
        );
        assert_eq!(
            primary_plan_tool(false, true, true),
            Some(ReleaseTool::Bumpy)
        );
        assert_eq!(
            primary_plan_tool(false, false, true),
            Some(ReleaseTool::Changesets)
        );
        assert_eq!(primary_plan_tool(false, false, false), None);
    }
}