oakum 0.3.2

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
//! `oakum add`: write one bump file (ADR-0023 / specs/bump-files.md).

use std::io::{self, IsTerminal};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use clap::{Args, ValueEnum};

use oakum::changeset::{
    default_stem, parse_packages_list, resolve_package_name, skipped_instruction_name, slugify,
    write, KnopePresence, PackageSpec, PackagesError, UnknownReason, WriteError,
};
use oakum::discover::{discover_cargo, discover_pnpm};
use oakum::plan::{BumpLevel, Package, Workspace};

use super::config::{enforce_tool_version, load_config, require_config};
use super::fs::{repo_path_display, resolve_capability_path, write_file_exclusive};
use super::init::ensure_changeset_dir;
use super::repository::{self, Repository};
use super::CliError;
use super::{ask, deliver_out, say_err};

#[derive(Debug, Args)]
pub(super) struct AddArgs {
    /// Comma-separated `name:level` pairs (`core:minor,utils:patch`).
    #[arg(long, value_name = "LIST", allow_hyphen_values = true)]
    packages: Option<String>,

    /// Changelog note body.
    #[arg(long, default_value = "")]
    message: String,

    /// Keep a Changelog section for the note; the level picks one otherwise.
    #[arg(
        long,
        value_enum,
        value_name = "SECTION",
        requires = "message",
        conflicts_with = "interactive"
    )]
    section: Option<Section>,

    /// Filename stem (slugified). Defaults to a generated name.
    #[arg(long, value_name = "SLUG")]
    name: Option<String>,

    /// Guided prompts. Exits non-zero when stdin is not a terminal.
    #[arg(long, conflicts_with_all = ["packages", "empty", "none"])]
    interactive: bool,

    /// Write empty frontmatter (intentionally releaseless; ADR-0028).
    #[arg(long, conflicts_with_all = ["packages", "none", "interactive"])]
    empty: bool,

    /// Write `name: none` coverage entries (ADR-0028). Requires `--packages`.
    #[arg(long, conflicts_with_all = ["empty", "interactive"])]
    none: bool,
}

/// Written as the note's opening `### <heading>` line, which `version` reads
/// and drops.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum Section {
    Added,
    Changed,
    Deprecated,
    Removed,
    Fixed,
    Security,
}

impl Section {
    const fn heading(self) -> &'static str {
        match self {
            Self::Added => "Added",
            Self::Changed => "Changed",
            Self::Deprecated => "Deprecated",
            Self::Removed => "Removed",
            Self::Fixed => "Fixed",
            Self::Security => "Security",
        }
    }
}

fn sectioned(message: &str, section: Option<Section>) -> String {
    match section {
        Some(section) if !message.is_empty() => {
            format!(
                "### {}\n\n{}",
                section.heading(),
                message.trim_start_matches('\n')
            )
        }
        _ => message.to_owned(),
    }
}

pub(super) fn run(args: AddArgs) -> Result<(), Box<dyn std::error::Error>> {
    if args.interactive {
        if !io::stdin().is_terminal() {
            return Err(Box::new(CliError::new(
                "`--interactive` needs a terminal; use `--packages <list>` (and optionally `--message` / `--name`) instead",
            )));
        }
        return run_interactive(args.message, args.name);
    }

    if args.section.is_some() && args.message.is_empty() {
        return Err(Box::new(CliError::new(
            "`--section` needs a non-empty `--message` to put under the heading",
        )));
    }

    if args.empty {
        if args.packages.is_some() {
            return Err(Box::new(CliError::new(
                "`--empty` cannot be combined with `--packages`",
            )));
        }
        return write_bump_file(
            &[],
            &sectioned(&args.message, args.section),
            args.name.as_deref(),
        );
    }

    let Some(packages_text) = args.packages.as_deref() else {
        return Err(Box::new(CliError::new(if args.none {
            "`--none` needs `--packages` with `name:none` pairs"
        } else {
            "`oakum add` needs `--packages <list>`, `--empty`, `--none`, or `--interactive`"
        })));
    };

    let specs = parse_packages_list(packages_text).map_err(|err| packages_cli_error(&err))?;
    if args.none {
        for spec in &specs {
            if spec.level() != BumpLevel::None {
                return Err(Box::new(CliError::new(format!(
                    "`--none` requires every `--packages` entry to use level `none` (got `{}:{}`)",
                    spec.name(),
                    spec.level()
                ))));
            }
        }
    }

    write_bump_file(
        &specs,
        &sectioned(&args.message, args.section),
        args.name.as_deref(),
    )
}

/// ADR-0007: the config must exist and match the binary before anything is
/// written.
fn gated_workspace() -> Result<(Repository, Workspace), Box<dyn std::error::Error>> {
    let repo = repository::discover()?;
    let config = load_config(&repo)?;
    require_config(&config)?;
    enforce_tool_version(&config)?;
    let workspace = discover_workspace(&repo)?;
    Ok((repo, workspace))
}

fn run_interactive(
    message_flag: String,
    name_flag: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let (repo, workspace) = gated_workspace()?;
    let package_names = package_names_sorted(&workspace);

    say_err("Packages in this workspace:");
    for name in &package_names {
        say_err(&format!("  {name}"));
    }
    ask("Packages as name:level (comma-separated): ")?;
    let packages_line = read_line()?;
    let specs = parse_packages_list(&packages_line).map_err(|err| packages_cli_error(&err))?;
    validate_specs(&specs, &workspace)?;

    let message = if message_flag.is_empty() {
        ask("Summary (changelog note): ")?;
        read_line()?
    } else {
        message_flag
    };

    let name = if let Some(stem) = name_flag {
        Some(stem)
    } else {
        ask("Filename stem (empty to generate): ")?;
        let line = read_line()?;
        if line.is_empty() {
            None
        } else {
            Some(line)
        }
    };

    write_bump_file_in(&repo, &workspace, &specs, &message, name.as_deref())
}

fn write_bump_file(
    specs: &[PackageSpec],
    message: &str,
    name: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let (repo, workspace) = gated_workspace()?;
    write_bump_file_in(&repo, &workspace, specs, message, name)
}

pub(super) fn write_bump_file_in(
    repo: &Repository,
    workspace: &Workspace,
    specs: &[PackageSpec],
    message: &str,
    name: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    if !specs.is_empty() {
        validate_specs(specs, workspace)?;
    }

    let knope = knope_presence(repo)?;
    let entries: Vec<(String, BumpLevel)> = specs
        .iter()
        .map(|spec| (String::from(spec.name()), spec.level()))
        .collect();
    let body = bump_file_body(&entries, message, knope).map_err(|err| write_cli_error(&err))?;

    let stem = match name {
        Some(raw) => slugify(raw),
        None => default_stem(unique_seed()),
    };
    let file_name = format!("{stem}.md");
    if skipped_instruction_name(&file_name) {
        return Err(Box::new(CliError::new(format!(
            "refusing to write `{file_name}`: that name is reserved for instruction files in `.changeset/`"
        ))));
    }

    ensure_changeset_dir(repo.dir())?;
    let relative =
        resolve_capability_path(repo.dir(), repo.path(), Path::new(".changeset"))?.join(&file_name);
    write_file_exclusive(repo.dir(), &relative, &body)
        .map_err(|err| exclusive_create_error(&err, &relative))?;
    let path = repo_path_display(&relative);
    deliver_out(&path)
        .map_err(|err| CliError::undelivered(format!("wrote `{path}`, but its path"), &err))?;
    Ok(())
}

/// The enveloped body for `add` and `generate`, preview and file alike, so
/// the dry-run cannot drift from the write. `migrate` rewrites parsed notes
/// with `write` directly.
pub(super) fn bump_file_body(
    entries: &[(String, BumpLevel)],
    message: &str,
    knope: KnopePresence,
) -> Result<String, WriteError> {
    write(entries, &enveloped(message), knope)
}

/// ADR-0031's mechanical envelope: a blank line after the closing `---` and a
/// trailing newline. The message itself stays verbatim; an empty message gets
/// no envelope so `--empty` still writes a bare frontmatter block.
pub(super) fn enveloped(message: &str) -> String {
    if message.is_empty() {
        return String::new();
    }
    let lead = if message.starts_with('\n') { "" } else { "\n" };
    let tail = if message.ends_with('\n') { "" } else { "\n" };
    format!("{lead}{message}{tail}")
}

fn validate_specs(
    specs: &[PackageSpec],
    workspace: &Workspace,
) -> Result<(), Box<dyn std::error::Error>> {
    for spec in specs {
        match resolve_package_name(spec.name(), workspace) {
            Ok(_) => {}
            Err(UnknownReason::Missing) => {
                return Err(Box::new(CliError::new(format!(
                    "package `{}` is not in the workspace",
                    spec.name()
                ))));
            }
            Err(UnknownReason::Ambiguous) => {
                return Err(Box::new(CliError::new(format!(
                    "package `{}` matches more than one workspace package",
                    spec.name()
                ))));
            }
        }
    }
    Ok(())
}

pub(super) const NOTHING_TO_DISCOVER: &str =
    "no Cargo.toml or package.json found; nothing to discover";

/// Empty discovery is a typed miss (`Ok(None)`), not a string-matched error.
/// Hard failures (adapter errors, invalid workspace) remain `Err`.
pub(super) fn try_discover_workspace(
    repo: &Repository,
) -> Result<Option<Workspace>, Box<dyn std::error::Error>> {
    let path = repo.ambient_path()?;
    let mut packages = Vec::new();
    let mut errors = Vec::new();
    let cwd = std::env::current_dir()?;

    let mut cargo_workspace_root = None;
    let mut catalog_file = None;

    let cargo_dir = find_manifest_dir(&cwd, path, "Cargo.toml");
    if cargo_dir.is_some() || path.join("Cargo.toml").is_file() {
        let path = repo.ambient_path()?;
        let start = cargo_dir.as_deref().unwrap_or(path);
        match discover_cargo(start, path) {
            Ok(ws) => {
                cargo_workspace_root = ws.cargo_workspace_root().map(str::to_owned);
                packages.extend(ws.packages().cloned());
            }
            Err(err) => errors.push(format!("cargo: {err}")),
        }
    }

    let pnpm_marker = path.join("pnpm-workspace.yaml").is_file()
        || path.join("package.json").is_file()
        || find_manifest_dir(&cwd, path, "package.json").is_some();
    if pnpm_marker {
        let path = repo.ambient_path()?;
        let start = find_manifest_dir(&cwd, path, "package.json")
            .or_else(|| find_manifest_dir(&cwd, path, "pnpm-workspace.yaml"))
            .unwrap_or_else(|| path.to_path_buf());
        match discover_pnpm(&start, path) {
            Ok(ws) => {
                catalog_file = ws.catalog_file().map(str::to_owned);
                packages.extend(ws.packages().cloned());
            }
            Err(err) => errors.push(format!("pnpm: {err}")),
        }
    }

    if !errors.is_empty() {
        return Err(Box::new(CliError::new(format!(
            "workspace discovery failed ({})",
            errors.join("; ")
        ))));
    }

    let _ = repo.ambient_path()?;
    if packages.is_empty() {
        return Ok(None);
    }
    Ok(Some(workspace_from_discovered(
        packages,
        cargo_workspace_root,
        catalog_file,
    )?))
}

pub(super) fn discover_workspace(
    repo: &Repository,
) -> Result<Workspace, Box<dyn std::error::Error>> {
    match try_discover_workspace(repo)? {
        Some(workspace) => Ok(workspace),
        None => Err(Box::new(CliError::new(NOTHING_TO_DISCOVER))),
    }
}

fn workspace_from_discovered(
    packages: Vec<Package>,
    cargo_workspace_root: Option<String>,
    catalog_file: Option<String>,
) -> Result<Workspace, Box<dyn std::error::Error>> {
    let mut workspace = Workspace::new(packages).map_err(|err| -> Box<dyn std::error::Error> {
        Box::new(CliError::new(err.to_string()))
    })?;
    if let Some(dir) = cargo_workspace_root {
        workspace = workspace.with_cargo_workspace_root(dir);
    }
    if let Some(path) = catalog_file {
        workspace = workspace.with_catalog_file(path);
    }
    Ok(workspace)
}

pub(super) fn find_manifest_dir(start: &Path, stop: &Path, file_name: &str) -> Option<PathBuf> {
    let mut dir = std::fs::canonicalize(start).unwrap_or_else(|_| start.to_path_buf());
    let stop = std::fs::canonicalize(stop).unwrap_or_else(|_| stop.to_path_buf());
    loop {
        if dir.join(file_name).is_file() {
            return Some(dir);
        }
        if same_walk_stop(&dir, &stop) || !dir.pop() {
            return None;
        }
    }
}

/// `Path` equality is structural: `C:\repo` and `\\?\C:\repo` are not equal,
/// so a walk that stops only on `==` continues into an ancestor cargo
/// workspace. Canonicalize when the path exists; also treat Windows
/// drive/UNC spellings as one identity.
fn same_walk_stop(dir: &Path, stop: &Path) -> bool {
    if dir == stop {
        return true;
    }
    #[cfg(any(windows, test))]
    {
        let a = super::fs::normalized_windows_path(dir);
        let b = super::fs::normalized_windows_path(stop);
        if windows_abs(&a) && a.eq_ignore_ascii_case(&b) {
            return true;
        }
    }
    false
}

#[cfg(any(windows, test))]
fn windows_abs(path: &str) -> bool {
    let bytes = path.as_bytes();
    (bytes.len() >= 3
        && bytes[0].is_ascii_alphabetic()
        && bytes[1] == b':'
        && (bytes[2] == b'\\' || bytes[2] == b'/'))
        || path.starts_with(r"\\")
}

pub(super) fn knope_presence(
    repo: &Repository,
) -> Result<KnopePresence, Box<dyn std::error::Error>> {
    match repo.dir().metadata("knope.toml") {
        Ok(meta) if meta.is_file() => Ok(KnopePresence::Present),
        Ok(_) => Ok(KnopePresence::Absent),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(KnopePresence::Absent),
        Err(err) => Err(Box::new(CliError::new(format!(
            "failed to inspect `knope.toml`: {err}"
        )))),
    }
}

fn exclusive_create_error(err: &io::Error, relative: &Path) -> Box<dyn std::error::Error> {
    if err.kind() == io::ErrorKind::AlreadyExists {
        Box::new(CliError::new(format!(
            "refusing to overwrite existing bump file `{}`",
            repo_path_display(relative)
        )))
    } else {
        Box::new(CliError::new(err.to_string()))
    }
}

fn package_names_sorted(workspace: &Workspace) -> Vec<String> {
    let mut names: Vec<String> = workspace
        .packages()
        .map(|pkg| pkg.id().name.clone())
        .collect();
    names.sort();
    names.dedup();
    names
}

fn unique_seed() -> u64 {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(d) => d
            .as_secs()
            .wrapping_mul(1_000_000_000)
            .wrapping_add(u64::from(d.subsec_nanos())),
        Err(_) => 0,
    }
}

fn read_line() -> Result<String, Box<dyn std::error::Error>> {
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    Ok(line.trim_end_matches(['\r', '\n']).to_string())
}

fn packages_cli_error(err: &PackagesError) -> Box<dyn std::error::Error> {
    Box::new(CliError::new(err.to_string()))
}

fn write_cli_error(err: &WriteError) -> Box<dyn std::error::Error> {
    Box::new(CliError::new(err.to_string()))
}

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

    use super::{enveloped, workspace_from_discovered};

    fn pkg(ecosystem: Ecosystem, name: &str) -> Package {
        Package::new(
            PackageId::new(ecosystem, name),
            Version::new(0, 1, 0),
            ResolvesDependenciesAt::Install,
            true,
            vec![],
        )
    }

    #[test]
    fn cargo_and_pnpm_merge_keeps_both_discovery_paths() {
        let workspace = workspace_from_discovered(
            vec![pkg(Ecosystem::Cargo, "core"), pkg(Ecosystem::Npm, "app")],
            Some("rust".into()),
            Some("js/pnpm-workspace.yaml".into()),
        )
        .expect("merge");
        assert_eq!(workspace.cargo_workspace_root(), Some("rust"));
        assert_eq!(workspace.catalog_file(), Some("js/pnpm-workspace.yaml"));
    }

    #[test]
    fn merge_without_paths_leaves_both_none() {
        let workspace = workspace_from_discovered(vec![pkg(Ecosystem::Cargo, "core")], None, None)
            .expect("merge");
        assert_eq!(workspace.cargo_workspace_root(), None);
        assert_eq!(workspace.catalog_file(), None);
    }

    #[test]
    fn verbatim_and_plain_windows_paths_are_the_same_walk_stop() {
        use std::path::Path;
        assert!(super::same_walk_stop(
            Path::new(r"C:\a\oakum\oakum\target\tmp\pin-npm"),
            Path::new(r"\\?\C:\a\oakum\oakum\target\tmp\pin-npm"),
        ));
        assert!(super::same_walk_stop(
            Path::new(r"C:\Repo"),
            Path::new(r"\\?\c:\repo"),
        ));
        assert!(!super::same_walk_stop(
            Path::new(r"C:\a\oakum\oakum"),
            Path::new(r"\\?\C:\a\oakum\oakum\target\tmp\pin-npm"),
        ));
    }

    #[test]
    fn find_manifest_dir_does_not_walk_past_a_verbatim_stop() {
        use std::path::Path;
        let start = Path::new(r"C:\a\oakum\oakum\target\tmp\pin-npm");
        let stop = Path::new(r"\\?\C:\a\oakum\oakum\target\tmp\pin-npm");
        assert_eq!(super::find_manifest_dir(start, stop, "Cargo.toml"), None);
    }

    #[test]
    fn exclusive_create_maps_already_exists_to_overwrite() {
        use std::io;
        use std::path::Path;

        let already = io::Error::new(
            io::ErrorKind::AlreadyExists,
            "failed to create `exists.md`: File exists",
        );
        let err = super::exclusive_create_error(&already, Path::new(".changeset/exists.md"));
        assert!(err.to_string().contains("overwrite"), "{err}");
    }

    #[test]
    fn exclusive_create_does_not_treat_permission_denied_as_overwrite() {
        use std::io;
        use std::path::Path;

        let denied = io::Error::new(
            io::ErrorKind::PermissionDenied,
            "failed to create `exists.md`: Permission denied (os error 13)",
        );
        let err = super::exclusive_create_error(&denied, Path::new(".changeset/exists.md"));
        let message = err.to_string();
        assert!(!message.contains("overwrite"), "{message}");
        assert!(message.contains("Permission denied"), "{message}");
    }

    #[test]
    fn sectioned_prepends_the_heading_line_only_with_a_message() {
        assert_eq!(
            super::sectioned("note", Some(super::Section::Changed)),
            "### Changed\n\nnote"
        );
        assert_eq!(
            super::sectioned("\nnote\n", Some(super::Section::Security)),
            "### Security\n\nnote\n"
        );
        assert_eq!(super::sectioned("note", None), "note");
        assert_eq!(super::sectioned("", Some(super::Section::Fixed)), "");
    }

    #[test]
    fn enveloped_adds_blank_line_and_trailing_newline() {
        assert_eq!(enveloped(""), "");
        assert_eq!(enveloped("note"), "\nnote\n");
        assert_eq!(enveloped("note\n"), "\nnote\n");
        assert_eq!(enveloped("\nnote\n"), "\nnote\n");
        assert_eq!(enveloped("two\nlines"), "\ntwo\nlines\n");
    }
}