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

use std::io::{self, IsTerminal};
use std::path::Path;
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::plan::{BumpLevel, Workspace};

use super::changelog::heading_list;
use super::config::{load_config, require_config, LoadedConfig, UNMANAGED_FIX};
use super::fs::{repo_path_display, resolve_capability_path, write_file_exclusive};
use super::init::ensure_changeset_dir;
use super::install_pin::{self, PinPolicy};
use super::repository::{self, Repository};
use super::workspace::discover_validated;
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: releases nothing, and covers every changed package.
    #[arg(long, conflicts_with_all = ["packages", "none", "interactive"])]
    empty: bool,

    /// Write `name: none` entries, which cover a changed package without releasing it. 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);
    }

    // Trimmed first: spaces render nothing, so a message of them is the empty
    // message wearing a disguise. Without this, `--section` refuses `""` and
    // accepts `"   "`, and the second writes a note that reaches no changelog.
    let args = AddArgs {
        message: String::from(args.message.trim()),
        ..args
    };

    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(),
    )
}

/// The config must exist and the install pin must name this binary before
/// anything is written (ADR-0038).
fn gated_workspace() -> Result<(Repository, Workspace, LoadedConfig), Box<dyn std::error::Error>> {
    let repo = repository::discover()?;
    let config = load_config(&repo)?;
    require_config(&config)?;
    install_pin::gate(&repo, PinPolicy::Writer)?;
    let workspace = discover_validated(&repo, &config)?;
    Ok((repo, workspace, config))
}

fn run_interactive(
    message_flag: String,
    name_flag: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let (repo, workspace, config) = 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, &config)?;

    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,
        &config,
        &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, config) = gated_workspace()?;
    write_bump_file_in(&repo, &workspace, &config, specs, message, name)
}

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

    let knope = knope_presence(repo)?;
    let entries: Vec<(String, BumpLevel)> = specs
        .iter()
        .map(|spec| (String::from(spec.name()), spec.level()))
        .collect();
    // Caught where the note is written rather than at `version`, which is the
    // cheaper place: the author is still here, and the alternative is a
    // release that silently omits what they wrote.
    if let Some(level) = entries.iter().map(|(_, level)| *level).max() {
        let dropped = super::changelog::dropped_headings(message, level);
        if !dropped.is_empty() {
            return Err(Box::new(CliError::new(format!(
                "the note has a heading with nothing under it ({}), so that section would reach no changelog: put text under the heading or remove it, or use `--none` for a change that is deliberately releaseless",
                heading_list(&dropped)
            ))));
        }
    }
    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))?;
    let releases = entries.iter().any(|(_, level)| *level != BumpLevel::None);
    if releases && message.trim().is_empty() {
        say_err(&format!(
            "`{path}` has no note, so its changelog entry will be empty; write one below its frontmatter"
        ));
    }
    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,
    config: &LoadedConfig,
) -> Result<(), Box<dyn std::error::Error>> {
    for spec in specs {
        match resolve_package_name(spec.name(), workspace) {
            Ok(id) => {
                if config.refuses_intent(workspace, &id, spec.level()) {
                    return Err(Box::new(CliError::new(format!(
                        "`{}` is not version-managed, so every later step would refuse a bump file releasing it; {UNMANAGED_FIX}",
                        spec.name()
                    ))));
                }
            }
            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) 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 super::enveloped;

    #[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");
    }
}