oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
Documentation
//! The one path from a repository to a [`ReleaseState`] for `status` and
//! `ci pr-status`, and the plan pipeline `version` shares with it.

use std::collections::{BTreeMap, BTreeSet};

use oakum::plan::{
    aggregate_with_updates, compose_managed, declared_range, explain_plan, AggregatedBump,
    BumpFile, CascadeAs, ComposeError, DependencyUpdate, Explain, Origin, PackageId, Plan,
    Workspace,
};
use oakum::state::{Coverage, CoverageOutcome, ReleaseState, RenderTarget, Unlinked};

use super::config::{intent_names_unmanaged, LoadedConfig, PlanIntentSource};
use super::coverage::{self, BranchBumpFiles, Covering};
use super::generate::resolve_from_ref;
use super::git::Git;
use super::intent::{load_coverage_intent, load_plan_intent, DroppedIntent, PlanIntent};
use super::preconditions;
use super::render::NextStep;
use super::repository;
use super::say_err;
use super::verdict::verdict_line;
use super::workspace::discover_validated;
use super::CliError;

/// The workspace, the git handle and the bump files, discovered once for a
/// caller about to plan. Named apart from `preconditions::Loaded`, which is
/// `check`'s config-and-workspace pair: these are the three a planner needs.
/// `check`'s looks deliberately skip the package overrides; only its
/// `--explain`, which plans, comes through here.
///
/// The selection check rides here rather than at each call site, because a
/// caller that discovers a workspace and forgets to validate it against the
/// config plans over packages the config never named.
pub(super) struct Discovered {
    workspace: Workspace,
    git: Git,
    files: Vec<BumpFile>,
    updates: Vec<DependencyUpdate>,
    dropped: DroppedIntent,
}

impl Discovered {
    /// # Errors
    ///
    /// Discovery, a selection naming a package the workspace does not have,
    /// a git handle that cannot open, or bump files that cannot be read.
    pub(super) fn read(
        repo: &repository::Repository,
        config: &LoadedConfig,
        from: Option<&str>,
    ) -> Result<Self, CliError> {
        let workspace = discover_validated(repo, config)?;
        let git = Git::at_repository(repo)?;
        let PlanIntent {
            files,
            updates,
            dropped,
            ..
        } = load_plan_intent(&git, repo, &workspace, config, from)?;
        Ok(Self {
            workspace,
            git,
            files,
            updates,
            dropped,
        })
    }

    /// The parts, for a caller about to plan. Private fields plus this are
    /// what make [`Self::read`] the only way in: a struct literal elsewhere
    /// would skip the selection check this type exists to carry, which was
    /// measured turning an unknown `include` from a refusal into `versioned
    /// nothing` at exit 0.
    pub(super) fn into_parts(
        self,
    ) -> (
        Workspace,
        Git,
        Vec<BumpFile>,
        Vec<DependencyUpdate>,
        DroppedIntent,
    ) {
        (
            self.workspace,
            self.git,
            self.files,
            self.updates,
            self.dropped,
        )
    }
}

/// What a caller does when the coverage look fails. Named rather than implied:
/// left to whichever of `match` or `?` a call site happens to write, the
/// disposition is inherited rather than chosen.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CoverageMode {
    /// A failed look refuses — the caller cannot answer without it.
    Required,
    /// A failed look is recorded as not run, and the report goes out saying so.
    Reported,
}

/// The one path from a repository to a [`ReleaseState`], for `status` and `ci
/// pr-status`. Building it twice is how two renderers of the same state come to
/// disagree. The version-PR body is not here: `ci::pr_body` renders a plan it
/// already holds, with no repository to look at, which is why its coverage is
/// `NotAsked` rather than a look that failed.
///
/// Takes the config rather than loading one, so the config that chose the
/// channel is the config that built the plan; the workspace and git are
/// discovered here, once. Measured before this: `ci pr-status` opened
/// `_config.toml` twice.
pub(super) fn release_state(
    repo: &repository::Repository,
    config: &LoadedConfig,
    from: Option<&str>,
    target: RenderTarget,
    mode: CoverageMode,
) -> Result<(ReleaseState, NextStep), CliError> {
    let Discovered {
        workspace,
        git,
        files,
        updates,
        dropped,
    } = Discovered::read(repo, config, from)?;
    // `generate` writes intent for every commit in the range, so, as in
    // `check`, it is offered only while the branch has no bump file of its own.
    let mut generate_from = None;
    let coverage = resolve_coverage(
        covering(repo, config, &git, &workspace, &files, from).and_then(|(covering, base)| {
            if covering.files().is_empty() {
                generate_from = Some(super::tags::shell_quote(&base));
            }
            coverage::changed_by_standing(&git, &workspace, &covering, from, |package| {
                config.standing(package)
            })
        }),
        mode,
    )?;
    let next = match config.plan_intent_source()? {
        PlanIntentSource::ChangeFiles => NextStep::BumpFiles {
            pending: files.len(),
            generate: config.generate_allowed(),
            generate_from: generate_from.filter(|_| config.generate_allowed()),
        },
        PlanIntentSource::CommitsOnly => NextStep::Commits,
    };
    let intent = aggregate_with_updates(files, updates);
    let plan = compose_plan(config, &workspace, &intent)?;
    let hand_set =
        preconditions::hand_set_versions(&git, repo, config, &workspace, plan.changes())?
            .reported()?;
    let dropped = DroppedIntent {
        only_updates: only_dependency_updates(&intent),
        ..dropped
    };
    let state = dropped
        .report(ReleaseState::from_plan(&plan, coverage, target))
        .with_hand_set(hand_set)
        .with_unlinked(
            if matches!(target, RenderTarget::Status | RenderTarget::Summary) {
                unlinked(config, &workspace)
            } else {
                Vec::new()
            },
        )
        .with_retired(preconditions::retired_packages(&git, config, &workspace));
    let state = if preconditions::manages_nothing(config, &workspace) {
        state.managing_nothing()
    } else if preconditions::selection_is_empty(config, &workspace) {
        state.selection_emptied()
    } else {
        state
    };
    Ok((state, next))
}

/// For `status` alone: on a pull request's comment or job summary a deliberate
/// registry pin would be reported on every run. Excluded dependents are left
/// out, since an exclusion is a decision.
fn unlinked(config: &LoadedConfig, workspace: &Workspace) -> Vec<Unlinked> {
    workspace
        .packages()
        .filter(|package| config.standing(package) != coverage::Standing::Excluded)
        .flat_map(|package| {
            package
                .unlinked_dependencies()
                .iter()
                .filter_map(move |dependency| {
                    let member =
                        workspace.get(&PackageId::new(package.id().ecosystem, &dependency.on))?;
                    Some(Unlinked::new(
                        package.id().clone(),
                        dependency,
                        member.version().clone(),
                    ))
                })
        })
        .collect()
}

/// The branch's own intent, as `check` reads it for coverage: the plan's also
/// holds what is pending on the base branch.
fn covering(
    repo: &repository::Repository,
    config: &LoadedConfig,
    git: &Git,
    workspace: &Workspace,
    files: &[BumpFile],
    from: Option<&str>,
) -> Result<(Covering, String), CliError> {
    let base = resolve_from_ref(git, from)?;
    let covering = match config.plan_intent_source()? {
        PlanIntentSource::ChangeFiles => Covering::ChangeFiles {
            files: BranchBumpFiles::read(git, &base)?.own(files),
            commits: super::intent::releaseless_commits(git, workspace, config, &base)?,
        },
        PlanIntentSource::CommitsOnly => {
            let intent = load_coverage_intent(git, repo, workspace, config, &base)?;
            Covering::CommitsOnly {
                commits: intent.files,
                types: intent.commit_types.unwrap_or_default(),
            }
        }
    };
    Ok((covering, base))
}

/// One plan pipeline for every renderer, under the config's version selection.
/// Measured before this: `version` carried its own copy, so two pipelines fed
/// one renderer.
pub(super) fn compose_plan(
    config: &LoadedConfig,
    workspace: &Workspace,
    intent: &BTreeMap<PackageId, AggregatedBump>,
) -> Result<Plan, CliError> {
    compose_managed(
        workspace,
        intent,
        |id| config.versioning_for(&id.name),
        CASCADE_AS,
        |package| config.version_managed(package),
    )
    .map_err(|err| match err {
        ComposeError::Unmanaged(id) => CliError::new(intent_names_unmanaged(&id.name)),
        err => CliError::new(err.to_string()),
    })
}

/// The cascade level [`compose_plan`] plans with, and so the one
/// [`explain`] must trace under.
const CASCADE_AS: CascadeAs = CascadeAs::Patch;

/// The packages whose every releasing contribution is a dependency update.
pub(super) fn only_dependency_updates(
    intent: &BTreeMap<PackageId, AggregatedBump>,
) -> BTreeSet<PackageId> {
    intent
        .iter()
        .filter(|(_, bump)| {
            let mut releasing = bump
                .contributions()
                .iter()
                .filter(|contribution| contribution.level().is_release())
                .peekable();
            releasing.peek().is_some()
                && releasing.all(|contribution| contribution.origin() == Origin::DependencyUpdate)
        })
        .map(|(id, _)| id.clone())
        .collect()
}

/// The trace of the plan [`compose_plan`] builds from the pending intent,
/// for `check --explain`. The adapters are the ones `compose` itself uses,
/// so the trace describes that plan.
pub(super) fn explain(
    git: &Git,
    repo: &repository::Repository,
    config: &LoadedConfig,
    from: Option<&str>,
) -> Result<Explain, CliError> {
    let workspace = discover_validated(repo, config)?;
    let PlanIntent { files, updates, .. } = load_plan_intent(git, repo, &workspace, config, from)?;
    let plan = compose_plan(config, &workspace, &aggregate_with_updates(files, updates))?;
    Ok(explain_plan(&workspace, &plan, CASCADE_AS, declared_range))
}

/// What a failed look becomes, given the caller's disposition. Pure, so the one
/// distinction [`CoverageMode`] exists to draw is testable without a repository
/// — the alternative is a shallow-clone fixture and a subprocess, which is how
/// the disposition went unguarded in the first place.
fn resolve_coverage(
    look: Result<Coverage, CliError>,
    mode: CoverageMode,
) -> Result<CoverageOutcome, CliError> {
    match look {
        Ok(coverage) => Ok(CoverageOutcome::Ran(coverage)),
        Err(err) if mode == CoverageMode::Required => Err(err),
        Err(err) => {
            say_err(&format!(
                "unverified: coverage not checked: {}",
                verdict_line(&err.detail())
            ));
            Ok(CoverageOutcome::Failed)
        }
    }
}

pub(super) fn apply_package_overrides(
    workspace: &Workspace,
    config: &LoadedConfig,
) -> Result<Workspace, Box<dyn std::error::Error>> {
    let packages: Vec<_> = workspace
        .packages()
        .cloned()
        .map(
            |pkg| match config.resolves_dependencies_at(&pkg.id().name) {
                Some(at) => pkg.with_resolves_dependencies_at(at),
                None => pkg,
            },
        )
        .collect();
    Workspace::new(packages)
        .map(|built| built.with_discovery_paths(workspace))
        .map_err(|err| CliError::new(err.to_string()).into())
}

/// The disposition [`CoverageMode`] names, at unit level. The same distinction
/// costs a shallow-clone fixture and a subprocess to observe end to end.
#[cfg(test)]
mod disposition {
    use oakum::state::{Coverage, CoverageOutcome};

    use super::{resolve_coverage, CoverageMode};
    use crate::cli::CliError;

    fn failed_look() -> Result<Coverage, CliError> {
        Err(CliError::unverified("unverified: shallow clone"))
    }

    #[test]
    fn a_required_look_that_failed_refuses() {
        assert!(resolve_coverage(failed_look(), CoverageMode::Required).is_err());
    }

    #[test]
    fn a_reported_look_that_failed_is_recorded_not_refused() {
        assert_eq!(
            resolve_coverage(failed_look(), CoverageMode::Reported).expect("reported"),
            CoverageOutcome::Failed
        );
    }

    #[test]
    fn a_look_that_ran_carries_its_answers_under_either_disposition() {
        for mode in [CoverageMode::Required, CoverageMode::Reported] {
            let outcome = resolve_coverage(Ok(Coverage::default()), mode).expect("ran");
            assert_eq!(outcome, CoverageOutcome::Ran(Coverage::default()));
        }
    }
}