use std::collections::{BTreeMap, BTreeSet};
use oakum::changeset::{is_bump_file_name, load_bump_files};
use oakum::commits::path_crate_changes;
use oakum::plan::{BumpFile, Ecosystem, Package, PackageId, Workspace};
use oakum::state::{BumpName, ChangedPackage, CoverSource, Coverage, ReleasingCommit};
use oakum::tags::Declared;
use super::changelog;
use super::dependency_updates::{self, Ask, HeadPackages, Verdicts};
use super::generate::{resolve_from_ref, CommitTypes};
use super::git::{Commit, Followed, Git, Op};
use super::intent::BranchCommits;
use super::reasons;
use super::root_files::{self, RootReach};
use super::CliError;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Standing {
Excluded,
Unmanaged,
Managed,
}
#[derive(Clone, Debug)]
pub(super) enum Covering {
ChangeFiles {
files: Vec<BumpFile>,
commits: BranchCommits,
},
CommitsOnly {
commits: Vec<BumpFile>,
types: CommitTypes,
},
}
impl Covering {
pub(super) fn files(&self) -> &[BumpFile] {
match self {
Self::ChangeFiles { files, .. } => files,
Self::CommitsOnly { .. } => &[],
}
}
fn commits(&self) -> (&[BumpFile], &CommitTypes) {
match self {
Self::ChangeFiles { commits, .. } => (&commits.files, &commits.types),
Self::CommitsOnly { commits, types } => (commits, types),
}
}
fn sources(&self, id: &PackageId) -> Vec<CoverSource> {
let named = |file: &BumpFile| {
file.entries
.iter()
.filter(|(named, _)| named == id)
.map(|(_, level)| *level)
.max()
};
let mut sources = Vec::new();
for file in self.files() {
let path = format!("{BUMP_DIR}/{}", file.id);
if file.entries.is_empty() {
sources.push(CoverSource::EmptyFile { file: path });
} else if let Some(level) = named(file) {
sources.push(CoverSource::file(path, level));
}
}
let (commits, types) = self.commits();
for commit in commits {
if let Some(level) = named(commit) {
let kind = types.get(&commit.id).and_then(|read| read.kind.clone());
sources.push(CoverSource::commit(commit.id.clone(), kind, level));
}
}
sources
}
fn released_by(&self, id: &PackageId) -> Vec<ReleasingCommit> {
match self {
Self::ChangeFiles { commits, .. } => {
commits.released.get(id).cloned().unwrap_or_default()
}
Self::CommitsOnly { .. } => Vec::new(),
}
}
fn fix(&self, id: &PackageId, released_by: &[ReleasingCommit]) -> Option<String> {
if let Self::CommitsOnly { .. } = self {
return None;
}
let level = released_by
.iter()
.map(|commit| commit.bump)
.max()
.map_or("<level>", BumpName::as_str);
Some(format!("oakum add --packages {}:{level}", id.name))
}
}
pub(super) fn changed_by_standing(
git: &Git,
workspace: &Workspace,
covering: &Covering,
from: Option<&str>,
standing: impl Fn(&Package) -> Standing,
) -> Result<Coverage, CliError> {
Ok(answer(
&committed_changes(git, workspace, from)?,
workspace,
covering,
&classify(workspace, standing),
))
}
struct Changes {
paths: Vec<String>,
root: RootReach,
verdicts: Verdicts,
}
struct Committed {
changes: Changes,
base: String,
listed: Vec<String>,
}
fn committed_changes(
git: &Git,
workspace: &Workspace,
from: Option<&str>,
) -> Result<Changes, CliError> {
committed(git, workspace, from).map(|committed| committed.changes)
}
fn committed(git: &Git, workspace: &Workspace, from: Option<&str>) -> Result<Committed, CliError> {
let (base, listed, paths) = changed_paths(git, workspace, from)?;
let root_touched = root_files::touched(workspace, &listed);
if !root_touched && !dependency_updates::names_a_manifest(workspace, &paths) {
return Ok(Committed {
changes: Changes {
paths,
root: RootReach::default(),
verdicts: Verdicts::default(),
},
base,
listed,
});
}
let (fork, head) = (fork_point(git, &base)?, git.head()?);
let root = if root_touched {
root_files::between_commits(git, workspace, &fork, &head, &listed)?
} else {
RootReach::default()
};
let sides = (&fork, HeadPackages::Commit(&head));
let verdicts = dependency_updates::verdicts(git, workspace, sides, &paths, &root, &|wanted| {
dependency_updates::followed(git, &head, wanted)
})?;
Ok(Committed {
changes: Changes {
paths,
root,
verdicts,
},
base,
listed,
})
}
fn fork_point(git: &Git, base: &str) -> Result<Commit, CliError> {
git.merge_base(base)?.ok_or_else(|| {
CliError::unverified(format!(
"unverified: `{base}` and `HEAD` share no commit, so the workspace's root files have no side to compare against"
))
})
}
#[derive(Debug, Default)]
pub(super) struct Unseen(Vec<ChangedPackage>);
impl Unseen {
pub(super) fn lines(&self, hint: impl Fn(&ChangedPackage) -> String) -> Vec<String> {
self.0
.iter()
.map(|package| {
format!(
"{}: changed{} outside `HEAD`, which the coverage look does not read; \
commit it and {}",
package.id(),
reasons::via_clause(package),
hint(package)
)
})
.collect()
}
}
pub(super) struct Uncovered {
pub(super) committed: Coverage,
pub(super) outside_head: Result<Worktree, CliError>,
}
#[derive(Debug)]
pub(super) struct Worktree {
pub(super) unseen: Unseen,
pub(super) covered_off_disk: Result<Vec<OffDisk>, CliError>,
}
#[derive(Debug)]
pub(super) struct OffDisk {
pub(super) package: PackageId,
pub(super) files: Vec<String>,
}
impl Worktree {
pub(super) fn lines(&self, hint: impl Fn(&ChangedPackage) -> String) -> Vec<String> {
let mut lines = self.unseen.lines(hint);
let off_disk = match &self.covered_off_disk {
Ok(off_disk) => off_disk,
Err(err) => {
lines.push(format!(
"the intent `HEAD` carries could not be read, so what a pull request would \
be covered by is unknown: {}",
err.detail()
));
return lines;
}
};
lines.extend(off_disk.iter().map(|off| {
let quoted: Vec<String> = off.files.iter().map(|file| format!("`{file}`")).collect();
let quoted: Vec<&str> = quoted.iter().map(String::as_str).collect();
format!(
"{}: covered on disk by {}, not by `HEAD`; commit that, or a pull request gets \
this package with nothing covering it",
off.package,
super::verdict::named("ed)
)
}));
lines
}
}
pub(super) fn changed_by_standing_and_unseen(
git: &Git,
workspace: &Workspace,
covering: &Covering,
from: Option<&str>,
branch: Option<&BranchBumpFiles>,
standing: impl Fn(&Package) -> Standing,
read_disk: impl Fn(&str) -> Result<Option<String>, CliError>,
) -> Result<Uncovered, CliError> {
let classified = classify(workspace, standing);
let Committed {
changes: committed_changes,
base,
listed,
} = committed(git, workspace, from)?;
let committed = answer(&committed_changes, workspace, covering, &classified);
let paths = &committed_changes.paths;
let outside_head = uncommitted_paths(git).and_then(|uncommitted| {
let changes: Vec<String> = uncommitted
.into_iter()
.filter(|path| !is_intent_path(path))
.collect();
let covered_off_disk = match (branch, covering) {
(Some(branch), Covering::ChangeFiles { files, commits }) if !files.is_empty() => {
intent_in_head(git, workspace).map(|head| {
resting_on_uncommitted_intent(
&Covering::ChangeFiles {
files: branch.own_in_head(head),
commits: commits.clone(),
},
&committed_changes,
workspace,
files,
&classified,
&committed,
)
})
}
_ => Ok(Vec::new()),
};
let mut everything = paths.clone();
everything.extend(changes.iter().cloned());
let mut listed = listed.clone();
listed.extend(changes.iter().cloned());
let root_touched = root_files::touched(workspace, &listed);
let (root, verdicts) =
if root_touched || dependency_updates::names_a_manifest(workspace, &everything) {
let (fork, head) = (fork_point(git, &base)?, git.head()?);
let root = if root_touched {
root_files::against_worktree(
git, workspace, &fork, &head, &listed, &changes, &read_disk,
)?
} else {
RootReach::default()
};
let verdicts = dependency_updates::verdicts(
git,
workspace,
(&fork, HeadPackages::Worktree),
&everything,
&root,
&|wanted| {
let committed = dependency_updates::followed(git, &head, wanted)?;
wanted
.iter()
.zip(committed)
.map(|(path, committed)| {
if changes.iter().any(|listed| listed == path) {
read_disk(path)
} else {
Ok(committed)
}
})
.collect()
},
)?;
(root, verdicts)
} else {
(RootReach::default(), Verdicts::default())
};
let if_committed = answer(
&Changes {
paths: everything,
root,
verdicts,
},
workspace,
covering,
&classified,
);
let already: Vec<&oakum::state::PackageRef> =
committed.uncovered().map(ChangedPackage::id).collect();
Ok(Worktree {
unseen: Unseen(
if_committed
.uncovered()
.filter(|package| !already.contains(&package.id()))
.cloned()
.collect(),
),
covered_off_disk,
})
});
Ok(Uncovered {
committed,
outside_head,
})
}
fn classify(
workspace: &Workspace,
standing: impl Fn(&Package) -> Standing,
) -> BTreeMap<PackageId, Standing> {
workspace
.packages()
.map(|package| (package.id().clone(), standing(package)))
.collect()
}
fn answer(
diff: &Changes,
workspace: &Workspace,
covering: &Covering,
classified: &BTreeMap<PackageId, Standing>,
) -> Coverage {
let managed = |package: &Package| classified.get(package.id()) == Some(&Standing::Managed);
let asks =
dependency_updates::asks(workspace, &diff.paths, &diff.root, &diff.verdicts, managed);
let origins = |wanted: Ask| {
asks.iter()
.filter(move |(_, asked)| **asked == wanted)
.map(|(id, _)| id)
};
let mut reached = oakum::plan::reach(workspace, origins(Ask::Intent), managed);
let updated = oakum::plan::reach(workspace, origins(Ask::Update), managed);
let crates = path_crate_changes(&diff.paths, workspace);
let through_crates = oakum::plan::reach(workspace, crates.keys(), managed);
for (id, mut via) in through_crates.managed {
let origin = via.last().unwrap_or(&id);
if let Some(name) = crates.get(origin).and_then(|names| names.first()) {
via.push(PackageId::new(Ecosystem::Cargo, name.clone()));
}
if reached
.managed
.get(&id)
.is_none_or(|direct| direct.len() > via.len())
{
reached.managed.insert(id, via);
}
}
reached.stranded.extend(through_crates.stranded);
let mut through = diff.root.through(workspace, managed);
let mut changed = BTreeMap::new();
for (id, via) in reached.managed {
let covered_by = covering.sources(&id);
let (released_by, fix) = if covered_by.is_empty() {
let released_by = covering.released_by(&id);
let fix = covering.fix(&id, &released_by);
(released_by, fix)
} else {
(Vec::new(), None)
};
let through = through.remove(&id).unwrap_or_default();
let package = ChangedPackage::new(id.clone(), via, covered_by, released_by, fix);
changed.insert(id, package.with_through(through));
}
for (id, via) in updated.managed {
if changed.contains_key(&id) {
continue;
}
let mut covered_by = covering.sources(&id);
covered_by.push(CoverSource::DependencyUpdate);
let through = through.remove(&id).unwrap_or_default();
let package = ChangedPackage::new(id.clone(), via, covered_by, Vec::new(), None);
changed.insert(id, package.with_through(through));
}
let changed = changed.into_values().collect();
Coverage {
unmanaged: reached
.stranded
.into_iter()
.chain(updated.stranded)
.filter(|id| classified.get(id) == Some(&Standing::Unmanaged))
.collect(),
changed,
}
}
fn changed_paths(
git: &Git,
workspace: &Workspace,
from: Option<&str>,
) -> Result<(String, Vec<String>, Vec<String>), CliError> {
refuse_shallow(git)?;
let base = resolve_from_ref(git, from)?;
let dirs: BTreeSet<&str> = workspace.packages().map(Package::manifest_dir).collect();
let released = written_only_by_version_commits(git, &base, &dirs, |commit, dir| {
released_in(git, workspace, commit, dir)
})?;
let listed: Vec<String> = git
.paths(Op::ChangedPaths { from: &base })?
.into_iter()
.filter(|path| !is_intent_path(path))
.collect();
let paths = listed
.iter()
.filter(|path| !released.contains(*path))
.cloned()
.collect();
Ok((base, listed, paths))
}
pub(super) fn refuse_shallow(git: &Git) -> Result<(), CliError> {
if super::tags::is_shallow(git)? {
return Err(CliError::unverified(
"unverified: shallow clone; changed files cannot be listed against a base that was not fetched — use `fetch-depth: 0`, or `git fetch --unshallow`",
));
}
Ok(())
}
const VERSION_WRITES: [&str; 7] = [
"Cargo.toml",
"package.json",
"CHANGELOG.md",
"Cargo.lock",
"pnpm-lock.yaml",
"pnpm-workspace.yaml",
".yarnrc.yml",
];
const MANIFESTS: [&str; 2] = ["Cargo.toml", "package.json"];
fn written_only_by_version_commits(
git: &Git,
base: &str,
dirs: &BTreeSet<&str>,
released: impl Fn(&RangeCommit, &str) -> Result<BTreeSet<String>, CliError>,
) -> Result<BTreeSet<String>, CliError> {
let mut excused = BTreeSet::new();
let mut ordinary = BTreeSet::new();
for commit in range_commits(git, base)? {
let written = |status: &str| status != "D";
let wrote: BTreeSet<&str> = commit
.changes
.iter()
.filter(|(status, _)| written(status))
.map(|(_, path)| path.as_str())
.collect();
let mut by_dir: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
for (status, path) in &commit.changes {
let (dir, name) = path.rsplit_once('/').unwrap_or(("", path));
let changelog = if dir.is_empty() {
String::from("CHANGELOG.md")
} else {
format!("{dir}/CHANGELOG.md")
};
let candidate = !commit.merge
&& written(status)
&& VERSION_WRITES.contains(&name)
&& dirs.contains(dir)
&& wrote.contains(changelog.as_str());
if candidate && !by_dir.contains_key(dir) {
by_dir.insert(dir, released(&commit, dir)?);
}
let released_here = candidate
&& by_dir.get(dir).is_some_and(|manifests| {
!manifests.is_empty()
&& (!MANIFESTS.contains(&name) || manifests.contains(path))
});
if released_here {
excused.insert(path.clone());
} else {
ordinary.insert(path.clone());
}
}
}
Ok(excused.difference(&ordinary).cloned().collect())
}
fn released_in(
git: &Git,
workspace: &Workspace,
commit: &RangeCommit,
dir: &str,
) -> Result<BTreeSet<String>, CliError> {
let head = Commit::from_log(&commit.hash)?;
let parent = git.first_parent_or_empty(&head)?;
let read = |at: &Commit, path: &str| -> Result<Result<Option<String>, ()>, CliError> {
Ok(match git.followed_blob(at, path)? {
Followed::File(bytes) => Ok(Some(String::from_utf8_lossy(&bytes).into_owned())),
Followed::Absent => Ok(None),
Followed::Dangling | Followed::Unfollowed(_) => Err(()),
})
};
let mut released = BTreeSet::new();
for package in workspace
.packages()
.filter(|package| package.manifest_dir() == dir)
{
let manifest = package.manifest_path();
let root = match package.id().ecosystem {
Ecosystem::Cargo => workspace
.cargo_root_manifest()
.filter(|root| *root != manifest),
Ecosystem::Npm => None,
};
let declared = |at: &Commit| -> Result<Declared, CliError> {
let text = match read(at, &manifest)? {
Ok(Some(text)) => text,
Ok(None) => return Ok(Declared::Absent),
Err(()) => return Ok(Declared::Unreadable),
};
oakum::tags::declared(package.id().ecosystem, &text, || match &root {
Some(root) => read(at, root).map(|side| side.unwrap_or(Some(String::new()))),
None => Ok(Some(text.clone())),
})
};
let Declared::Version(version) = declared(&head)? else {
continue;
};
match declared(&parent)? {
Declared::Version(before) if before == version => continue,
Declared::Unreadable => continue,
Declared::Version(_) | Declared::Absent => {}
}
let path = changelog::changelog_repo_path(package);
let section = |at: &Commit| -> Result<Option<bool>, CliError> {
Ok(match read(at, &path)? {
Ok(Some(text)) => Some(changelog::holds_version_section(
&text,
changelog::Owner::new(&package.id().name, false),
&version,
)),
Ok(None) => Some(false),
Err(()) => None,
})
};
if section(&head)? == Some(true) && section(&parent)? == Some(false) {
released.insert(manifest);
}
}
Ok(released)
}
struct RangeCommit {
hash: String,
merge: bool,
changes: Vec<(String, String)>,
}
fn range_commits(git: &Git, base: &str) -> Result<Vec<RangeCommit>, CliError> {
let cut_short = || {
CliError::unverified(
"unverified: `git log --name-status` ended mid-record, so version commits could not be told from the rest",
)
};
let is_hash =
|id: &str| matches!(id.len(), 40 | 64) && id.bytes().all(|b| b.is_ascii_hexdigit());
let raw = git.text(Op::RangeChanges { from: base })?;
let mut fields = raw.split('\0');
let mut commits: Vec<RangeCommit> = Vec::new();
while let Some(field) = fields.next() {
let field = field.strip_prefix('\n').unwrap_or(field);
if field.is_empty() {
continue;
}
if let Some(header) = field.strip_prefix('\u{1}') {
let ids: Vec<&str> = header.split_ascii_whitespace().collect();
if ids.is_empty() || !ids.iter().all(|id| is_hash(id)) {
return Err(cut_short());
}
commits.push(RangeCommit {
hash: ids[0].to_owned(),
merge: ids.len() > 2,
changes: Vec::new(),
});
continue;
}
let status_letters = field.bytes().all(|b| b.is_ascii_uppercase());
let path = fields.next().filter(|path| !path.is_empty());
let (Some(commit), Some(path), true) = (commits.last_mut(), path, status_letters) else {
return Err(cut_short());
};
commit.changes.push((field.to_owned(), path.to_owned()));
}
let counted = git.text(Op::RangeCount { from: base })?;
if counted.trim().parse::<usize>().ok() != Some(commits.len()) {
return Err(cut_short());
}
Ok(commits)
}
fn uncommitted_paths(git: &Git) -> Result<Vec<String>, CliError> {
let mut paths = Vec::new();
let mut origin_follows = false;
for record in git.paths(Op::UncommittedPaths)? {
if std::mem::take(&mut origin_follows) {
paths.push(record);
continue;
}
let Some((status, path)) = record
.split_at_checked(3)
.filter(|(_, path)| !path.is_empty())
else {
return Err(CliError::unverified(format!(
"unverified: `git status --porcelain -z` wrote `{record}`, which is not a status pair and a path, so this tree could not be compared with `HEAD`"
)));
};
origin_follows = status.contains(['R', 'C']);
paths.push(path.to_owned());
}
if origin_follows {
return Err(CliError::unverified(
"unverified: `git status --porcelain -z` ended after a rename with no origin path, so this tree could not be compared with `HEAD`",
));
}
Ok(paths)
}
fn intent_in_head(git: &Git, workspace: &Workspace) -> Result<Vec<BumpFile>, CliError> {
let head = git.head()?;
let listed = git.paths(Op::TreePaths {
commit: &head,
dir: BUMP_DIR,
})?;
let named: Vec<(&str, &str)> = listed
.iter()
.filter_map(|path| {
bump_file_name(path)
.filter(|name| is_bump_file_name(name))
.map(|name| (name, path.as_str()))
})
.collect();
let framed: Vec<&str> = named
.iter()
.map(|(_, path)| *path)
.filter(|path| !path.contains('\n'))
.collect();
let mut batched = git.blobs(&head, &framed).ok().map(Vec::into_iter);
let mut pairs: Vec<(String, String)> = Vec::new();
for (name, path) in named {
let body = match batched.as_mut() {
Some(bodies) if !path.contains('\n') => bodies
.next()
.expect("one batched body per framed path, in order"),
_ => git.blob(Op::BlobText {
commit: &head,
path,
})?,
};
pairs.push((name.to_owned(), body));
}
let mut files = Vec::new();
let mut malformed = Vec::new();
for (name, body) in &pairs {
let Ok(loaded) = load_bump_files([(name.as_str(), body.as_str())], workspace) else {
continue;
};
files.extend(loaded.files);
malformed.extend(loaded.malformed);
}
let loaded = oakum::changeset::LoadedBumpFiles { files, malformed };
if !loaded.malformed.is_empty() {
let reports: Vec<String> = loaded.malformed.iter().map(ToString::to_string).collect();
return Err(CliError::unverified(format!(
"unverified: `HEAD` carries intent oakum cannot parse ({}), so what a pull request \
would be covered by could not be worked out",
reports.join("; also ")
)));
}
Ok(loaded.files)
}
#[derive(Default)]
pub(super) struct BranchBumpFiles {
committed: BTreeSet<String>,
uncommitted: BTreeSet<String>,
}
impl BranchBumpFiles {
pub(super) fn read(git: &Git, base: &str) -> Result<Self, CliError> {
refuse_shallow(git)?;
let unread = |err: CliError| match err.exit_code() {
2 => err,
_ => CliError::unverified(format!("unverified: {}", err.detail())),
};
let fork = git.merge_base(base).map_err(unread)?;
let Some(fork) = fork else {
return Err(CliError::unverified(format!(
"unverified: `{base}` and `HEAD` share no history, so the bump files pending \
there cannot be told from this branch's"
)));
};
let names = |paths: Vec<String>| -> BTreeSet<String> {
paths
.iter()
.filter_map(|path| bump_file_name(path))
.map(str::to_owned)
.collect()
};
let in_head = names(git.paths(Op::TreePaths {
commit: &git.head().map_err(unread)?,
dir: BUMP_DIR,
})?);
let changed = names(git.paths(Op::ChangedPaths {
from: fork.as_str(),
})?);
Ok(Self {
committed: changed.intersection(&in_head).cloned().collect(),
uncommitted: uncommitted_paths(git).map(names).unwrap_or_default(),
})
}
pub(super) fn own(&self, files: &[BumpFile]) -> Vec<BumpFile> {
files
.iter()
.filter(|file| self.committed.contains(&file.id) || self.uncommitted.contains(&file.id))
.cloned()
.collect()
}
fn own_in_head(&self, files: Vec<BumpFile>) -> Vec<BumpFile> {
files
.into_iter()
.filter(|file| self.committed.contains(&file.id))
.collect()
}
}
fn resting_on_uncommitted_intent(
in_head: &Covering,
changes: &Changes,
workspace: &Workspace,
files: &[BumpFile],
classified: &BTreeMap<PackageId, Standing>,
committed: &Coverage,
) -> Vec<OffDisk> {
let already: BTreeSet<PackageId> = committed
.uncovered()
.map(|package| package.id().package_id())
.collect();
answer(changes, workspace, in_head, classified)
.uncovered()
.map(|package| package.id().package_id())
.filter(|id| !already.contains(id))
.map(|id| OffDisk {
files: files
.iter()
.filter(|file| covers(file, &id))
.map(|file| format!("{BUMP_DIR}/{}", file.id))
.collect(),
package: id,
})
.collect()
}
fn covers(file: &BumpFile, id: &PackageId) -> bool {
file.entries.is_empty() || file.entries.iter().any(|(covered, _)| covered == id)
}
const BUMP_DIR: &str = ".changeset";
fn is_intent_path(path: &str) -> bool {
let path = path.trim_start_matches("./");
path == BUMP_DIR
|| path
.strip_prefix(BUMP_DIR)
.is_some_and(|rest| rest.starts_with('/'))
}
fn bump_file_name(path: &str) -> Option<&str> {
let rest = path.trim_start_matches("./").strip_prefix(BUMP_DIR)?;
let name = rest.strip_prefix('/')?;
(!name.contains('/')).then_some(name)
}
#[cfg(test)]
mod tests {
use oakum::plan::{BumpLevel, Ecosystem, ResolvesDependenciesAt};
use semver::Version;
use super::super::git::Reply;
use super::*;
const STATUS: &str = "status --porcelain -z";
const DIFF: &str = "diff --name-only";
const SHALLOW: &str = "rev-parse --is-shallow-repository";
const RESOLVE: &str = "rev-parse --verify";
const COMMITS: &str = "log --name-status";
const COUNT: &str = "rev-list --count";
fn heard(stdout: &'static str) -> Result<Vec<String>, CliError> {
uncommitted_paths(&Git::answering([(STATUS, Reply::said(stdout))]))
}
fn released(log: &str) -> Result<BTreeSet<String>, CliError> {
let headers = log.matches('\u{1}').count() - log.matches("x\u{1}").count();
released_counting(log, headers)
}
fn released_counting(log: &str, count: usize) -> Result<BTreeSet<String>, CliError> {
released_by(log, count, true)
}
fn released_by(log: &str, count: usize, moved: bool) -> Result<BTreeSet<String>, CliError> {
let mut spelled = log.replace("\u{1}m ", &format!("\u{1}{} ", "e".repeat(40)));
for (name, digit) in [("c1", "1"), ("c2", "2"), ("p1", "a"), ("p2", "b")] {
spelled = spelled.replace(name, &digit.repeat(40));
}
let git = Git::answering([
(COMMITS, Reply::said(spelled)),
(COUNT, Reply::said(format!("{count}\n"))),
]);
written_only_by_version_commits(
&git,
"v0.1.0",
&BTreeSet::from(["", "alpha", "beta"]),
|commit, dir| {
Ok(if moved && commit.hash == "1".repeat(40) {
let manifest = |name: &str| {
if dir.is_empty() {
name.to_owned()
} else {
format!("{dir}/{name}")
}
};
BTreeSet::from([manifest("Cargo.toml"), manifest("package.json")])
} else {
BTreeSet::new()
})
},
)
}
const VERSION: &str =
"\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0";
#[test]
fn a_version_commit_excuses_only_what_it_wrote_for_a_package_it_released() {
let both = BTreeSet::from([
String::from("alpha/CHANGELOG.md"),
String::from("alpha/Cargo.toml"),
]);
assert_eq!(released(VERSION).expect("read"), both);
for (log, why) in [
(
"\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/src/lib.rs\0",
"no changelog written: alpha was not released",
),
(
"\u{1}m p1 p2\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0",
"a merge is never a version commit",
),
(
"\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/fixtures/package.json\0M\0alpha/fixtures/CHANGELOG.md\0",
"a directory that is no package's",
),
(
"\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0D\0alpha/CHANGELOG.md\0",
"deleting the changelog is not writing it",
),
(
"\u{1}m p1 p2\0\nM\0alpha/x\u{1}y\0D\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0",
"a path holding \\x01 does not split the merge into a commit of its own",
),
] {
assert!(released(log).expect("read").is_empty(), "{why}");
}
assert!(
released_by(VERSION, 1, false).expect("read").is_empty(),
"a commit that moved no version released nothing"
);
let no_bump_file = "\u{1}c1 p1\0\nM\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0";
assert_eq!(
released(no_bump_file).expect("read"),
both,
"a release made only of dependency updates consumes no bump file"
);
let root = "\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0Cargo.toml\0M\0CHANGELOG.md\0";
assert_eq!(
released(root).expect("root package"),
BTreeSet::from([String::from("CHANGELOG.md"), String::from("Cargo.toml")])
);
assert!(released("\u{1}c1 \0\nA\0alpha/src/lib.rs\0")
.expect("a root commit has no parents")
.is_empty());
let beta_by_hand ="\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0M\0beta/Cargo.toml\0";
assert_eq!(released(beta_by_hand).expect("read"), both);
let edited_after =
"\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0\u{1}c2 c1\0\nM\0alpha/CHANGELOG.md\0";
assert_eq!(
released(edited_after).expect("read"),
BTreeSet::from([String::from("alpha/Cargo.toml")])
);
}
#[test]
fn a_commit_listing_that_fails_or_stops_short_is_unverified() {
let failed = Git::answering([(COMMITS, Reply::failed(128, "fatal: bad revision"))]);
let err = written_only_by_version_commits(&failed, "v0.1.0", &BTreeSet::new(), |_, _| {
Ok(BTreeSet::new())
})
.expect_err("failed");
assert_eq!(err.exit_code(), 2, "{err}");
for log in [
"\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0",
"\u{1}not-a-hash\0\nM\0alpha/Cargo.toml\0",
"M\0alpha/Cargo.toml\0",
"\u{1}c1 p1\0\nnot a status\0alpha/Cargo.toml\0",
] {
let err = released(log).expect_err(log);
assert_eq!(err.exit_code(), 2, "{log:?}: {err}");
}
let err = released_counting(VERSION, 2).expect_err("short");
assert_eq!(err.exit_code(), 2, "{err}");
}
#[test]
fn a_head_intent_that_cannot_be_read_keeps_the_rest_of_the_answer() {
let git = Git::answering([
(SHALLOW, Reply::said("false")),
(RESOLVE, Reply::said("v0.1.0")),
(COMMITS, Reply::said("")),
(COUNT, Reply::said("0\n")),
(DIFF, Reply::said("")),
(
STATUS,
Reply::said("?? .changeset/cover.md\0 M demo/src/lib.rs\0"),
),
(
"rev-parse HEAD",
Reply::said("cafebabecafebabecafebabecafebabecafebabe"),
),
("ls-tree", Reply::said(".changeset/cover.md\0")),
("cat-file --batch", Reply::failed(128, "fatal: bad object")),
("cat-file blob", Reply::failed(128, "fatal: bad object")),
]);
let workspace = Workspace::new([member("demo"), member("other")]).expect("workspace");
let files = Vec::from([BumpFile {
id: String::from("cover.md"),
entries: Vec::from([(PackageId::new(Ecosystem::Cargo, "other"), BumpLevel::Patch)]),
note: String::from("note"),
}]);
let uncovered = changed_by_standing_and_unseen(
&git,
&workspace,
&Covering::ChangeFiles {
files,
commits: BranchCommits::default(),
},
Some("v0.1.0"),
Some(&BranchBumpFiles::default()),
|_| Standing::Managed,
|_| Ok(None),
)
.expect("the committed half still answers");
let worktree = uncovered
.outside_head
.expect("the worktree itself read fine");
let err = worktree
.covered_off_disk
.as_ref()
.expect_err("`HEAD`'s intent could not be read");
assert!(err.to_string().contains("bad object"), "{err}");
let lines = worktree.lines(|_| String::from("add a bump file"));
assert!(
lines
.iter()
.any(|line| line.contains("intent `HEAD` carries could not be read")),
"it names what actually failed: {lines:?}"
);
assert!(
lines
.iter()
.any(|line| line.contains("demo (cargo): changed outside `HEAD`")),
"and the half that did answer still says so: {lines:?}"
);
}
#[test]
fn head_intent_is_judged_by_the_same_rules_as_the_disk_copy() {
for body in [
"\n---\ndemo: patch\n---\nnote\n",
"not frontmatter at all\n",
] {
let git = Git::answering([
(
"rev-parse HEAD",
Reply::said("cafebabecafebabecafebabecafebabecafebabe"),
),
("ls-tree", Reply::said(".changeset/cover.md\0")),
(
"cat-file --batch",
Reply::said(format!("o1 blob {}\n{body}\n", body.len())),
),
]);
let err = intent_in_head(&git, &one_package())
.expect_err("a body the disk loader would refuse is refused here");
assert_eq!(err.exit_code(), 2, "{body:?}: {err}");
assert!(err.to_string().contains("cannot parse"), "{body:?}: {err}");
}
}
#[test]
fn a_bump_file_named_with_a_newline_is_read_on_its_own() {
let body = |level: &str| format!("---\ndemo: {level}\n---\n\nnote\n");
let patch = body("patch");
let git = Git::answering([
(
"rev-parse HEAD",
Reply::said("cafebabecafebabecafebabecafebabecafebabe"),
),
(
"ls-tree",
Reply::said(".changeset/a\nb.md\0.changeset/c.md\0"),
),
(
"cat-file --batch",
Reply::said(format!("o1 blob {}\n{patch}\n", patch.len())),
),
("cat-file blob", Reply::said(body("minor"))),
]);
let files = intent_in_head(&git, &one_package()).expect("both read");
let read: Vec<(&str, BumpLevel)> = files
.iter()
.map(|file| (file.id.as_str(), file.entries[0].1))
.collect();
assert_eq!(
read,
[("a\nb.md", BumpLevel::Minor), ("c.md", BumpLevel::Patch)]
);
}
#[test]
fn only_a_direct_child_of_the_bump_directory_is_a_bump_file() {
assert_eq!(bump_file_name(".changeset/demo.md"), Some("demo.md"));
assert_eq!(bump_file_name("./.changeset/demo.md"), Some("demo.md"));
assert_eq!(bump_file_name(".changeset/nested/demo.md"), None);
assert_eq!(bump_file_name(".changesetish/demo.md"), None);
assert_eq!(bump_file_name("src/lib.rs"), None);
}
fn member(name: &str) -> Package {
Package::new(
PackageId::new(Ecosystem::Cargo, name),
Version::new(0, 1, 0),
ResolvesDependenciesAt::Install,
true,
Vec::new(),
)
.with_manifest_dir(name)
}
fn one_package() -> Workspace {
Workspace::new([member("demo")]).expect("workspace")
}
fn releasing(
hash: &str,
subject: &str,
kind: Option<&str>,
level: BumpLevel,
) -> ReleasingCommit {
ReleasingCommit::new(
hash.to_owned(),
subject.to_owned(),
kind.map(str::to_owned),
level,
)
.expect("releases")
}
#[test]
fn the_fix_asks_for_the_highest_level_a_commit_asks_for() {
let commits = vec![
releasing("aaaaaaa111", "tweak demo", None, BumpLevel::Patch),
releasing(
"bbbbbbb222",
"feat!: drop x",
Some("feat"),
BumpLevel::Major,
),
releasing("ccccccc333", "fix: a bug", Some("fix"), BumpLevel::Patch),
];
let id = PackageId::new(Ecosystem::Cargo, "demo");
let files = Covering::ChangeFiles {
files: Vec::new(),
commits: BranchCommits::default(),
};
assert_eq!(
files.fix(&id, &commits).as_deref(),
Some("oakum add --packages demo:major")
);
assert_eq!(
files.fix(&id, &commits[2..]).as_deref(),
Some("oakum add --packages demo:patch")
);
assert_eq!(
files.fix(&id, &[]).as_deref(),
Some("oakum add --packages demo:<level>")
);
let commits_only = Covering::CommitsOnly {
commits: Vec::new(),
types: CommitTypes::new(),
};
assert_eq!(
commits_only.fix(&id, &commits),
None,
"only a commit covers"
);
}
#[test]
fn a_branch_whose_bump_files_cannot_be_listed_is_unverified() {
let fork = "cafebabecafebabecafebabecafebabecafebabe";
let cases = [
Git::answering([
(SHALLOW, Reply::said("false")),
("merge-base", Reply::failed(128, "fatal: bad object")),
]),
Git::answering([
(SHALLOW, Reply::said("false")),
("merge-base", Reply::said(fork)),
("rev-parse HEAD", Reply::failed(128, "fatal: bad head")),
]),
Git::answering([
(SHALLOW, Reply::said("false")),
("merge-base", Reply::said(fork)),
("rev-parse HEAD", Reply::said(fork)),
("ls-tree", Reply::failed(128, "fatal: bad tree")),
]),
Git::answering([
(SHALLOW, Reply::said("false")),
("merge-base", Reply::said(fork)),
("rev-parse HEAD", Reply::said(fork)),
("ls-tree", Reply::said("")),
(DIFF, Reply::failed(128, "fatal: bad revision")),
]),
];
for git in cases {
let Err(err) = BranchBumpFiles::read(&git, "main") else {
panic!("an unread listing read as nothing touched");
};
assert_eq!(err.exit_code(), 2, "{err}");
assert!(err.to_string().contains("fatal: bad"), "{err}");
}
}
#[test]
fn only_bump_files_the_branch_touched_are_its_own() {
let sha = "cafebabecafebabecafebabecafebabecafebabe";
let git = Git::answering([
(SHALLOW, Reply::said("false")),
("merge-base", Reply::said(sha)),
("rev-parse HEAD", Reply::said(sha)),
(
"ls-tree",
Reply::said(".changeset/committed.md\0.changeset/pending.md\0"),
),
(
DIFF,
Reply::said(
".changeset/committed.md\0.changeset/deleted.md\0demo/src/lib.rs\0\
docs/pending.md\0.changeset/nested/pending.md\0",
),
),
(STATUS, Reply::said("?? .changeset/new.md\0")),
]);
let branch = BranchBumpFiles::read(&git, "main").expect("listed");
let file = |id: &str| BumpFile {
id: String::from(id),
entries: Vec::from([(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)]),
note: String::from("note"),
};
let disk = [
file("committed.md"),
file("new.md"),
file("pending.md"),
file("deleted.md"),
];
let own: Vec<String> = branch.own(&disk).into_iter().map(|f| f.id).collect();
assert_eq!(own, ["committed.md", "new.md"]);
let in_head: Vec<String> = branch
.own_in_head(disk.to_vec())
.into_iter()
.map(|f| f.id)
.collect();
assert_eq!(in_head, ["committed.md"]);
let unreadable_tree = Git::answering([
(SHALLOW, Reply::said("false")),
("merge-base", Reply::said(sha)),
("rev-parse HEAD", Reply::said(sha)),
("ls-tree", Reply::said(".changeset/committed.md\0")),
(
DIFF,
Reply::said(".changeset/committed.md\0.changeset/deleted.md\0"),
),
(STATUS, Reply::failed(128, "fatal: bad index")),
]);
let branch = BranchBumpFiles::read(&unreadable_tree, "main")
.expect("an unreadable worktree leaves the committed answer");
let own: Vec<String> = branch.own(&disk).into_iter().map(|f| f.id).collect();
assert_eq!(own, ["committed.md"]);
}
#[test]
fn a_worktree_that_cannot_be_read_keeps_the_committed_answer() {
let git = Git::answering([
(SHALLOW, Reply::said("false")),
(RESOLVE, Reply::said("v0.1.0")),
(COMMITS, Reply::said("")),
(COUNT, Reply::said("0\n")),
(DIFF, Reply::said("demo/src/lib.rs\0")),
(STATUS, Reply::failed(128, "fatal: status is not available")),
]);
let workspace = one_package();
let uncovered = changed_by_standing_and_unseen(
&git,
&workspace,
&Covering::ChangeFiles {
files: Vec::new(),
commits: BranchCommits::default(),
},
Some("v0.1.0"),
Some(&BranchBumpFiles::default()),
|_| Standing::Managed,
|_| Ok(None),
)
.expect("the committed half still answers");
assert_eq!(
uncovered
.committed
.uncovered()
.map(|package| package.id().package_id())
.collect::<Vec<_>>(),
[PackageId::new(Ecosystem::Cargo, "demo")],
"the commits established this before the worktree was read"
);
let err = uncovered
.outside_head
.expect_err("the worktree could not be read");
assert_eq!(err.exit_code(), 2, "{err}");
assert!(err.to_string().contains("failed: exit 128"), "{err}");
}
#[test]
fn each_status_pair_yields_its_path() {
assert_eq!(
heard("M staged.rs\0 M edited.rs\0?? new.rs\0A added.rs\0").expect("parsed"),
["staged.rs", "edited.rs", "new.rs", "added.rs"]
);
}
#[test]
fn a_rename_or_copy_contributes_both_of_its_names() {
assert_eq!(
heard("R beta/moved.rs\0alpha/origin.rs\0 M other.rs\0").expect("parsed"),
["beta/moved.rs", "alpha/origin.rs", "other.rs"]
);
assert_eq!(
heard("C beta/copy.rs\0alpha/origin.rs\0").expect("parsed"),
["beta/copy.rs", "alpha/origin.rs"]
);
}
#[test]
fn a_rename_with_no_origin_field_is_unverified() {
let err = heard("R beta/moved.rs\0").expect_err("refused");
assert_eq!(err.exit_code(), 2, "{err}");
assert!(err.to_string().contains("no origin path"), "{err}");
}
#[test]
fn intent_is_told_from_change() {
for path in [".changeset/demo.md", "./.changeset/demo.md", ".changeset"] {
assert!(is_intent_path(path), "{path}");
}
for path in [
"src/lib.rs",
".changesetish/demo.md",
"a/.changeset/demo.md",
] {
assert!(!is_intent_path(path), "{path}");
}
}
#[test]
fn a_clean_tree_lists_nothing() {
assert_eq!(heard("").expect("parsed"), Vec::<String>::new());
}
#[test]
fn a_record_without_a_path_is_unverified() {
for record in ["??\0", "?? \0"] {
let err = heard(record).expect_err("refused");
assert_eq!(err.exit_code(), 2, "{record:?}: {err}");
assert!(
err.to_string().contains("not a status pair and a path"),
"{err}"
);
}
}
}