use std::{
collections::{BTreeMap, BTreeSet},
fs,
};
use super::{
eol::{is_base, keep_ending, normalise, same_text},
git, landing,
lock::{Accepted, Lock, LockedFile, LockedPack, base_path, hash_of},
manifest::{requires_newer, tool_version},
mode::{carries_mode, file_is_executable},
owner::{Ownership, Supply},
source::{FILES, PackFiles, Source, destination},
};
use crate::{
Error, RepoPath, RepoRoot, Result, Source as TextSource,
check::conflict_lines,
model::{Document, ParseMode, SchemaDocument, parse_source},
};
#[derive(Debug, Clone)]
pub struct Fetched {
pub pack: PackFiles,
pub source: Source,
pub git_ref: Option<String>,
pub path: Option<String>,
pub commit: String,
pub offline: bool,
}
impl Fetched {
pub fn version(&self) -> String {
match self.source {
Source::Builtin(_) if !self.offline => tool_version().to_string(),
_ => self.pack.manifest.version.clone(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FileAction {
Added,
Updated,
Merged,
Conflicted,
KeptExisting,
Removed,
Kept,
Overridden,
Deleted,
}
impl FileAction {
pub fn label(self) -> &'static str {
match self {
FileAction::Added => "added",
FileAction::Updated => "updated",
FileAction::Merged => "merged",
FileAction::Conflicted => "conflicted",
FileAction::KeptExisting => "kept-existing",
FileAction::Removed => "removed",
FileAction::Kept => "kept",
FileAction::Overridden => "overridden",
FileAction::Deleted => "deleted",
}
}
}
#[derive(Debug, Clone)]
pub struct PackPlan {
pub name: String,
pub entry: LockedPack,
pub actions: Vec<(RepoPath, FileAction)>,
pub writes: Vec<(RepoPath, Vec<u8>)>,
pub deletes: Vec<RepoPath>,
pub modes: Vec<(RepoPath, bool)>,
pub notes: Vec<String>,
}
#[derive(Debug, Clone, Default)]
pub struct Request {
pub store: Option<RepoPath>,
pub keep_existing: bool,
pub roots: Vec<RepoPath>,
pub protected: landing::Protected,
pub vacated: BTreeSet<RepoPath>,
}
pub fn schema_type(path: &RepoPath, bytes: &[u8]) -> Option<String> {
let source = TextSource::from_text(path.clone(), &String::from_utf8_lossy(bytes));
let parsed = parse_source(&source, ParseMode::Document);
SchemaDocument::new(Document::new(source, parsed)).type_const
}
pub fn locked_types(root: &RepoRoot, lock: &Lock) -> BTreeMap<String, BTreeSet<String>> {
lock.packs
.iter()
.map(|(name, pack)| {
let types = pack
.files
.keys()
.filter(|rel| rel.starts_with("schemas/"))
.filter_map(|rel| {
let base = base_path(name, rel);
let bytes = fs::read(base.to_fs(root)).ok()?;
schema_type(&base, &bytes)
})
.collect();
(name.clone(), types)
})
.collect()
}
pub fn store_of(lock: &Lock, fetched: &Fetched, request: &Request) -> Result<Option<RepoPath>> {
let name = &fetched.pack.manifest.name;
let fail = |m: String| Error::Pack(format!("{name}: {m}"));
let needs_store = fetched
.pack
.files
.keys()
.any(|rel| rel.starts_with("schemas/") || rel.starts_with("documents/"));
if !needs_store {
return Ok(None);
}
let locked_store = lock.packs.get(name).and_then(|e| e.store.as_deref());
Ok(Some(match (&request.store, locked_store) {
(Some(s), Some(e)) if s.as_str() != e => {
return Err(fail(format!(
"the lock holds this pack in the store {e}, not {s}"
)));
}
(Some(s), _) => s.clone(),
(None, Some(e)) => RepoPath::parse(e)
.ok_or_else(|| fail(format!("the lock's store `{e}` is not a path")))?,
(None, None) => RepoPath::parse("/knowledge").expect("literal"),
}))
}
pub fn supply(fetched: &Fetched, store: Option<&RepoPath>) -> Supply {
let name = &fetched.pack.manifest.name;
let files = fetched
.pack
.files
.iter()
.filter_map(|(rel, bytes)| {
let dest = RepoPath::parse(&destination(name, store.map(RepoPath::as_str), rel)?)?;
let ty = rel
.starts_with("schemas/")
.then(|| schema_type(&dest, bytes))
.flatten();
Some((dest, ty))
})
.collect();
Supply {
store: store.cloned(),
files,
}
}
pub fn plan(
root: &RepoRoot,
lock: &Lock,
fetched: &Fetched,
request: &Request,
own: &Ownership,
) -> Result<PackPlan> {
let manifest = &fetched.pack.manifest;
let name = manifest.name.clone();
let fail = |m: String| Error::Pack(format!("{name}: {m}"));
if requires_newer(&manifest.requires_sokf, tool_version()) {
return Err(fail(format!(
"the pack requires sokf {}, and this is sokf {}; upgrade sokf",
manifest.requires_sokf,
tool_version()
)));
}
let existing = lock.packs.get(&name);
let label = fetched.source.label();
let refused = landing::check(&fetched.pack, &request.roots, &request.protected);
if !refused.is_empty() {
return Err(fail(refused.join("; ")));
}
let store = store_of(lock, fetched, request)?;
if let Some(store) = &store {
let has_manifest = store
.join("manifest.sokf.yaml")
.is_some_and(|m| m.to_fs(root).is_file());
if !has_manifest {
return Err(fail(format!(
"{store} is not a knowledge store; create it with `sokf init`"
)));
}
}
let mut out = PackPlan {
name: name.clone(),
entry: LockedPack {
source: label,
git_ref: fetched.git_ref.clone(),
path: fetched.path.clone(),
store: store.as_ref().map(|s| s.as_str().to_string()),
commit: fetched.commit.clone(),
version: fetched.version(),
depends: manifest.depends.clone(),
files: BTreeMap::new(),
},
actions: Vec::new(),
writes: Vec::new(),
deletes: Vec::new(),
modes: Vec::new(),
notes: Vec::new(),
};
let mut unrecorded = Vec::new();
let mut conflicted = Vec::new();
for (rel, upstream) in &fetched.pack.files {
let Some(dest) = destination(&name, store.as_ref().map(RepoPath::as_str), rel) else {
continue;
};
let dest = RepoPath::parse(&dest).ok_or_else(|| fail(format!("{rel}: not a path")))?;
let current = if request.vacated.contains(&dest) {
None
} else {
fs::read(dest.to_fs(root)).ok()
};
let old = existing.and_then(|e| e.files.get(rel));
let executable = rel.starts_with(FILES) && fetched.pack.executable.contains(rel);
if let Some(shadow) = own.shadowed.get(&dest) {
let changed = old.is_some_and(|f| f.base != hash_of(upstream));
let wrote = old.is_some_and(|f| f.shadowed_by.is_none());
if wrote && old.is_some_and(|f| f.accepted.is_some()) {
out.notes.push(format!(
"note: the pack {} now owns {dest}, so the acceptance of its edit is dropped; accept it again if the project keeps the edit",
shadow.owner
));
}
let action = match (¤t, old) {
(Some(cur), Some(f)) if shadow.by_type && wrote => {
if is_base(cur, &f.base) {
out.deletes.push(dest.clone());
Some(FileAction::Removed)
} else {
Some(FileAction::Kept)
}
}
_ => changed.then(|| {
out.notes.push(format!(
"note: the pack {name} changed {dest}, which the pack {} overrides; check whether its version needs the change too",
shadow.owner
));
FileAction::Overridden
}),
};
if let Some(action) = action {
out.actions.push((dest.clone(), action));
}
out.entry.files.insert(
rel.clone(),
LockedFile {
path: dest.as_str().to_string(),
base: hash_of(upstream),
executable,
shadowed_by: Some(shadow.owner.clone()),
changed,
accepted: None,
},
);
let base = base_path(&name, rel);
if !fs::read(base.to_fs(root)).is_ok_and(|b| same_text(&b, upstream)) {
out.writes.push((base, upstream.clone()));
}
continue;
}
let recorded = old.filter(|f| f.shadowed_by.is_none());
let takeover = own.takeover.get(&dest);
let mode = carries_mode(rel)
.then(|| match takeover {
Some(t) if current.is_some() => {
let bit = file_is_executable(&dest.to_fs(root));
Some(if bit == t.executable { executable } else { bit })
}
_ => file_mode(recorded, current.is_some(), executable, &dest, root),
})
.flatten();
if (recorded.is_some() || takeover.is_some())
&& current
.as_ref()
.is_some_and(|c| !conflict_lines(&dest, &String::from_utf8_lossy(c)).is_empty())
{
conflicted.push(dest.to_string());
}
let before = current.clone();
let was = recorded.and_then(|f| f.accepted.clone());
let held = was.as_ref().is_some_and(|a| {
let bit = (carries_mode(rel) && before.is_some())
.then(|| file_is_executable(&dest.to_fs(root)));
a.holds(before.as_deref(), bit)
});
if takeover.is_some_and(|t| t.accepted) {
out.notes.push(format!(
"note: the pack {name} now owns {dest}, so the acceptance of its edit is dropped; accept it again if the project keeps the edit"
));
}
let action = match (recorded, current) {
(_, Some(cur)) if let Some(t) = takeover => {
if is_base(&cur, &t.base) {
if same_text(&cur, upstream) {
None
} else {
out.writes
.push((dest.clone(), keep_ending(&cur, upstream.clone())));
Some(FileAction::Updated)
}
} else {
let base_copy = base_path(&t.from, &t.rel);
let base = fs::read(base_copy.to_fs(root)).map_err(|_| {
fail(format!(
"{dest}: the base copy {base_copy} of the pack {} is missing, so the sync can't merge this pack's version into the edited file; restore the base copy from git",
t.from
))
})?;
let merge = git::merge_file(
&normalise(&cur),
&normalise(&base),
&normalise(upstream),
dest.as_str(),
)?;
out.writes
.push((dest.clone(), keep_ending(&cur, merge.text)));
Some(if merge.conflicted {
FileAction::Conflicted
} else {
FileAction::Merged
})
}
}
(Some(_), None) => Some(FileAction::Deleted),
(None, None) if takeover.is_some() => Some(FileAction::Deleted),
(None, None) => {
out.writes.push((dest.clone(), upstream.clone()));
Some(FileAction::Added)
}
(None, Some(cur)) => {
let same = same_text(&cur, upstream)
&& (!carries_mode(rel) || file_is_executable(&dest.to_fs(root)) == executable);
if !same && !request.keep_existing {
unrecorded.push(dest.to_string());
}
(!same).then_some(FileAction::KeptExisting)
}
(Some(f), Some(cur)) if is_base(&cur, &f.base) => {
if same_text(&cur, upstream) {
None
} else {
out.writes
.push((dest.clone(), keep_ending(&cur, upstream.clone())));
Some(FileAction::Updated)
}
}
(Some(f), Some(cur)) => {
if hash_of(upstream) == f.base || same_text(&cur, upstream) {
None
} else {
let base_copy = base_path(&name, rel);
let base = fs::read(base_copy.to_fs(root)).map_err(|_| {
fail(format!(
"{dest}: the base copy {base_copy} is missing, so the sync can't merge the pack's change into the edited file; restore the base copy from git, or run `sokf pack remove {name}` and then `sokf pack add` with --keep-existing, which records the edited file as an edit of the pack's version"
))
})?;
let merge = git::merge_file(
&normalise(&cur),
&normalise(&base),
&normalise(upstream),
dest.as_str(),
)?;
out.writes
.push((dest.clone(), keep_ending(&cur, merge.text)));
Some(if merge.conflicted {
FileAction::Conflicted
} else {
FileAction::Merged
})
}
}
};
let written = out.writes.last().is_some_and(|(p, _)| *p == dest);
let action = match mode {
Some(m) if written || m != file_is_executable(&dest.to_fs(root)) => {
out.modes.push((dest.clone(), m));
action.or(Some(FileAction::Updated))
}
_ => action,
};
if let Some(action) = action {
out.actions.push((dest.clone(), action));
}
let after = if written {
out.writes.last().map(|(_, b)| b.clone())
} else {
before
};
let accepted = was.and_then(|a| {
follow_acceptance(
a,
&Followed {
dest: &dest,
action,
held,
after: after.as_deref(),
bit: mode,
upstream,
executable,
changed: recorded.is_some_and(|f| f.base != hash_of(upstream)),
},
&mut out.notes,
)
});
out.entry.files.insert(
rel.clone(),
LockedFile {
path: dest.as_str().to_string(),
base: hash_of(upstream),
executable,
shadowed_by: None,
changed: false,
accepted,
},
);
let base = base_path(&name, rel);
if !fs::read(base.to_fs(root)).is_ok_and(|b| same_text(&b, upstream)) {
out.writes.push((base, upstream.clone()));
}
}
if !conflicted.is_empty() {
return Err(fail(format!(
"a file of the pack holds a conflict that an earlier sync left: {}; resolve it, then sync again",
conflicted.join(", ")
)));
}
if !unrecorded.is_empty() {
return Err(fail(format!(
"the pack's files land on files that the lock doesn't record: {}; delete a file to take the pack's version, or pass --keep-existing to keep each as an edit of the pack's version",
unrecorded.join(", ")
)));
}
if let Some(e) = existing {
for (rel, f) in &e.files {
if out.entry.files.contains_key(rel) {
continue;
}
out.deletes.push(base_path(&name, rel));
let Some(dest) = RepoPath::parse(&f.path) else {
continue;
};
match fs::read(dest.to_fs(root)) {
Ok(cur) if is_base(&cur, &f.base) => {
out.deletes.push(dest.clone());
out.actions.push((dest, FileAction::Removed));
}
Ok(_) => out.actions.push((dest, FileAction::Kept)),
Err(_) => {}
}
}
}
out.actions.sort();
Ok(out)
}
struct Followed<'a> {
dest: &'a RepoPath,
action: Option<FileAction>,
held: bool,
after: Option<&'a [u8]>,
bit: Option<bool>,
upstream: &'a [u8],
executable: bool,
changed: bool,
}
fn follow_acceptance(
accepted: Accepted,
f: &Followed,
notes: &mut Vec<String>,
) -> Option<Accepted> {
let dest = f.dest;
let holds_base = f.after.is_some_and(|b| same_text(b, f.upstream))
&& f.bit.is_none_or(|b| b == f.executable);
if holds_base {
return None;
}
match f.action {
Some(FileAction::Conflicted) => {
notes.push(format!(
"note: the merge into {dest} conflicts, so its acceptance is dropped; accept it again with `sokf pack accept` after you resolve the conflict"
));
None
}
Some(FileAction::Merged) if !f.held => {
notes.push(format!(
"note: the sync merged the pack's change into {dest}, which changed since its acceptance, so the acceptance is dropped"
));
None
}
_ => {
if accepted.deleted && f.after.is_none() && f.changed {
notes.push(format!(
"note: the pack changed {dest}, whose deletion is accepted; the file stays deleted"
));
}
Some(if f.held {
Accepted::of(f.after, f.bit.unwrap_or(false), &accepted.note)
} else {
accepted
})
}
}
}
fn file_mode(
recorded: Option<&LockedFile>,
exists: bool,
executable: bool,
dest: &RepoPath,
root: &RepoRoot,
) -> Option<bool> {
let current = file_is_executable(&dest.to_fs(root));
match (recorded, exists) {
(Some(_), false) => None,
(None, false) => Some(executable),
(Some(f), true) if f.executable == current => Some(executable),
(_, true) => Some(current),
}
}