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
//! Plan intent loader: change files or commits-only (ADR-0029 / `okm-64b.5`).

use std::collections::{BTreeMap, BTreeSet};
use std::io;
use std::path::Path;

use clap::Args;
use oakum::changeset::{is_bump_file_name, load_bump_files, MalformedBumpFile};
use oakum::config::DependencyUpdates;
use oakum::plan::{BumpFile, BumpLevel, DependencyUpdate, Package, PackageId, Workspace};
use oakum::state::{ReleaseState, ReleasingCommit, UnresolvedScope};
use oakum::tags::{intent_base, latest_tags, IntentBase};
use serde::Serialize;

use super::changelog::{has_version_section, Owner};
use super::config::{
    load_config, named_by_a_commit, tag_managed_ids, unresolved_scope_line, LoadedConfig,
    PlanIntentSource,
};
use super::coverage::Standing;
use super::deliver_out;
use super::fs::{repo_path_display, resolve_capability_path};
use super::generate::{commit_intents, resolve_from_ref, CommitIntents, CommitRanges, CommitTypes};
use super::git::Git;
use super::repository::{self, Repository};
use super::tags::reachable_tags;
use super::update_release::dependency_update_releases;
use super::workspace::discover_validated;
use super::write_set::read_text;
use super::CliError;

#[derive(Debug, Args)]
pub(super) struct PlanIntentArgs {
    #[arg(long, value_name = "REF", help = super::FROM_INTENT)]
    from: Option<String>,
}

/// Hidden until `status`/`check` land; ADR-0029 plan intent for integration tests.
pub(super) fn run(args: &PlanIntentArgs) -> Result<(), Box<dyn std::error::Error>> {
    let repo = repository::discover()?;
    let config = load_config(&repo)?;
    let workspace = discover_validated(&repo, &config)?;
    let git = Git::at_repository(&repo)?;
    let files = load_plan_bump_files(&git, &repo, &workspace, &config, args.from.as_deref())?;
    let report: Vec<PlanIntentReportFile> = files.iter().map(PlanIntentReportFile::from).collect();
    deliver_out(&serde_json::to_string_pretty(&report)?)
        .map_err(|err| CliError::undelivered("report", &err))?;
    Ok(())
}

#[derive(Debug, Serialize)]
struct PlanIntentReportFile {
    id: String,
    entries: Vec<PlanIntentReportEntry>,
    note: String,
}

#[derive(Debug, Serialize)]
struct PlanIntentReportEntry {
    ecosystem: String,
    name: String,
    level: String,
}

impl From<&BumpFile> for PlanIntentReportFile {
    fn from(file: &BumpFile) -> Self {
        Self {
            id: file.id.clone(),
            entries: file
                .entries
                .iter()
                .map(|(id, level)| PlanIntentReportEntry {
                    ecosystem: id.ecosystem.to_string(),
                    name: id.name.clone(),
                    level: level.to_string(),
                })
                .collect(),
            note: file.note.clone(),
        }
    }
}

/// Plan bump-file inputs per ADR-0029 (change files, or one per commit). Does
/// not write.
///
/// `from` is the exclusive git base for commits-only mode (same default rules as
/// `oakum generate` when `None`).
pub(super) fn load_plan_bump_files(
    git: &Git,
    repo: &Repository,
    workspace: &Workspace,
    config: &LoadedConfig,
    from: Option<&str>,
) -> Result<Vec<BumpFile>, Box<dyn std::error::Error>> {
    load_intent(git, repo, workspace, config, from, Updates::Skip).map(|intent| intent.files)
}

/// The plan's inputs, and the release intent commits asked for that no plan
/// receives.
pub(super) struct PlanIntent {
    pub(super) files: Vec<BumpFile>,
    /// Releases dependency updates derive under `dependency-updates =
    /// "release"`; never consumed, linked or counted as pending.
    pub(super) updates: Vec<DependencyUpdate>,
    /// `Some` when `files` are commits, keyed by hash.
    pub(super) commit_types: Option<CommitTypes>,
    pub(super) dropped: DroppedIntent,
}

/// Intent the plan does not receive, which only a report shows. Change files
/// carry none: the plan refuses a file naming an unversioned package, a file
/// names packages, not scopes, and pending files are consumed, not reread.
#[derive(Debug, Default)]
pub(super) struct DroppedIntent {
    /// Packages the config keeps but cannot version. Excluded packages are left
    /// out, since an exclusion is a decision.
    pub(super) named_unmanaged: Vec<PackageId>,
    pub(super) unresolved: Vec<UnresolvedScope>,
    /// Released by `version` and not yet tagged, so commits before the branch
    /// are not read again.
    pub(super) awaiting_tag: Vec<PackageId>,
    /// Versioned packages whose dependency updates `"release"` does not read,
    /// since no tag records what they last released.
    pub(super) updates_unread: Vec<PackageId>,
    /// Packages whose every releasing contribution is a dependency update,
    /// set once the plan's intent is aggregated, so each surface that reports
    /// the plan marks them alike.
    pub(super) only_updates: BTreeSet<PackageId>,
}

impl DroppedIntent {
    /// Said by `check` and on stderr by `version`, so the two cannot differ.
    pub(super) fn lines(&self) -> Vec<String> {
        self.named_unmanaged
            .iter()
            .map(named_by_a_commit)
            .chain(self.unresolved.iter().map(unresolved_scope_line))
            .collect()
    }

    pub(super) fn report(&self, state: ReleaseState) -> ReleaseState {
        state
            .with_named_unmanaged(self.named_unmanaged.clone())
            .with_unresolved_scopes(self.unresolved.clone())
            .with_awaiting_tag(self.awaiting_tag.clone())
            .with_updates_unread(self.updates_unread.clone())
            .with_dependency_updates(&self.only_updates)
    }
}

/// [`load_plan_bump_files`], keeping what commits-only intent left out.
pub(super) fn load_plan_intent(
    git: &Git,
    repo: &Repository,
    workspace: &Workspace,
    config: &LoadedConfig,
    from: Option<&str>,
) -> Result<PlanIntent, Box<dyn std::error::Error>> {
    load_intent(git, repo, workspace, config, from, Updates::Derive)
}

/// [`load_plan_intent`] for the coverage look, which counts only the branch's
/// own intent: commits after `base`, never one pending on the base branch.
/// Bump files come back whole; [`super::coverage::BranchBumpFiles::own`] keeps
/// the branch's.
pub(super) fn load_coverage_intent(
    git: &Git,
    repo: &Repository,
    workspace: &Workspace,
    config: &LoadedConfig,
    base: &str,
) -> Result<PlanIntent, Box<dyn std::error::Error>> {
    load_intent(git, repo, workspace, config, Some(base), Updates::Skip)
}

/// Whether a loader derives dependency-update releases: coverage reads only
/// intent, and a derived release covers nothing it does not already.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Updates {
    Derive,
    Skip,
}

/// With change files and conventional commits both on, the branch's commits
/// that release nothing, as `none` entries for coverage alone (ADR-0039): a
/// package is covered this way only when no commit on the branch that reaches
/// it releases. Empty when either mechanism is off, since a file then is the
/// only intent coverage reads.
///
/// # Errors
///
/// `unverified` on a shallow clone, whose listing would stop short of the base.
pub(super) fn releaseless_commits(
    git: &Git,
    workspace: &Workspace,
    config: &LoadedConfig,
    base: &str,
) -> Result<BranchCommits, Box<dyn std::error::Error>> {
    if !config.generate_allowed() {
        return Ok(BranchCommits::default());
    }
    super::coverage::refuse_shallow(git)?;
    let ranges = CommitRanges::from_base(&resolve_from_ref(git, Some(base))?, workspace);
    let managed = |package: &oakum::plan::Package| config.version_managed(package);
    let CommitIntents {
        intents,
        merges,
        releasing,
        types,
        ..
    } = commit_intents(git, workspace, &ranges, managed)?;
    // A releasing commit blocks every package it reaches by scope and every
    // one its paths touch: `fix(b)` editing `a/` must not leave `a` covered.
    let mut released: BTreeMap<PackageId, Vec<ReleasingCommit>> = BTreeMap::new();
    let mut blocks = |id: PackageId, hash: &str, level: BumpLevel| {
        let by = released.entry(id).or_default();
        if by.iter().any(|seen| seen.commit == hash) {
            return;
        }
        let read = types.get(hash).cloned().unwrap_or_default();
        by.push(
            ReleasingCommit::new(hash.to_owned(), read.subject, read.kind, level)
                .expect("only a commit asking for a release blocks"),
        );
    };
    for (hash, intent) in &intents {
        if intent.level().is_release() {
            for id in intent.packages() {
                blocks(id.clone(), hash, intent.level());
            }
        }
    }
    // A releasing commit whose paths went unread blocks what nothing can name,
    // so coverage is unknown, as it was before its paths were read for scope.
    for (hash, level, touched) in releasing {
        for id in touched? {
            blocks(id, &hash, level);
        }
    }
    let files = intents
        .iter()
        .filter(|(hash, intent)| !intent.level().is_release() && !merges.contains(hash))
        .filter_map(|(hash, intent)| {
            let mut file = intent.bump_file(hash.clone());
            file.entries.retain(|(id, _)| !released.contains_key(id));
            (!file.entries.is_empty()).then_some(file)
        })
        .collect();
    Ok(BranchCommits {
        files,
        types,
        released,
    })
}

/// What the branch's commits say to the coverage look, read by
/// [`releaseless_commits`].
#[derive(Clone, Debug, Default)]
pub(super) struct BranchCommits {
    /// The commits that release nothing, as `none` entries.
    pub(super) files: Vec<BumpFile>,
    pub(super) types: CommitTypes,
    /// Each package a commit asks to release, with those commits in the order
    /// read: none of its commits that release nothing cover it.
    pub(super) released: BTreeMap<PackageId, Vec<ReleasingCommit>>,
}

fn load_intent(
    git: &Git,
    repo: &Repository,
    workspace: &Workspace,
    config: &LoadedConfig,
    from: Option<&str>,
    updates: Updates,
) -> Result<PlanIntent, Box<dyn std::error::Error>> {
    let (updates, updates_unread) = match updates {
        Updates::Derive => release_updates(git, repo, workspace, config, from)?,
        Updates::Skip => (Vec::new(), Vec::new()),
    };
    match config.plan_intent_source()? {
        PlanIntentSource::ChangeFiles => Ok(PlanIntent {
            files: load_change_files(repo, workspace)?,
            updates,
            commit_types: None,
            dropped: DroppedIntent {
                updates_unread,
                ..DroppedIntent::default()
            },
        }),
        PlanIntentSource::CommitsOnly => {
            let (ranges, awaiting_tag) = match from {
                Some(from) => (
                    CommitRanges::from_base(&resolve_from_ref(git, Some(from))?, workspace),
                    Vec::new(),
                ),
                None => ranges_since_tags(git, repo, workspace, config)?,
            };
            // A commit is not a decision to release: one touching a package the
            // config does not version names nothing, rather than a package
            // every later step refuses.
            let CommitIntents {
                intents,
                left_out,
                unresolved,
                types,
                ..
            } = commit_intents(git, workspace, &ranges, |package| {
                config.version_managed(package)
            })?;
            let named_unmanaged = workspace
                .packages()
                .filter(|package| {
                    left_out.contains(package.id())
                        && config.standing(package) == Standing::Unmanaged
                })
                .map(|package| package.id().clone())
                .collect();
            let files = intents
                .into_iter()
                .map(|(hash, intent)| intent.bump_file(hash))
                .collect();
            Ok(PlanIntent {
                files,
                updates,
                commit_types: Some(types),
                dropped: DroppedIntent {
                    named_unmanaged,
                    unresolved,
                    awaiting_tag,
                    updates_unread,
                    only_updates: BTreeSet::new(),
                },
            })
        }
    }
}

/// The releases dependency updates derive, under `"release"` only: each
/// versioned package from its last tag, `--from` replacing every base. A
/// package oakum does not tag, one never tagged and one awaiting its tag read
/// nothing, since no tag records what their last release held (ADR-0040);
/// they are returned beside the releases, but for one awaiting its tag that
/// commits-only intent reports as that already.
fn release_updates(
    git: &Git,
    repo: &Repository,
    workspace: &Workspace,
    config: &LoadedConfig,
    from: Option<&str>,
) -> Result<(Vec<DependencyUpdate>, Vec<PackageId>), Box<dyn std::error::Error>> {
    if config.dependency_updates() != DependencyUpdates::Release {
        return Ok((Vec::new(), Vec::new()));
    }
    let managed = |package: &Package| config.version_managed(package);
    let (bases, unread): (BTreeMap<PackageId, String>, Vec<PackageId>) = if let Some(from) = from {
        let base = resolve_from_ref(git, Some(from))?;
        let bases = workspace
            .packages()
            .filter(|package| managed(package))
            .map(|package| (package.id().clone(), base.clone()))
            .collect();
        (bases, Vec::new())
    } else {
        let tagged = tag_managed_ids(workspace, config);
        let (ranges, awaiting) = ranges_since(git, repo, workspace, config, Untagged::Skipped)?;
        let bases: BTreeMap<PackageId, String> = ranges
            .bases()
            .iter()
            .filter(|(id, _)| tagged.contains(*id))
            .filter(|(id, _)| workspace.get(id).is_some_and(managed))
            .filter_map(|(id, base)| Some((id.clone(), base.clone()?)))
            .collect();
        // Only commits-only intent reports a package awaiting its tag.
        let awaiting_reported = config.plan_intent_source()? == PlanIntentSource::CommitsOnly;
        let unread = workspace
            .packages()
            .filter(|package| managed(package))
            .map(|package| package.id().clone())
            .filter(|id| !bases.contains_key(id) && (!awaiting_reported || !awaiting.contains(id)))
            .collect();
        (bases, unread)
    };
    Ok((
        dependency_update_releases(git, workspace, managed, &bases)?,
        unread,
    ))
}

/// Each package's commits since its highest reachable tag, and the packages
/// awaiting a tag, which read nothing: only the tag records what a release
/// included. A package oakum does not tag keeps the merge-base range.
fn ranges_since_tags(
    git: &Git,
    repo: &Repository,
    workspace: &Workspace,
    config: &LoadedConfig,
) -> Result<(CommitRanges, Vec<PackageId>), Box<dyn std::error::Error>> {
    ranges_since(git, repo, workspace, config, Untagged::MergeBase)
}

/// What a package oakum does not tag reads.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Untagged {
    /// The merge-base range, which the default base ref names.
    MergeBase,
    /// Nothing: dependency updates read a range only from a tag.
    Skipped,
}

/// [`ranges_since_tags`], an untagged package reading what `untagged` says.
fn ranges_since(
    git: &Git,
    repo: &Repository,
    workspace: &Workspace,
    config: &LoadedConfig,
    untagged: Untagged,
) -> Result<(CommitRanges, Vec<PackageId>), Box<dyn std::error::Error>> {
    let tag_managed = tag_managed_ids(workspace, config);
    let latest = if tag_managed.is_empty() {
        BTreeMap::new()
    } else {
        let groups =
            super::retired::without_retired(git, workspace, &tag_managed, reachable_tags(git)?)?
                .groups;
        let tags: Vec<Vec<&str>> = groups
            .iter()
            .map(|group| group.tags().iter().map(String::as_str).collect())
            .collect();
        let commits: Vec<(&str, &[&str])> = groups
            .iter()
            .zip(&tags)
            .map(|(group, tags)| (group.commit(), tags.as_slice()))
            .collect();
        latest_tags(&commits, workspace, |id| tag_managed.contains(id))
            .map_err(|err| CliError::unverified(err.to_string()))?
    };
    let mut merge_base: Option<String> = None;
    let mut since_merge_base = || -> Result<Option<String>, Box<dyn std::error::Error>> {
        if merge_base.is_none() {
            merge_base = Some(resolve_from_ref(git, None)?);
        }
        Ok(merge_base.clone())
    };
    let mut bases = BTreeMap::new();
    let mut awaiting_tag = Vec::new();
    for package in workspace.packages() {
        let base = if tag_managed.contains(package.id()) {
            match intent_base(package, latest.get(package.id()), || {
                has_version_section(repo.dir(), package, Owner::of(workspace, config, package))
            })? {
                IntentBase::Since(commit) => Some(commit),
                IntentBase::Root => None,
                IntentBase::AwaitingTag => {
                    if config.version_managed(package) {
                        awaiting_tag.push(package.id().clone());
                    }
                    continue;
                }
            }
        } else if untagged == Untagged::MergeBase {
            since_merge_base()?
        } else {
            continue;
        };
        bases.insert(package.id().clone(), base);
    }
    Ok((CommitRanges::new(bases), awaiting_tag))
}

fn load_change_files(
    repo: &Repository,
    workspace: &Workspace,
) -> Result<Vec<BumpFile>, Box<dyn std::error::Error>> {
    let dir = repo.dir();
    match dir.symlink_metadata(".changeset") {
        Ok(_) => {}
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(err) => {
            return Err(Box::new(CliError::new(format!(
                "failed to inspect `.changeset`: {err}"
            ))));
        }
    }
    let changeset = resolve_capability_path(dir, repo.path(), Path::new(".changeset"))?;
    let entries = dir.read_dir(&changeset).map_err(|err| {
        CliError::new(format!(
            "failed to read `{}`: {err}",
            repo_path_display(&changeset)
        ))
    })?;

    let mut pairs: Vec<(String, String)> = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|err| {
            CliError::new(format!(
                "failed to read `{}`: {err}",
                repo_path_display(&changeset)
            ))
        })?;
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            continue;
        };
        if !is_bump_file_name(name) {
            continue;
        }
        let relative = changeset.join(name);
        match dir.metadata(&relative) {
            Ok(meta) if meta.is_file() => {}
            Ok(_) => continue,
            Err(err) if err.kind() == io::ErrorKind::NotFound => {
                return Err(Box::new(CliError::new(format!(
                    "failed to read `{}`: file disappeared",
                    repo_path_display(&relative)
                ))));
            }
            Err(err) => {
                return Err(Box::new(CliError::new(format!(
                    "failed to inspect `{}`: {err}",
                    repo_path_display(&relative)
                ))));
            }
        }
        let Some(body) = read_text(dir, &relative)? else {
            return Err(Box::new(CliError::new(format!(
                "failed to read `{}`: file disappeared",
                repo_path_display(&relative)
            ))));
        };
        pairs.push((String::from(name), body));
    }
    pairs.sort_by(|a, b| a.0.cmp(&b.0));

    let loaded = load_bump_files(
        pairs
            .iter()
            .map(|(name, body)| (name.as_str(), body.as_str())),
        workspace,
    )
    .map_err(|err| CliError::new(err.to_string()))?;

    refuse_malformed(&loaded.malformed)?;
    Ok(loaded.files)
}

/// The library collects malformed bodies; every command refuses them. A
/// skipped file turns a formatter's rewrite into a release that never happens.
pub(super) fn refuse_malformed(malformed: &[MalformedBumpFile]) -> Result<(), CliError> {
    if malformed.is_empty() {
        return Ok(());
    }
    let reports: Vec<String> = malformed.iter().map(ToString::to_string).collect();
    Err(CliError::new(reports.join("; also ")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use oakum::plan::Ecosystem;
    use oakum::state::ReleaseSource;

    /// Every surface that reports the plan goes through `report`, the
    /// version pull request's templates included, so it marks derived-only
    /// releases there and nowhere else.
    #[test]
    fn report_marks_releases_made_only_of_dependency_updates() {
        let state: ReleaseState = serde_json::from_str(
            r#"{"schema_version":1,"target":"status","uncovered":[],"packages":[
                {"name":"app","ecosystem":"cargo","from":"0.1.0","to":"0.1.1","bump":"patch","source":{"kind":"intent"}},
                {"name":"lib","ecosystem":"cargo","from":"0.1.0","to":"0.1.1","bump":"patch","source":{"kind":"intent"}}]}"#,
        )
        .expect("state");
        let dropped = DroppedIntent {
            only_updates: BTreeSet::from([PackageId::new(Ecosystem::Cargo, "app")]),
            ..DroppedIntent::default()
        };
        let state = dropped.report(state);
        let sources: Vec<&ReleaseSource> = state
            .packages()
            .iter()
            .map(oakum::state::PackageRelease::source)
            .collect();
        assert_eq!(
            sources,
            [&ReleaseSource::DependencyUpdate, &ReleaseSource::Intent]
        );
    }
}