use std::collections::{BTreeMap, BTreeSet};
use oakum::changeset::{is_bump_file_name, load_bump_files};
use oakum::commits::packages_for_paths;
use oakum::plan::{BumpFile, Package, PackageId, Workspace};
use oakum::state::Coverage;
use super::generate::resolve_from_ref;
use super::git::{Git, Op};
use super::CliError;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Standing {
Excluded,
Unmanaged,
Managed,
}
pub(super) fn changed_by_standing(
git: &Git,
workspace: &Workspace,
files: &[BumpFile],
from: Option<&str>,
standing: impl Fn(&Package) -> Standing,
) -> Result<Coverage, CliError> {
Ok(answer(
&changed_paths(git, from)?,
workspace,
files,
&classify(workspace, standing),
))
}
#[derive(Debug, Default)]
pub(super) struct Unseen(Vec<PackageId>);
impl Unseen {
pub(super) fn lines(&self, hint: &str) -> Vec<String> {
self.0
.iter()
.map(|id| {
format!(
"{id}: changed outside `HEAD`, which the coverage look does not read; \
commit it and {hint}"
)
})
.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: &str) -> 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,
files: &[BumpFile],
from: Option<&str>,
intent_from_disk: bool,
standing: impl Fn(&Package) -> Standing,
) -> Result<Uncovered, CliError> {
let classified = classify(workspace, standing);
let paths = changed_paths(git, from)?;
let committed = answer(&paths, workspace, files, &classified);
let outside_head = uncommitted_paths(git).map(|pending| {
let changes: Vec<String> = pending
.into_iter()
.filter(|path| !is_intent_path(path))
.collect();
let covered_off_disk = if !intent_from_disk || files.is_empty() {
Ok(Vec::new())
} else {
intent_in_head(git, workspace).map(|head_files| {
resting_on_uncommitted_intent(
&head_files,
&paths,
workspace,
files,
&classified,
&committed,
)
})
};
let mut everything = paths;
everything.extend(changes);
let if_committed = answer(&everything, workspace, files, &classified);
let already: BTreeSet<&PackageId> = committed.uncovered.iter().collect();
Worktree {
unseen: Unseen(
if_committed
.uncovered
.iter()
.filter(|id| !already.contains(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(
paths: &[String],
workspace: &Workspace,
files: &[BumpFile],
classified: &BTreeMap<PackageId, Standing>,
) -> Coverage {
let kept = packages_for(paths, workspace, &|id: &PackageId| {
classified.get(id) != Some(&Standing::Excluded)
});
let (managed, unmanaged): (Vec<PackageId>, Vec<PackageId>) = kept
.into_iter()
.partition(|id| classified.get(id) == Some(&Standing::Managed));
let managed: BTreeSet<PackageId> = managed.into_iter().collect();
let covered = covered_packages(files, &managed);
Coverage {
uncovered: managed
.into_iter()
.filter(|id| !covered.contains(id))
.collect(),
unmanaged,
}
}
fn covered_packages(files: &[BumpFile], changed: &BTreeSet<PackageId>) -> BTreeSet<PackageId> {
let mut covered = BTreeSet::new();
let mut empty_file = false;
for file in files {
if file.entries.is_empty() {
empty_file = true;
continue;
}
for (id, _) in &file.entries {
covered.insert(id.clone());
}
}
if empty_file {
covered.extend(changed.iter().cloned());
}
covered
}
fn changed_paths(git: &Git, from: Option<&str>) -> Result<Vec<String>, 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`",
));
}
let base = resolve_from_ref(git, from).map_err(CliError::from_boxed)?;
Ok(git
.paths(Op::ChangedPaths { from: &base })?
.into_iter()
.filter(|path| !is_intent_path(path))
.collect())
}
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 packages_for(
paths: &[String],
workspace: &Workspace,
kept: &impl Fn(&PackageId) -> bool,
) -> BTreeSet<PackageId> {
let dirs: Vec<(PackageId, String)> = workspace
.packages()
.map(|package| (package.id().clone(), package.manifest_dir().to_owned()))
.collect();
packages_for_paths(paths, &dirs)
.into_iter()
.filter(|id| kept(id))
.collect()
}
fn intent_in_head(git: &Git, workspace: &Workspace) -> Result<Vec<BumpFile>, CliError> {
let head = git.head()?;
let mut pairs: Vec<(String, String)> = Vec::new();
for path in git.paths(Op::TreePaths {
commit: &head,
dir: BUMP_DIR,
})? {
let Some(name) = bump_file_name(&path).filter(|name| is_bump_file_name(name)) else {
continue;
};
pairs.push((
name.to_owned(),
git.blob(Op::BlobText {
commit: &head,
path: &path,
})?,
));
}
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)
}
fn resting_on_uncommitted_intent(
head_files: &[BumpFile],
paths: &[String],
workspace: &Workspace,
files: &[BumpFile],
classified: &BTreeMap<PackageId, Standing>,
committed: &Coverage,
) -> Vec<OffDisk> {
let already: BTreeSet<&PackageId> = committed.uncovered.iter().collect();
answer(paths, workspace, head_files, classified)
.uncovered
.iter()
.filter(|id| !already.contains(id))
.map(|id| OffDisk {
package: id.clone(),
files: files
.iter()
.filter(|file| covers(file, id))
.map(|file| format!("{BUMP_DIR}/{}", file.id))
.collect(),
})
.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";
fn heard(stdout: &'static str) -> Result<Vec<String>, CliError> {
uncommitted_paths(&Git::answering([(STATUS, Reply::said(stdout))]))
}
#[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")),
(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 blob", Reply::failed(128, "fatal: bad object")),
]);
let workspace = Workspace::new([member("demo"), member("other")]).expect("workspace");
let files = [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, &files, Some("v0.1.0"), true, |_| {
Standing::Managed
})
.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("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 blob", Reply::said(body)),
]);
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 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")
}
#[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")),
(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, &[], Some("v0.1.0"), true, |_| {
Standing::Managed
})
.expect("the committed half still answers");
assert_eq!(
uncovered.committed.uncovered,
[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}"
);
}
}
}