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
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
//! `oakum version`: write planned manifests, declared extra-files, inherited pins,
//! lockfile rows, changelogs, and (when bumping the Cargo member named `oakum`)
//! `tool-version`, then delete consumed bump files.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::io::{self, Read};
use std::path::{Component, Path, PathBuf};
use std::time::SystemTime;

use cap_std::fs::Dir;
use clap::Args;
use oakum::config::ExtraFileFormat;
use oakum::manifest::{
    cargo_package_version_inherits_workspace, replace_json_at_key, retarget_cargo_lock,
    rewrite_dependencies, set_json_string, set_toml_string, CargoLockBump,
};
use oakum::plan::{aggregate, ChangeSource, Ecosystem, Package, PackageId, Plan, Workspace};
use semver::Version;

use super::changelog::{
    plan_changelog_writes, supplied_note, utc_date, ChangelogPlan, Links, Provenance,
};
use super::config::{enforce_tool_version, load_config, require_config, LoadedConfig};
use super::fs::repo_path_display;
use super::git::Git;
use super::inherited::{cargo_toml_path, plan_inherited_writes};
use super::intent::COMMITS_BUMP_FILE_ID;
use super::release_state::{compose_plan, Discovered};
use super::repository;
use super::template::{load_contained_file, load_template_body};
use super::write_set::{commit_write_set, read_text, PlannedDelete, PlannedWrite, WriteSet};
use super::CliError;

const PACKAGE_JSON: &str = "package.json";
const CARGO_TOML: &str = "Cargo.toml";
const CARGO_LOCK: &str = "Cargo.lock";
const CHANGESET_DIR: &str = ".changeset";

pub(super) struct VersionWritePlan {
    pub repo: repository::Repository,
    pub writes: Vec<PlannedWrite>,
    pub deletes: Vec<PlannedDelete>,
    pub plan: Plan,
    pub tool_version: String,
    pub title: Option<oakum::template::TemplateSource>,
    pub commit_message: Option<oakum::template::TemplateSource>,
}

impl VersionWritePlan {
    pub(super) fn needs_github(&self) -> bool {
        !self.deletes.is_empty()
            || self
                .writes
                .iter()
                .any(|write| write.original() != write.next())
    }
}

#[derive(Debug, Args)]
pub(super) struct VersionArgs {
    /// Git ref to scan from (exclusive). Same default as `generate` / `status`.
    #[arg(long, value_name = "REF")]
    from: Option<String>,
    /// Release notes body. `-` reads stdin. Path cannot escape the checkout (ADR-0006).
    #[arg(long, value_name = "PATH")]
    notes_file: Option<PathBuf>,
}

pub(super) fn run(args: &VersionArgs) -> Result<(), Box<dyn std::error::Error>> {
    let prepared = plan_writes(args)?;
    commit_write_set(prepared.repo.dir(), &prepared.writes, &prepared.deletes)?;
    // The writes have landed. A refused summary must not panic away the one
    // account of what changed, nor read as ok: the files exist, the answer did
    // not arrive.
    super::deliver_block(&wrote_summary(&prepared)).map_err(|err| {
        CliError::undelivered("files written, but the summary of what changed", &err)
    })?;
    Ok(())
}

/// What the run changed, printed after the writes land so it reports rather than
/// promises. `version` performs the irreversible part of a release — manifests,
/// lockfile rows, changelogs, `extra-files`, and the bump files it consumes —
/// and said nothing at all about any of it (`okm-404.7`).
///
/// `ci version-pr` calls [`plan_writes`] rather than [`run`], so its output is
/// unaffected.
fn wrote_summary(prepared: &VersionWritePlan) -> String {
    let mut out = String::new();
    let changes = prepared.plan.changes();
    if changes.is_empty() {
        // Not a wasted run: a bump file that names nothing is still consumed,
        // so the `consumed` lines below are the whole report. Every write path
        // iterates the plan's changes, so an empty plan wrote no file.
        out.push_str("versioned nothing\n");
    } else {
        out.push_str("versioned:\n");
        for (id, change) in changes {
            let cascaded = match change.source() {
                ChangeSource::Cascade { trigger } => format!(" (cascaded from {trigger})"),
                ChangeSource::Intent => String::new(),
            };
            let _ = writeln!(out, "  {id} {} -> {}{cascaded}", change.from(), change.to());
        }
    }
    // Only files whose bytes moved: a planned write that matched what was
    // already there is not something the reader has to look at.
    let touched: Vec<&Path> = prepared
        .writes
        .iter()
        .filter(|write| write.original() != write.next())
        .map(PlannedWrite::path)
        .collect();
    for path in &touched {
        let _ = writeln!(out, "  wrote {}", repo_path_display(path));
    }
    for delete in &prepared.deletes {
        let _ = writeln!(out, "  consumed {}", repo_path_display(delete.path()));
    }
    if touched.is_empty() && prepared.deletes.is_empty() {
        out.push_str("  no file changed\n");
    }
    out
}

pub(super) fn plan_writes(
    args: &VersionArgs,
) -> Result<VersionWritePlan, Box<dyn std::error::Error>> {
    let repo = repository::discover()?;
    let config = load_config(&repo)?;
    require_config(&config)?;
    enforce_tool_version(&config)?;
    let (workspace, git, files) =
        Discovered::read(&repo, &config, args.from.as_deref())?.into_parts();
    let consume_ids: Vec<String> = files
        .iter()
        .filter(|file| file.id != COMMITS_BUMP_FILE_ID)
        .map(|file| file.id.clone())
        .collect();
    let intent = aggregate(files);
    let plan = compose_plan(&config, &workspace, &intent)?;

    let (writes, deletes, tool_version, title, commit_message) = {
        let dir = repo.dir();
        let new_versions = versions_from_plan(&plan);
        let mut write_set = WriteSet::new();
        write_set.extend(plan_inherited_writes(dir, &workspace, &new_versions)?);
        plan_member_writes(dir, &workspace, &plan, &mut write_set)?;
        plan_extra_file_writes(dir, &workspace, &plan, &config, &mut write_set)?;
        plan_self_host_tool_version_write(dir, &workspace, &plan, &mut write_set)?;
        write_set.extend(plan_lock_writes(dir, &workspace, &plan)?);
        let date = utc_date(SystemTime::now())?;
        let tool_version = config
            .tool_version()
            .map_or_else(|| env!("CARGO_PKG_VERSION").to_owned(), Version::to_string);
        let template_body = match config.template() {
            Some(source) => Some(load_template_body(dir, repo.path(), source)?),
            None => None,
        };
        let supplied_notes = load_supplied_notes(&repo, args.notes_file.as_deref())?;
        // A supplied body leaves `changes` empty, so there is nothing to link.
        let links = match (template_body.as_deref(), supplied_notes.is_some()) {
            (Some(source), false) => template_links(&git, source, &consume_ids)?,
            _ => None,
        };
        write_set.extend(plan_changelog_writes(
            dir,
            &workspace,
            &plan,
            &intent,
            &ChangelogPlan::new(
                &date,
                &tool_version,
                template_body.as_deref(),
                supplied_notes.as_deref(),
                links.as_ref(),
            ),
        )?);
        let deletes = plan_consume_deletes(dir, &consume_ids)?;
        (
            write_set.writes(),
            deletes,
            tool_version,
            config.title().cloned(),
            config.commit_message().cloned(),
        )
    };
    Ok(VersionWritePlan {
        repo,
        writes,
        deletes,
        plan,
        tool_version,
        title,
        commit_message,
    })
}

fn load_supplied_notes(
    repo: &repository::Repository,
    notes_file: Option<&Path>,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
    let Some(path) = notes_file else {
        return Ok(None);
    };
    if path == Path::new("-") {
        let mut body = String::new();
        io::stdin()
            .read_to_string(&mut body)
            .map_err(|err| CliError::new(format!("`--notes-file -`: {err}")))?;
        let body = strip_bom(&body);
        if supplied_note(&body).is_none() {
            return Err(Box::new(CliError::new(
                "`--notes-file -` produced no notes",
            )));
        }
        return Ok(Some(body));
    }
    let relative = path
        .to_str()
        .ok_or_else(|| CliError::new("`--notes-file` path is not valid UTF-8"))?;
    let body = load_contained_file(repo.dir(), repo.path(), relative, "--notes-file")?;
    Ok(Some(strip_bom(&body)))
}

fn strip_bom(body: &str) -> String {
    body.trim_start_matches('\u{FEFF}').to_owned()
}

fn plan_consume_deletes(
    dir: &Dir,
    ids: &[String],
) -> Result<Vec<PlannedDelete>, Box<dyn std::error::Error>> {
    let mut deletes = Vec::new();
    for id in ids {
        let path = Path::new(CHANGESET_DIR).join(id);
        let original = read_text(dir, &path)?.ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                format!("{} is missing", repo_path_display(&path)),
            )
        })?;
        deletes.push(PlannedDelete::new(path, original));
    }
    Ok(deletes)
}

fn versions_from_plan(plan: &Plan) -> BTreeMap<PackageId, Version> {
    plan.changes()
        .values()
        .map(|change| (change.id().clone(), change.to().clone()))
        .collect()
}

fn plan_member_writes(
    dir: &Dir,
    workspace: &Workspace,
    plan: &Plan,
    write_set: &mut WriteSet,
) -> Result<(), Box<dyn std::error::Error>> {
    let new_versions = versions_from_plan(plan);
    if new_versions.is_empty() {
        return Ok(());
    }
    for package in workspace.packages() {
        let bump = plan.get(package.id());
        let retargets = package
            .dependencies()
            .iter()
            .any(|dep| new_versions.contains_key(&dep.on));
        if bump.is_none() && !retargets {
            continue;
        }
        let path = package_manifest_path(package);
        let (original, mut next) = write_set.source_text(dir, &path)?;
        if let Some(change) = bump {
            if package.id().ecosystem == Ecosystem::Cargo
                && cargo_package_version_inherits_workspace(&next)
                    .map_err(|err| format!("{}: {err}", repo_path_display(&path)))?
            {
                ensure_inheritors_are_planned(dir, workspace, write_set, plan, change.to())?;
                next = plan_workspace_package_version(
                    dir,
                    workspace,
                    write_set,
                    &path,
                    next,
                    change.from(),
                    change.to(),
                )?;
            } else {
                next = bump_package_version(package.id().ecosystem, &next, change.to()).map_err(
                    |err| -> Box<dyn std::error::Error> {
                        format!("{}: {err}", repo_path_display(&path)).into()
                    },
                )?;
            }
        }
        if retargets {
            next = rewrite_dependencies(
                package.id().ecosystem,
                &next,
                package.dependencies(),
                &new_versions,
            )
            .map_err(|err| -> Box<dyn std::error::Error> {
                format!("{}: {err}", repo_path_display(&path)).into()
            })?;
        }
        write_set.put_write(path, original, next);
    }
    Ok(())
}

/// `None` when the template reads neither `repo` nor `changes`, so it costs
/// no git children. Off GitHub `repo` is `None` and the commit fields render
/// without URLs; a `GITHUB_REPOSITORY` that is set but malformed is an error,
/// as in `ci`.
fn template_links(
    git: &Git,
    source: &str,
    file_ids: &[String],
) -> Result<Option<Links>, Box<dyn std::error::Error>> {
    if !oakum::template::reads_any(source, &["repo", "changes"])? {
        return Ok(None);
    }
    let slug = super::ci::repository_slug(git);
    let repo = if std::env::var("GITHUB_REPOSITORY").is_ok_and(|value| !value.trim().is_empty()) {
        Some(slug?)
    } else {
        slug.ok()
    };
    let mut links = Links {
        repo,
        by_file: BTreeMap::new(),
    };
    for id in file_ids {
        let path = format!(".changeset/{id}");
        if let Some(found) = Provenance::of(git, &path)? {
            links.by_file.insert(id.clone(), found);
        }
    }
    Ok(Some(links))
}

/// When the Cargo workspace member named `oakum` is bumped (self-host install
/// pin, ADR-0007), keep `tool-version` in lockstep in the same write set.
/// `upgrade` still owns binary↔config repair; this is the version-PR half of
/// the pin (ADR-0023 amendment).
fn plan_self_host_tool_version_write(
    dir: &Dir,
    workspace: &Workspace,
    plan: &Plan,
    write_set: &mut WriteSet,
) -> Result<(), Box<dyn std::error::Error>> {
    let oakum_id = PackageId::new(Ecosystem::Cargo, "oakum");
    let Some(change) = plan.get(&oakum_id) else {
        return Ok(());
    };
    if workspace.get(&oakum_id).is_none() {
        return Ok(());
    }
    let path = PathBuf::from(".changeset/_config.toml");
    let (original, current) = write_set.source_text(dir, &path).map_err(|err| {
        format!(
            "self-host `tool-version` write for `oakum` at {}: {err}",
            repo_path_display(&path)
        )
    })?;
    let next = oakum::config::set_tool_version(&current, change.to()).map_err(|err| {
        format!(
            "self-host `tool-version` write for `oakum` at {}: {err}",
            repo_path_display(&path)
        )
    })?;
    write_set.put_write(path, original, next);
    Ok(())
}

fn plan_extra_file_writes(
    dir: &Dir,
    workspace: &Workspace,
    plan: &Plan,
    config: &LoadedConfig,
    write_set: &mut WriteSet,
) -> Result<(), Box<dyn std::error::Error>> {
    for change in plan.changes().values() {
        let Some(package) = workspace.get(change.id()) else {
            return Err(format!(
                "plan contains `{}` but the workspace has no such package",
                change.id().name
            )
            .into());
        };
        let extras = config.extra_files_for(&change.id().name);
        if extras.is_empty() {
            continue;
        }
        let next_version = change.to().to_string();
        for extra in extras {
            let path = extra_file_repo_path(package, extra.path()).map_err(|err| {
                format!(
                    "extra-files `{}` for `{}`: {err}",
                    extra.path(),
                    change.id().name
                )
            })?;
            let (original, current) = write_set.source_text(dir, &path).map_err(|err| {
                format!(
                    "extra-files `{}` for `{}`: {err}",
                    extra.path(),
                    change.id().name
                )
            })?;
            let next = match extra.format() {
                ExtraFileFormat::Json => replace_json_at_key(&current, extra.key(), &next_version)
                    .map_err(|err| {
                        format!(
                            "{} (extra-files key `{}` for `{}`): {err}",
                            repo_path_display(&path),
                            extra.key(),
                            change.id().name
                        )
                    })?,
            };
            write_set.put_write(path, original, next);
        }
    }
    Ok(())
}

/// Leading `/` is repository-root relative; otherwise relative to the package
/// manifest directory (ADR-0033). Lexically collapse `.` / `..` so two spellings
/// of the same shared file share one `WriteSet` key. Escaping above the
/// repository root is an error (unmatched `..` is not clamped away).
pub(super) fn extra_file_repo_path(
    package: &Package,
    declared: &str,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let joined = if let Some(rest) = declared.strip_prefix('/') {
        PathBuf::from(rest)
    } else {
        let dir = package.manifest_dir();
        if dir.is_empty() {
            PathBuf::from(declared)
        } else {
            Path::new(dir).join(declared)
        }
    };
    lexical_normalize_repo_relative(&joined)
}

fn lexical_normalize_repo_relative(path: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                if !out.pop() {
                    return Err("path escapes the repository".into());
                }
            }
            Component::CurDir | Component::RootDir | Component::Prefix(_) => {}
            Component::Normal(s) => out.push(s),
        }
    }
    if out.as_os_str().is_empty() {
        return Err("path resolves to empty".into());
    }
    Ok(out)
}

fn plan_lock_writes(
    dir: &Dir,
    workspace: &Workspace,
    plan: &Plan,
) -> Result<Vec<PlannedWrite>, Box<dyn std::error::Error>> {
    let bumps: Vec<CargoLockBump<'_>> = plan
        .changes()
        .values()
        .filter(|change| change.id().ecosystem == Ecosystem::Cargo)
        .map(|change| CargoLockBump {
            name: change.id().name.as_str(),
            from: change.from(),
            to: change.to(),
        })
        .collect();
    if bumps.is_empty() {
        return Ok(Vec::new());
    }
    let path = cargo_lock_path(workspace).ok_or_else(|| {
        CliError::new(
            "cargo packages were bumped but no cargo workspace root is set, so Cargo.lock cannot be retargeted",
        )
    })?;
    let Some(original) = read_text(dir, &path)? else {
        return Ok(Vec::new());
    };
    let next =
        retarget_cargo_lock(&original, &bumps).map_err(|err| -> Box<dyn std::error::Error> {
            format!("{}: {err}", repo_path_display(&path)).into()
        })?;
    Ok(vec![PlannedWrite::new(path, original, next)])
}

fn plan_workspace_package_version(
    dir: &Dir,
    workspace: &Workspace,
    write_set: &mut WriteSet,
    member_path: &Path,
    member_next: String,
    from: &Version,
    to: &Version,
) -> Result<String, Box<dyn std::error::Error>> {
    let path = cargo_workspace_toml_path(workspace)?;
    if member_path == path {
        return set_workspace_package_version(&member_next, from, to)
            .map_err(|err| format!("{}: {err}", repo_path_display(&path)).into());
    }
    let (original, next) = write_set.source_text(dir, &path)?;
    let next = set_workspace_package_version(&next, from, to).map_err(
        |err| -> Box<dyn std::error::Error> {
            format!("{}: {err}", repo_path_display(&path)).into()
        },
    )?;
    write_set.put_write(path, original, next);
    Ok(member_next)
}

fn ensure_inheritors_are_planned(
    dir: &Dir,
    workspace: &Workspace,
    write_set: &WriteSet,
    plan: &Plan,
    to: &Version,
) -> Result<(), Box<dyn std::error::Error>> {
    for package in workspace.packages() {
        if package.id().ecosystem != Ecosystem::Cargo {
            continue;
        }
        let path = cargo_toml_path(package);
        let (_, text) = write_set.source_text(dir, &path)?;
        if !cargo_package_version_inherits_workspace(&text)
            .map_err(|err| format!("{}: {err}", repo_path_display(&path)))?
        {
            continue;
        }
        match plan.get(package.id()) {
            Some(change) if change.to() == to => {}
            Some(change) => {
                return Err(format!(
                    "{} inherits [workspace.package].version but the plan needs {}; another inheritor needs {to}",
                    package.id().name,
                    change.to()
                )
                .into());
            }
            None => {
                return Err(format!(
                    "{} inherits [workspace.package].version and is not in the plan; writing {to} would change it without a changeset",
                    package.id().name
                )
                .into());
            }
        }
    }
    Ok(())
}

fn set_workspace_package_version(
    text: &str,
    from: &Version,
    to: &Version,
) -> Result<String, Box<dyn std::error::Error>> {
    let next = to.to_string();
    if let Some(current) = workspace_package_version(text)? {
        if current == next {
            return Ok(text.to_owned());
        }
        if current != from.to_string() {
            return Err(format!(
                "[workspace.package].version is already {current}; cannot also set {next}"
            )
            .into());
        }
    }
    Ok(set_toml_string(
        text,
        &["workspace", "package", "version"],
        &next,
    )?)
}

fn workspace_package_version(text: &str) -> Result<Option<String>, Box<dyn std::error::Error>> {
    let doc: toml_edit::DocumentMut = text.parse().map_err(|err| format!("{err}"))?;
    Ok(doc
        .get("workspace")
        .and_then(|workspace| workspace.get("package"))
        .and_then(|package| package.get("version"))
        .and_then(|version| version.as_str())
        .map(str::to_owned))
}

fn cargo_workspace_toml_path(workspace: &Workspace) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let root = workspace.cargo_workspace_root().ok_or_else(|| {
        CliError::new(
            "a cargo package inherits [package].version from the workspace but no cargo workspace root is set",
        )
    })?;
    Ok(if root.is_empty() {
        PathBuf::from(CARGO_TOML)
    } else {
        Path::new(root).join(CARGO_TOML)
    })
}

fn bump_package_version(
    ecosystem: Ecosystem,
    text: &str,
    to: &Version,
) -> Result<String, Box<dyn std::error::Error>> {
    let next = to.to_string();
    match ecosystem {
        Ecosystem::Cargo => Ok(set_toml_string(text, &["package", "version"], &next)?),
        Ecosystem::Npm => Ok(set_json_string(text, &["version"], &next)?),
    }
}

fn package_manifest_path(package: &Package) -> PathBuf {
    match package.id().ecosystem {
        Ecosystem::Cargo => cargo_toml_path(package),
        Ecosystem::Npm => {
            let dir = package.manifest_dir();
            if dir.is_empty() {
                PathBuf::from(PACKAGE_JSON)
            } else {
                Path::new(dir).join(PACKAGE_JSON)
            }
        }
    }
}

fn cargo_lock_path(workspace: &Workspace) -> Option<PathBuf> {
    let root = workspace.cargo_workspace_root()?;
    Some(if root.is_empty() {
        PathBuf::from(CARGO_LOCK)
    } else {
        Path::new(root).join(CARGO_LOCK)
    })
}