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
//! `oakum init`: write oakum's three files and print everything else (ADR-0003 / ADR-0023).
//!
//! Install-pin gate first. Detect foreign tools before any write. `--interactive`
//! is opt-in over `--versioning` and never auto-detects a terminal.

use std::io::{self, IsTerminal};
use std::path::Path;

use cap_std::fs::Dir;
use clap::{Args, ValueEnum};
use oakum::changeset::instruction_occupants;
use oakum::config;
use oakum::discover::{discover_cargo, discover_pnpm, DiscoverError};
use oakum::plan::Versioning;
use semver::Version;

use super::config::{read_config_source, LoadedConfig, ALL_PRIVATE_GUIDANCE};
use super::detect_tools;
use super::fs::report_stray_staging;
use super::install_pin::{self, PinPolicy};
use super::owned_files::{write_owned_files, ConfigSettings, OwnedPlan, PrivatePackages, Records};
use super::repository;
use super::workflow::{
    next_step, npm_workspace, workflow_text, InstallFacts, TokenArgs, WorkflowPins,
};
use super::{ask, say_err, say_out};
use super::{binary_version, CliError};

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub(super) enum VersioningArg {
    #[value(name = "zero-major")]
    ZeroMajor,
    Semver,
}

impl VersioningArg {
    pub(super) fn to_versioning(self) -> Versioning {
        match self {
            Self::ZeroMajor => Versioning::ZeroMajor,
            Self::Semver => Versioning::Semver,
        }
    }
}

#[derive(Debug, Args)]
pub(super) struct InitArgs {
    /// Version policy written into `_config.toml`. Default `zero-major`.
    #[arg(long, value_enum)]
    versioning: Option<VersioningArg>,
    /// Read release intent from bump files. Default `true`.
    #[arg(
        long,
        num_args = 0..=1,
        default_missing_value = "true",
        value_parser = clap::builder::BoolishValueParser::new()
    )]
    change_files: Option<bool>,
    /// Read release intent from conventional commits. Default `true`.
    #[arg(
        long,
        num_args = 0..=1,
        default_missing_value = "true",
        value_parser = clap::builder::BoolishValueParser::new()
    )]
    conventional_commits: Option<bool>,
    /// Guided prompts. Exits non-zero when stdin is not a terminal.
    #[arg(long)]
    interactive: bool,
    #[command(flatten)]
    token: TokenArgs,
}

struct ResolvedInit {
    change_files: bool,
    conventional_commits: bool,
    versioning: VersioningArg,
}

pub(super) fn run(args: &InitArgs) -> Result<(), Box<dyn std::error::Error>> {
    let repo = repository::discover()?;
    report_stray_staging(repo.dir())?;
    let owed = install_pin::gate(&repo, PinPolicy::Adopt)?;
    if let Some(source) = read_config_source(&repo)? {
        already_initialized(&repo, &source, args)?;
        args.token.refuse_without_workflow("init")?;
        refuse_interactive_without_tty(args.interactive)?;
        say_out("already initialized");
        say_out(&next_step(&workflow_step("")));
        if let Some(owed) = &owed {
            say_out(&next_step(&owed.step(None)));
            if let Some(refusal) = owed.refusal() {
                return Err(Box::new(refusal));
            }
        }
        return Ok(());
    }
    refuse_interactive_without_tty(args.interactive)?;

    let report = detect_tools::scan(repo.dir())?;
    detect_tools::refuse_on_detection_errors(&report)?;
    if !report.detections.is_empty() {
        detect_tools::report_detections(&report.detections);
        return Err(Box::new(CliError::new("run oakum migrate")));
    }

    report_instruction_files(repo.dir())?;
    let packages = refuse_stray_workspace(&repo)?;
    let install = InstallFacts::read(repo.dir(), repo.ambient_path()?, packages.npm)?;

    let settings = resolve_init_settings(args)?;

    let binary = binary_version()?;
    let pins = WorkflowPins::lookup(install, args.token.token())?;
    ensure_changeset_dir(repo.dir())?;
    let plan = OwnedPlan::probe(repo.dir())?;
    let mut records = Records::default();
    let created = write_owned_files(
        repo.dir(),
        plan,
        ConfigSettings {
            change_files: settings.change_files,
            conventional_commits: settings.conventional_commits,
            versioning: settings.versioning.to_versioning(),
            private_packages: PrivatePackages::default(),
            tag_format: None,
            commit_message: None,
        },
        &mut records,
    )
    .map_err(|err| records.abandon(err))?;
    let workflow = print_workflow_and_footer(&binary, &pins, &created.written, &mut records);
    match packages.total {
        0 => say_out("no packages found"),
        n => say_out(&format!("{n} package(s) found")),
    }
    records.deliver(
        "the workflow step",
        &next_step(&workflow_step(&args.token.flags())),
    );
    for step in pins.owed_steps(owed.as_ref(), &binary, &workflow) {
        records.deliver("the pin step", &next_step(&step));
    }
    // `check` refuses this state. Saying so here, where the config was just
    // written, beats letting the next command be the one to mention it.
    if packages.all_private() {
        say_err(ALL_PRIVATE_GUIDANCE);
    }
    let usage = usage_steps(settings.change_files).map(next_step).join("\n");
    records.deliver("the next steps", &usage);
    let delivered = records.finish();
    match owed.as_ref().and_then(install_pin::Owed::refusal) {
        Some(pin) => Err(Box::new(match delivered {
            Ok(()) => pin.recast(format!("initialized files were kept; {}", pin.detail())),
            Err(undelivered) => pin.recast(format!(
                "initialized files were kept; {}; and {}",
                pin.detail(),
                undelivered.detail()
            )),
        })),
        None => Ok(delivered?),
    }
}

fn already_initialized(
    repo: &super::repository::Repository,
    source: &super::config::ConfigSource,
    args: &InitArgs,
) -> Result<(), Box<dyn std::error::Error>> {
    let parsed = config::parse(source.text()).map_err(|err| {
        CliError::new(format!(
            "`.changeset/_config.toml` is not a valid oakum config: {err}"
        ))
    })?;
    let loaded = LoadedConfig::from_parsed(repo, parsed, source.text())?;
    if let Some(flag) = args.versioning {
        let wanted = flag.to_versioning();
        let have = loaded.versioning();
        if wanted != have {
            return Err(Box::new(CliError::new(format!(
                "`--versioning` is `{wanted}` but `.changeset/_config.toml` has `versioning = \"{have}\"`; change `versioning` in `.changeset/_config.toml` to `{wanted}`"
            ))));
        }
    }
    if let Some(wanted) = args.change_files {
        let have = loaded.change_files();
        if wanted != have {
            return Err(Box::new(CliError::new(format!(
                "`--change-files` is `{wanted}` but `.changeset/_config.toml` has `change-files = {have}`; change `change-files` in `.changeset/_config.toml` to `{wanted}`"
            ))));
        }
    }
    if let Some(wanted) = args.conventional_commits {
        let have = loaded.conventional_commits();
        if wanted != have {
            return Err(Box::new(CliError::new(format!(
                "`--conventional-commits` is `{wanted}` but `.changeset/_config.toml` has `conventional-commits = {have}`; change `conventional-commits` in `.changeset/_config.toml` to `{wanted}`"
            ))));
        }
    }
    Ok(())
}

fn refuse_interactive_without_tty(interactive: bool) -> Result<(), Box<dyn std::error::Error>> {
    if interactive && !io::stdin().is_terminal() {
        return Err(Box::new(CliError::new(
            "`--interactive` needs a terminal; use `--versioning <zero-major|semver>`, \
             `--change-files <true|false>`, and `--conventional-commits <true|false>` instead",
        )));
    }
    Ok(())
}

fn resolve_init_settings(args: &InitArgs) -> Result<ResolvedInit, Box<dyn std::error::Error>> {
    let change_files = if args.interactive && args.change_files.is_none() {
        prompt_yes_no("change-files", true)?
    } else {
        args.change_files.unwrap_or(true)
    };
    let conventional_commits = if args.interactive && args.conventional_commits.is_none() {
        prompt_yes_no("conventional-commits", true)?
    } else {
        args.conventional_commits.unwrap_or(true)
    };
    refuse_both_intent_disabled(change_files, conventional_commits)?;
    let versioning = if args.interactive && args.versioning.is_none() {
        prompt_versioning()?
    } else {
        args.versioning.unwrap_or(VersioningArg::ZeroMajor)
    };
    Ok(ResolvedInit {
        change_files,
        conventional_commits,
        versioning,
    })
}

fn refuse_both_intent_disabled(
    change_files: bool,
    conventional_commits: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    if change_files || conventional_commits {
        return Ok(());
    }
    Err(Box::new(CliError::new(
        "both `change-files` and `conventional-commits` are disabled; enable one so the plan has intent to read (ADR-0019 / ADR-0029)",
    )))
}

/// `a`, `a and b`, or `a, b, and c`; empty in, empty out (every caller lists
/// at least one path).
pub(super) fn list_paths(paths: &[&str]) -> String {
    match paths {
        [] => String::new(),
        [one] => (*one).to_owned(),
        [first, second] => format!("{first} and {second}"),
        [init @ .., last] => format!("{}, and {last}", init.join(", ")),
    }
}

/// The footer line naming what to delete, with every path quoted.
pub(super) fn uninstall_line(owned: &[&str]) -> String {
    let quoted: Vec<String> = owned.iter().map(|path| format!("`{path}`")).collect();
    let quoted: Vec<&str> = quoted.iter().map(String::as_str).collect();
    format!("remove {} to uninstall", list_paths(&quoted))
}

/// The workflow is written nowhere else, so it is the deliverable, recorded
/// beside the files that were written; the caller's [`Records::finish`] says
/// whether it arrived.
pub(super) fn print_workflow_and_footer(
    binary: &Version,
    pins: &WorkflowPins,
    owned: &[&str],
    records: &mut Records,
) -> String {
    let workflow = workflow_text(binary, pins);
    records.deliver(
        "the workflow to paste",
        &format!(
            "workflow (paste into `.github/workflows/`; oakum does not write it):\n{workflow}"
        ),
    );
    records.deliver("the uninstall line", &uninstall_line(owned));
    workflow
}

fn report_instruction_files(dir: &Dir) -> Result<(), Box<dyn std::error::Error>> {
    let names = changeset_file_names(dir)?;
    for occupant in instruction_occupants(names.iter().map(String::as_str)) {
        if let Some(message) = occupant.init_message() {
            say_out(&message);
        }
    }
    Ok(())
}

pub(super) fn changeset_file_names(dir: &Dir) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let entries = match dir.read_dir(".changeset") {
        Ok(entries) => entries,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(err) => {
            return Err(Box::new(CliError::new(format!(
                "failed to read `.changeset/`: {err}"
            ))));
        }
    };
    let mut names = Vec::new();
    for entry in entries {
        let entry =
            entry.map_err(|err| CliError::new(format!("failed to read `.changeset/`: {err}")))?;
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            return Err(Box::new(CliError::new(
                "a path under `.changeset/` is not valid UTF-8",
            )));
        };
        if name == "." || name == ".." {
            continue;
        }
        let meta = entry.metadata().map_err(|err| {
            CliError::new(format!("failed to inspect `.changeset/{name}`: {err}"))
        })?;
        if meta.is_file() {
            names.push(name.to_string());
        }
    }
    // `read_dir` yields filesystem order, so an unsorted listing prints a
    // different plan on a different machine for the same repository.
    names.sort();
    Ok(names)
}

pub(super) fn ensure_changeset_dir(dir: &Dir) -> Result<(), Box<dyn std::error::Error>> {
    match dir.create_dir(".changeset") {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
            let meta = dir
                .metadata(".changeset")
                .map_err(|err| CliError::new(format!("failed to inspect `.changeset`: {err}")))?;
            if meta.is_dir() {
                Ok(())
            } else {
                Err(Box::new(CliError::new(
                    "`.changeset` exists and is not a directory",
                )))
            }
        }
        Err(err) => Err(Box::new(CliError::new(format!(
            "failed to create `.changeset/`: {err}"
        )))),
    }
}

fn refuse_stray_workspace(
    repo: &repository::Repository,
) -> Result<PackageTally, Box<dyn std::error::Error>> {
    let path = repo.ambient_path()?;
    let count = package_count(path)?;
    let _ = repo.ambient_path()?;
    Ok(count)
}

/// How many packages discovery found, and how many a registry would accept.
/// `init` writes `private-packages` off, so a workspace with none of the second
/// is one every later command reads as managing nothing.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
struct PackageTally {
    total: usize,
    publishable: usize,
    /// Whether pnpm discovery ran, which picks the workflow's install path.
    npm: bool,
}

impl PackageTally {
    fn add(self, other: Self) -> Self {
        Self {
            total: self.total + other.total,
            publishable: self.publishable + other.publishable,
            npm: self.npm || other.npm,
        }
    }

    const fn all_private(self) -> bool {
        self.total > 0 && self.publishable == 0
    }
}

fn package_count(repo: &Path) -> Result<PackageTally, Box<dyn std::error::Error>> {
    let mut tally = PackageTally::default();
    if repo.join("Cargo.toml").is_file() {
        tally = tally.add(workspace_len(discover_cargo(repo, repo))?);
    }
    if npm_workspace(repo) {
        tally = tally.add(workspace_len(discover_pnpm(repo, repo))?);
        tally.npm = true;
    }
    Ok(tally)
}

fn workspace_len(
    result: Result<oakum::plan::Workspace, DiscoverError>,
) -> Result<PackageTally, Box<dyn std::error::Error>> {
    match result {
        Ok(workspace) => Ok(PackageTally {
            total: workspace.packages().count(),
            publishable: workspace.packages().filter(|p| p.publishable()).count(),
            npm: false,
        }),
        Err(err @ DiscoverError::WorkspaceRootOutsideRepository { .. }) => {
            Err(Box::new(CliError::new(format!(
                "refusing to init: {err} (discovery would describe a different repository)"
            ))))
        }
        Err(err) if err.is_unverified() => {
            Err(Box::new(CliError::unverified(format!("unverified: {err}"))))
        }
        Err(err) => Err(Box::new(CliError::new(err.to_string()))),
    }
}

fn prompt_yes_no(name: &str, default: bool) -> Result<bool, Box<dyn std::error::Error>> {
    let default_label = if default { "Y" } else { "y" };
    let alt = if default { "n" } else { "Y" };
    let default_word = if default { "yes" } else { "no" };
    ask(&format!(
        "{name} [{default_label}/{alt}] (default {default_word}): "
    ))?;
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    parse_yes_no(name, line.trim(), default)
        .map_err(|err| Box::new(err) as Box<dyn std::error::Error>)
}

fn parse_yes_no(name: &str, answer: &str, default: bool) -> Result<bool, CliError> {
    match answer {
        "" => Ok(default),
        "y" | "yes" | "Y" | "Yes" | "YES" | "true" => Ok(true),
        "n" | "no" | "N" | "No" | "NO" | "false" => Ok(false),
        other => Err(CliError::new(format!(
            "unknown answer `{other}` for `{name}`; use yes or no"
        ))),
    }
}

fn prompt_versioning() -> Result<VersioningArg, Box<dyn std::error::Error>> {
    ask("versioning [zero-major/semver] (default zero-major): ")?;
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    parse_versioning(line.trim()).map_err(|err| Box::new(err) as Box<dyn std::error::Error>)
}

fn parse_versioning(answer: &str) -> Result<VersioningArg, CliError> {
    match answer {
        "" | "zero-major" => Ok(VersioningArg::ZeroMajor),
        "semver" => Ok(VersioningArg::Semver),
        other => Err(CliError::new(format!(
            "unknown versioning `{other}`; use zero-major or semver"
        ))),
    }
}

/// A fresh repository has no `.github/workflows/`, and a shell empties a
/// redirect's target before the run that may fail, so the save goes through
/// another file.
fn workflow_step(flags: &str) -> String {
    format!(
        "`oakum workflow{flags}` prints the workflow alone and writes nothing, so \
         `mkdir -p .github/workflows && oakum workflow{flags} > oakum.yml.new && \
         mv oakum.yml.new .github/workflows/oakum.yml` saves it"
    )
}

fn usage_steps(change_files: bool) -> [&'static str; 3] {
    let intent = if change_files {
        "run `oakum add` on each branch whose change should release, to write its bump file"
    } else {
        "write commits as conventional commits (`feat:`, `fix:`), which the plan reads as release intent"
    };
    [
        intent,
        "run `oakum status` to see what would release",
        "`versioning`, `change-files`, and `conventional-commits` are in `.changeset/_config.toml`; change them there",
    ]
}

#[cfg(test)]
mod prompts {
    use super::{parse_versioning, parse_yes_no, VersioningArg};

    #[test]
    fn yes_no_defaults_and_variants() {
        assert!(parse_yes_no("change-files", "", true).expect("default yes"));
        assert!(!parse_yes_no("change-files", "", false).expect("default no"));
        assert!(parse_yes_no("change-files", "y", false).expect("y"));
        assert!(!parse_yes_no("change-files", "no", true).expect("no"));
        assert!(parse_yes_no("change-files", "true", false).expect("true"));
        assert!(!parse_yes_no("change-files", "false", true).expect("false"));
    }

    #[test]
    fn yes_no_rejects_unknown() {
        let err = parse_yes_no("change-files", "maybe", true).expect_err("unknown");
        assert!(err.to_string().contains("maybe"));
    }

    #[test]
    fn versioning_defaults_and_variants() {
        assert_eq!(
            parse_versioning("").expect("default"),
            VersioningArg::ZeroMajor
        );
        assert_eq!(
            parse_versioning("semver").expect("semver"),
            VersioningArg::Semver
        );
    }

    #[test]
    fn versioning_rejects_unknown() {
        let err = parse_versioning("calver").expect_err("unknown");
        assert!(err.to_string().contains("calver"));
    }
}

#[cfg(all(test, unix))]
mod identity {
    use std::fs;
    use std::path::Path;

    use crate::cli::repository::discover_from;
    use crate::test_fixture::Fixture;

    use super::refuse_stray_workspace;

    fn git_repo(label: &str) -> Fixture {
        let root = Fixture::new("init", label);
        fs::create_dir(root.join(".git")).expect("git marker");
        root
    }

    fn replace_root(root: &Path) {
        let moved = root.with_file_name("moved");
        fs::rename(root, &moved).expect("rename repository");
        fs::create_dir(root).expect("replacement root");
        fs::create_dir(root.join(".git")).expect("replacement git marker");
    }

    #[test]
    fn refuse_stray_workspace_after_root_replacement_fails_closed() {
        let root = git_repo("stray-replaced");
        fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"original\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .expect("original manifest");
        let repository = discover_from(&root).expect("discover repository");
        replace_root(&root);

        let error = refuse_stray_workspace(&repository)
            .expect_err("empty replacement must not look like no workspace");
        let message = error.to_string();
        assert!(
            message.contains("no longer the directory originally opened"),
            "{message}"
        );
        assert!(!message.contains("nothing to discover"), "{message}");
    }

    #[test]
    fn refuse_stray_workspace_counts_the_original_tree() {
        let root = git_repo("stray-ok");
        fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"original\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
        )
        .expect("manifest");
        fs::create_dir(root.join("src")).expect("src");
        fs::write(root.join("src/lib.rs"), "").expect("lib");
        let repository = discover_from(&root).expect("discover repository");
        let count = refuse_stray_workspace(&repository).expect("count original tree");
        assert_eq!(count.total, 1);
    }
}

#[cfg(test)]
mod wording {
    use super::{list_paths, uninstall_line};

    #[test]
    fn list_paths_joins_like_prose() {
        assert_eq!(list_paths(&[]), "");
        assert_eq!(list_paths(&["a"]), "a");
        assert_eq!(list_paths(&["a", "b"]), "a and b");
        assert_eq!(list_paths(&["a", "b", "c"]), "a, b, and c");
    }

    #[test]
    fn uninstall_line_quotes_every_path() {
        assert_eq!(
            uninstall_line(&[".changeset/_schema.json", ".changeset/_config.toml"]),
            "remove `.changeset/_schema.json` and `.changeset/_config.toml` to uninstall"
        );
    }
}