use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use ostrya_core::{Checksum, ObjectType};
use crate::error::{Error, Result};
use crate::related::{self, RelationField};
use crate::repo::Repo;
use super::RefPlace;
use super::delta::{AttachmentLookup, complete_here_blocking};
#[derive(Default)]
pub(super) struct Attachments {
order: Vec<Checksum>,
named: HashMap<Checksum, (Checksum, String, usize)>,
naming: HashMap<Checksum, Vec<(String, Checksum)>>,
keys_only: bool,
}
impl Attachments {
pub(super) fn new(keys_only: bool) -> Self {
Self {
keys_only,
..Self::default()
}
}
pub(super) fn keys_only(&self) -> bool {
self.keys_only
}
pub(super) fn record(&mut self, commit: Checksum, attachments: Vec<(String, Checksum)>) {
self.insert(None, commit, attachments);
}
pub(super) fn record_at(
&mut self,
level: usize,
commit: Checksum,
attachments: Vec<(String, Checksum)>,
) {
self.insert(Some(level), commit, attachments);
}
fn insert(
&mut self,
level: Option<usize>,
commit: Checksum,
attachments: Vec<(String, Checksum)>,
) {
if attachments.is_empty() {
return;
}
let rank = level.unwrap_or(0);
for (name, attachment) in &attachments {
match self.named.entry(*attachment) {
Entry::Vacant(slot) => {
slot.insert((commit, name.clone(), rank));
self.order.push(*attachment);
}
Entry::Occupied(mut slot) => {
let (kept, _, kept_rank) = slot.get();
if level.is_some() && (rank, commit) < (*kept_rank, *kept) {
slot.insert((commit, name.clone(), rank));
}
}
}
}
let entries = if self.keys_only {
Vec::new()
} else {
attachments
};
self.naming.insert(commit, entries);
}
pub(super) fn order(&self) -> &[Checksum] {
&self.order
}
pub(super) fn named(&self, attachment: &Checksum) -> Option<(Checksum, &str)> {
self.named
.get(attachment)
.map(|(commit, name, _)| (*commit, name.as_str()))
}
pub(super) fn naming(&self) -> &HashMap<Checksum, Vec<(String, Checksum)>> {
&self.naming
}
pub(super) fn named_error(&self, attachment: &Checksum, end: &str) -> Option<Error> {
self.named(attachment)
.map(|(commit, name)| Error::InvalidRelations {
commit: Some(commit),
field: RelationField::Attachments,
reason: related::attachment_reason(name, attachment, end),
})
}
}
pub(super) struct Named {
pub(super) checksum: Checksum,
first: Option<usize>,
name: String,
pairs: Vec<(Pair, String)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Pair {
Target(usize),
Commit(Checksum),
}
pub(super) enum Level<'a> {
First,
Later(&'a [(Checksum, Option<Checksum>)]),
}
pub(super) fn pair_targets(
targets: &[(String, Checksum)],
depth: i32,
parents: &HashMap<Checksum, Option<Checksum>>,
naming: &HashMap<Checksum, Vec<(String, Checksum)>>,
level: &Level<'_>,
pending: Vec<Checksum>,
) -> Vec<Named> {
if pending.is_empty() {
return Vec::new();
}
let wanted: HashSet<Checksum> = pending.iter().copied().collect();
let mut out: Vec<Named> = Vec::new();
let mut position: HashMap<Checksum, usize> = HashMap::new();
let chains = match level {
Level::First => targets,
Level::Later(_) => &[],
};
for (target, (_, tip)) in chains.iter().enumerate() {
let mut commit = *tip;
let mut left = depth;
loop {
for (name, attachment) in naming.get(&commit).into_iter().flatten() {
if !wanted.contains(attachment) {
continue;
}
let at = *position.entry(*attachment).or_insert_with(|| {
out.push(Named {
checksum: *attachment,
first: Some(target),
name: name.clone(),
pairs: Vec::new(),
});
out.len() - 1
});
let named = &mut out[at];
let pair = Pair::Target(target);
if named.pairs.last().is_none_or(|(last, _)| *last != pair) {
named.pairs.push((pair, name.clone()));
}
}
if left == 0 {
break;
}
match parents.get(&commit) {
Some(Some(parent)) if parents.contains_key(parent) => commit = *parent,
_ => break,
}
if left > 0 {
left -= 1;
}
}
}
let outside: HashSet<Checksum> = pending
.iter()
.filter(|checksum| !position.contains_key(*checksum))
.copied()
.collect();
if outside.is_empty() {
return out;
}
let (all, above) = match level {
Level::First => (Some(naming), &[][..]),
Level::Later(above) => (None, *above),
};
let candidates = all.into_iter().flatten().chain(
above
.iter()
.filter_map(|(commit, _)| naming.get_key_value(commit)),
);
let mut names: HashMap<Checksum, (Checksum, &str)> = HashMap::new();
for (commit, entries) in candidates {
for (name, attachment) in entries {
if !outside.contains(attachment) {
continue;
}
let candidate = (*commit, name.as_str());
names
.entry(*attachment)
.and_modify(|lowest| *lowest = (*lowest).min(candidate))
.or_insert(candidate);
}
}
let mut pairs: HashMap<Checksum, Vec<(Pair, String)>> = HashMap::new();
let mut seen: HashSet<Checksum> = HashSet::new();
for (attachment, from) in above {
let Some(from) = from else {
continue;
};
seen.clear();
for (name, named) in naming.get(attachment).into_iter().flatten() {
if outside.contains(named) && seen.insert(*named) {
pairs
.entry(*named)
.or_default()
.push((Pair::Commit(*from), name.clone()));
}
}
}
for checksum in pending {
if !position.contains_key(&checksum) {
let name = names
.get(&checksum)
.map_or_else(String::new, |(_, name)| (*name).to_owned());
out.push(Named {
checksum,
first: None,
name,
pairs: pairs.remove(&checksum).unwrap_or_default(),
});
}
}
out
}
pub(super) async fn lookups(
repo: &Repo,
targets: &[(String, Checksum)],
place: RefPlace<'_>,
named: Vec<Named>,
checked: HashMap<Checksum, bool>,
) -> Result<(Vec<AttachmentLookup>, HashMap<Checksum, bool>)> {
if named.is_empty() {
return Ok((Vec::new(), checked));
}
let mut relpaths: Vec<Option<String>> = vec![None; targets.len()];
for (pair, _) in named.iter().flat_map(|named| &named.pairs) {
let Pair::Target(target) = *pair else {
continue;
};
let (name, tip) = &targets[target];
if relpaths[target].is_none() && *name != tip.to_hex() {
relpaths[target] = place.ref_path(name).ok();
}
}
let names: Vec<String> = targets.iter().map(|(name, _)| name.clone()).collect();
let repo = repo.clone();
ostrya_rt::unblock(move || {
let mut entries: Vec<Option<HashMap<String, Checksum>>> = Vec::with_capacity(names.len());
for relpath in &relpaths {
entries.push(match relpath {
Some(relpath) => held_entries(&repo, relpath)?,
None => None,
});
}
let mut complete = checked;
let mut is_complete = |commit: &Checksum| -> Result<bool> {
if let Some(held) = complete.get(commit) {
return Ok(*held);
}
let held = complete_here_blocking(&repo, commit)?;
complete.insert(*commit, held);
Ok(held)
};
let mut commits: HashMap<Checksum, Option<HashMap<String, Checksum>>> = HashMap::new();
let mut out = Vec::with_capacity(named.len());
for named in named {
if is_complete(&named.checksum)? {
continue;
}
let mut from = None;
for (pair, name) in &named.pairs {
let map = match pair {
Pair::Target(target) => entries[*target].as_ref(),
Pair::Commit(commit) => {
if !commits.contains_key(commit) {
commits.insert(*commit, commit_entries(&repo, commit)?);
}
commits[commit].as_ref()
}
};
if let Some(paired) = map.and_then(|map| map.get(name))
&& is_complete(paired)?
{
from = Some(*paired);
break;
}
}
let target = names
.get(named.first.unwrap_or(0))
.map_or("", String::as_str);
out.push(AttachmentLookup {
checksum: named.checksum,
subject: format!("{} of {target}", named.name),
from,
scratch: from.is_none(),
});
}
Ok((out, complete))
})
.await
}
fn held_entries(repo: &Repo, relpath: &str) -> Result<Option<HashMap<String, Checksum>>> {
let Some(tip) = repo.resolve_relpath_tip_blocking(relpath)? else {
return Ok(None);
};
commit_entries(repo, &tip)
}
fn commit_entries(repo: &Repo, commit: &Checksum) -> Result<Option<HashMap<String, Checksum>>> {
let Some(bytes) = repo.held_object_bytes_blocking(ObjectType::Commit, commit)? else {
return Ok(None);
};
let Ok(entries) = related::parse_attachments(&bytes).and_then(|entries| {
related::checked_entries(RelationField::Attachments, Some(*commit), entries)
}) else {
return Ok(None);
};
let mut map = HashMap::with_capacity(entries.len());
for (name, checksum) in entries {
map.entry(name).or_insert(checksum);
}
Ok(Some(map))
}
#[cfg(test)]
mod tests {
use super::Pair::Target;
use super::*;
fn cs(byte: u8) -> Checksum {
Checksum::from_bytes([byte; 32])
}
fn entries(list: &[(&str, u8)]) -> Vec<(String, Checksum)> {
list.iter()
.map(|(name, byte)| ((*name).to_owned(), cs(*byte)))
.collect()
}
fn pending(list: &[u8]) -> Vec<Checksum> {
list.iter().map(|byte| cs(*byte)).collect()
}
#[test]
fn attachments_keep_the_first_naming_commit() {
let mut atts = Attachments::new(false);
atts.record(cs(1), entries(&[("boot/uki", 3)]));
atts.record(cs(2), entries(&[("lib/uki", 3), ("lib/c", 4)]));
atts.record(cs(5), Vec::new());
assert!(!atts.keys_only());
assert_eq!(atts.order(), [cs(3), cs(4)]);
assert_eq!(atts.named(&cs(3)), Some((cs(1), "boot/uki")));
assert_eq!(atts.named(&cs(4)), Some((cs(2), "lib/c")));
assert_eq!(atts.named(&cs(5)), None);
let mut naming: Vec<&Checksum> = atts.naming().keys().collect();
naming.sort_unstable();
assert_eq!(naming, [&cs(1), &cs(2)]);
assert_eq!(atts.naming()[&cs(2)][1], ("lib/c".to_owned(), cs(4)));
}
#[test]
fn attachments_keep_the_commits_alone_under_keys_only() {
let mut atts = Attachments::new(true);
atts.record(cs(1), entries(&[("boot/uki", 3)]));
atts.record(cs(2), entries(&[("lib/c", 4), ("lib/uki", 3)]));
atts.record(cs(5), Vec::new());
assert!(atts.keys_only());
assert_eq!(atts.order(), [cs(3), cs(4)]);
assert_eq!(atts.named(&cs(3)), Some((cs(1), "boot/uki")));
let mut naming: Vec<&Checksum> = atts.naming().keys().collect();
naming.sort_unstable();
assert_eq!(naming, [&cs(1), &cs(2)]);
assert!(atts.naming().values().all(Vec::is_empty));
}
#[test]
fn an_attachment_error_names_the_first_naming_commit() {
let mut atts = Attachments::new(false);
atts.record(cs(1), entries(&[("lib/b", 2)]));
atts.record(cs(3), entries(&[("lib/x", 2)]));
let reason = |err: Option<Error>| match err {
Some(Error::InvalidRelations {
commit,
field: RelationField::Attachments,
reason,
}) => (commit, reason),
other => panic!("expected InvalidRelations in field 2, got {other:?}"),
};
assert_eq!(
reason(atts.named_error(&cs(2), related::UNHELD_REASON)),
(
Some(cs(1)),
format!(
"attachment lib/b names commit {}, which neither a source nor this \
repository holds",
cs(2)
)
)
);
assert!(atts.named_error(&cs(4), related::UNHELD_REASON).is_none());
}
type Flat<'a> = (u8, Option<usize>, &'a str, Vec<(Pair, &'a str)>);
fn flat(named: &[Named]) -> Vec<Flat<'_>> {
named
.iter()
.map(|named| {
(
named.checksum.as_bytes()[0],
named.first,
named.name.as_str(),
named
.pairs
.iter()
.map(|(pair, name)| (*pair, name.as_str()))
.collect(),
)
})
.collect()
}
#[test]
fn the_first_target_names_an_attachment_first() {
let targets = vec![("one".to_owned(), cs(1)), ("two".to_owned(), cs(2))];
let parents = HashMap::from([(cs(1), None), (cs(2), None), (cs(5), None)]);
let naming = HashMap::from([
(cs(1), entries(&[("boot/a", 9)])),
(cs(2), entries(&[("boot/b", 9), ("boot/c", 8)])),
(cs(5), entries(&[("lib/x", 7)])),
]);
let named = pair_targets(
&targets,
0,
&parents,
&naming,
&Level::First,
pending(&[7, 8, 9]),
);
assert_eq!(
flat(&named),
[
(
9,
Some(0),
"boot/a",
vec![(Target(0), "boot/a"), (Target(1), "boot/b")]
),
(8, Some(1), "boot/c", vec![(Target(1), "boot/c")]),
(7, None, "lib/x", vec![]),
]
);
assert!(pair_targets(&targets, 0, &parents, &naming, &Level::First, Vec::new()).is_empty());
}
#[test]
fn an_attachment_outside_every_chain_takes_the_lowest_name() {
let targets = vec![("main".to_owned(), cs(1))];
let parents = HashMap::from([(cs(1), None)]);
let records = [
(cs(6), entries(&[("lib/f", 9)])),
(cs(4), entries(&[("lib/z", 9), ("lib/d", 9)])),
(cs(5), entries(&[("lib/a", 9)])),
];
for order in [[0, 1, 2], [2, 1, 0], [1, 2, 0]] {
let mut naming = HashMap::new();
for at in order {
naming.insert(records[at].0, records[at].1.clone());
}
let named = pair_targets(
&targets,
-1,
&parents,
&naming,
&Level::First,
pending(&[9]),
);
assert_eq!(flat(&named), [(9, None, "lib/d", vec![])]);
}
}
#[test]
fn a_nested_attachment_pairs_with_field_2_of_the_paired_commit() {
let targets = vec![("main".to_owned(), cs(1))];
let parents = HashMap::from([(cs(1), None), (cs(2), None), (cs(3), None), (cs(4), None)]);
let naming = HashMap::from([
(
cs(1),
entries(&[("lib/d1", 2), ("lib/d2", 3), ("lib/d3", 4)]),
),
(cs(2), entries(&[("x/one", 9), ("x/dup", 9)])),
(cs(3), entries(&[("x/two", 9), ("y/two", 8)])),
(cs(4), entries(&[("x/three", 9)])),
]);
let above = [(cs(3), Some(cs(30))), (cs(4), None), (cs(2), Some(cs(20)))];
let named = pair_targets(
&targets,
0,
&parents,
&naming,
&Level::Later(&above),
pending(&[8, 9]),
);
assert_eq!(
flat(&named),
[
(8, None, "y/two", vec![(Pair::Commit(cs(30)), "y/two")]),
(
9,
None,
"x/dup",
vec![
(Pair::Commit(cs(30)), "x/two"),
(Pair::Commit(cs(20)), "x/one")
]
),
]
);
}
#[test]
fn the_walk_keeps_to_the_depth_and_the_reached_parents() {
let targets = vec![("main".to_owned(), cs(1))];
let parents = HashMap::from([
(cs(1), Some(cs(2))),
(cs(2), Some(cs(3))),
(cs(3), Some(cs(4))),
]);
let naming = HashMap::from([
(cs(1), entries(&[("boot/new", 9)])),
(cs(2), entries(&[("boot/old", 9), ("boot/two", 8)])),
(cs(3), entries(&[("boot/three", 7)])),
(cs(4), entries(&[("boot/four", 6)])),
]);
let all = pending(&[6, 7, 8, 9]);
let at = |depth| {
flat(&pair_targets(
&targets,
depth,
&parents,
&naming,
&Level::First,
all.clone(),
))
.into_iter()
.map(|(byte, first, _, pairs)| (byte, first, pairs.len()))
.collect::<Vec<_>>()
};
assert_eq!(
flat(&pair_targets(
&targets,
1,
&parents,
&naming,
&Level::First,
all.clone()
))[0],
(9, Some(0), "boot/new", vec![(Target(0), "boot/new")])
);
assert_eq!(
at(0),
[(9, Some(0), 1), (6, None, 0), (7, None, 0), (8, None, 0)]
);
assert_eq!(
at(1),
[(9, Some(0), 1), (8, Some(0), 1), (6, None, 0), (7, None, 0)]
);
for depth in [-1, 5] {
assert_eq!(
at(depth),
[
(9, Some(0), 1),
(8, Some(0), 1),
(7, Some(0), 1),
(6, None, 0)
]
);
}
}
}