use std::{
collections::BTreeSet,
fs,
path::{Path, PathBuf},
};
use serde::Serialize;
use super::pack::{SyncedPack, edited_files, holds_accepted, remove};
use crate::{
Error, RepoPath, RepoRoot, Result, check, config,
pack::{self, EMBEDDED, EmbeddedPack},
source::read_optional,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PackFileState {
Edited,
Conflicted,
Deleted,
Accepted,
}
impl PackFileState {
pub fn label(self) -> &'static str {
match self {
PackFileState::Edited => "edited",
PackFileState::Conflicted => "conflicted",
PackFileState::Deleted => "deleted",
PackFileState::Accepted => "accepted",
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PackState {
pub name: String,
pub version: String,
pub source: String,
pub git_ref: Option<String>,
pub stale: Option<String>,
pub files: Vec<PackFile>,
pub shadowed: Vec<ShadowedFile>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PackFile {
pub path: String,
pub state: PackFileState,
pub note: Option<String>,
pub changed_since_acceptance: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct ShadowedFile {
pub path: String,
pub owner: String,
pub changed: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct PackStatus {
pub packs: Vec<PackState>,
}
impl PackStatus {
pub fn drifted(&self) -> bool {
self.packs
.iter()
.any(|p| p.files.iter().any(|f| f.state != PackFileState::Accepted))
}
pub fn to_text(&self) -> String {
if self.packs.is_empty() {
return "the lock holds no pack\n".into();
}
let mut out = String::new();
for p in &self.packs {
let source = match &p.git_ref {
Some(r) => format!("{}@{r}", p.source),
None => p.source.clone(),
};
out.push_str(&format!("{} {} from {source}", p.name, p.version));
match &p.stale {
Some(why) => out.push_str(&format!(": stale, {why}\n")),
None => out.push('\n'),
}
for f in &p.files {
let tail = match (&f.note, f.state) {
(Some(note), PackFileState::Accepted) => format!(": {note}"),
_ if f.changed_since_acceptance => ", changed since its acceptance".into(),
_ => String::new(),
};
out.push_str(&format!("{} {}{tail}\n", f.state.label(), f.path));
}
for f in &p.shadowed {
let changed = if f.changed {
", changed in this pack at the last sync"
} else {
""
};
out.push_str(&format!(
"shadowed {} by the pack {}{changed}\n",
f.path, f.owner
));
}
}
out
}
}
pub fn pack_status(root: &RepoRoot) -> Result<PackStatus> {
let lock = pack::read_lock(root)?;
let tool = pack::tool_version();
let packs = pack::ordered(root, &lock)
.into_iter()
.filter_map(|name| lock.packs.get(&name).map(|p| (name, p)))
.map(|(name, p)| {
let edited = edited_files(root, p);
let mut files: Vec<PackFile> = p
.files
.iter()
.filter(|(_, f)| edited.contains(&f.path))
.map(|(rel, f)| {
let text = RepoPath::parse(&f.path)
.and_then(|rp| fs::read_to_string(rp.to_fs(root)).ok().map(|t| (rp, t)));
let held = holds_accepted(root, rel, f);
let state = match text {
_ if held => PackFileState::Accepted,
None => PackFileState::Deleted,
Some((rp, t)) if !check::conflict_lines(&rp, &t).is_empty() => {
PackFileState::Conflicted
}
Some(_) => PackFileState::Edited,
};
PackFile {
path: f.path.clone(),
state,
note: f.accepted.as_ref().map(|a| a.note.clone()),
changed_since_acceptance: f.accepted.is_some() && !held,
}
})
.collect();
files.sort_by(|a, b| {
let accepted = |f: &PackFile| f.state == PackFileState::Accepted;
(accepted(a), &a.path).cmp(&(accepted(b), &b.path))
});
let builtin = p.source.starts_with(pack::BUILTIN);
let stale = (builtin && p.version != tool).then(|| {
format!(
"this is sokf {tool}; run `sokf pack sync` to sync the pack of this release"
)
});
let shadowed = p
.files
.values()
.filter_map(|f| {
let owner = f.shadowed_by.clone()?;
Some((f, owner))
})
.map(|(f, owner)| ShadowedFile {
owner,
path: f.path.clone(),
changed: f.changed,
})
.collect();
PackState {
name,
version: p.version.clone(),
source: p.source.clone(),
git_ref: p.git_ref.clone(),
stale,
files,
shadowed,
}
})
.collect();
Ok(PackStatus { packs })
}
#[derive(Debug, Clone, Serialize)]
pub struct ListedPack {
pub name: String,
pub version: String,
pub description: String,
pub locked: bool,
}
pub fn list_text(packs: &[ListedPack]) -> String {
if packs.is_empty() {
return "the binary embeds no pack\n".into();
}
packs
.iter()
.map(|p| {
let mark = if p.locked { " (synced)" } else { "" };
format!("{} {}{mark}: {}\n", p.name, p.version, p.description)
})
.collect()
}
pub fn pack_list(root: Option<&RepoRoot>) -> Result<Vec<ListedPack>> {
pack_list_with(root, EMBEDDED)
}
pub fn pack_list_with(
root: Option<&RepoRoot>,
embedded: &[EmbeddedPack],
) -> Result<Vec<ListedPack>> {
let lock = match root {
Some(r) => pack::read_lock(r)?,
None => pack::Lock::default(),
};
Ok(pack::embedded_packs(embedded)?
.into_iter()
.map(|m| ListedPack {
locked: lock
.packs
.get(&m.name)
.is_some_and(|p| p.source == format!("{}{}", pack::BUILTIN, m.name)),
name: m.name,
version: m.version,
description: m.description,
})
.collect())
}
#[derive(Debug, Clone, Serialize)]
pub struct PackRemoved {
pub name: String,
pub undeclared: bool,
pub locked: bool,
pub removed: Vec<String>,
pub kept: Vec<String>,
pub handed: Vec<SyncedPack>,
pub instructions: Vec<String>,
}
impl PackRemoved {
pub fn conflicted(&self) -> bool {
self.handed.iter().any(|p| {
p.files
.iter()
.any(|(_, a)| *a == pack::FileAction::Conflicted)
})
}
pub fn to_text(&self) -> String {
let mut out = String::new();
for p in &self.removed {
out.push_str(&format!("removed {p}\n"));
}
for p in &self.kept {
out.push_str(&format!("kept {p}: edited\n"));
}
if self.undeclared {
out.push_str(&format!(
"removed the pack {} from /.sokf/config.toml\n",
self.name
));
}
if self.locked {
out.push_str(&format!("removed the pack {} from the lock\n", self.name));
}
for p in &self.handed {
for (path, action) in &p.files {
out.push_str(&format!(
"{} {path}: from the pack {}\n",
action.label(),
p.name
));
}
for note in &p.notes {
out.push_str(&format!("{note}\n"));
}
}
for line in &self.instructions {
out.push_str(&format!("{line}\n"));
}
out.push_str("note: run `sokf validate --fix` to bring the store's indexes up to date\n");
out
}
}
fn locked(root: &RepoRoot, name: &str) -> Result<(pack::Lock, pack::LockedPack)> {
let lock = pack::read_lock(root)?;
let entry = lock.packs.get(name).cloned().ok_or_else(|| {
let names: Vec<&str> = lock.packs.keys().map(String::as_str).collect();
Error::Pack(format!(
"the lock holds no pack named `{name}`; it holds {}",
if names.is_empty() {
"none".to_string()
} else {
names.join(", ")
}
))
})?;
Ok((lock, entry))
}
#[derive(Debug, Clone, Default)]
pub(super) struct Removal {
pub deletes: Vec<RepoPath>,
pub removed: Vec<String>,
pub kept: Vec<String>,
}
pub(super) fn plan_removal(
root: &RepoRoot,
name: &str,
entry: &pack::LockedPack,
supplied: &BTreeSet<RepoPath>,
) -> Removal {
let edited = edited_files(root, entry);
let mut out = Removal::default();
for (rel, f) in &entry.files {
let Some(p) = RepoPath::parse(&f.path) else {
continue;
};
if f.shadowed_by.is_some() || supplied.contains(&p) {
out.deletes.push(pack::base_path(name, rel));
continue;
}
let exists = p.to_fs(root).exists();
if edited.contains(&f.path) {
if exists {
out.kept.push(f.path.clone());
}
} else {
if exists {
out.removed.push(f.path.clone());
}
out.deletes.push(p);
}
out.deletes.push(pack::base_path(name, rel));
}
out
}
pub(super) fn apply_removal(root: &RepoRoot, removal: &Removal) -> Result<()> {
for p in &removal.deletes {
remove(root, p)?;
}
Ok(())
}
pub fn pack_remove(root: &RepoRoot, name: &str, home: Option<PathBuf>) -> Result<PackRemoved> {
let config_path = config::config_path();
let text = read_optional(&config_path.to_fs(root))?;
let config = match &text {
Some(t) => config::remove_entry(t, name)?,
None => None,
};
let lock = pack::read_lock(root)?;
let locked = lock.packs.contains_key(name);
if config.is_none() && !locked {
self::locked(root, name)?;
}
let dependents = super::pack_run::dependents(&lock, name);
if !dependents.is_empty() {
return Err(Error::Pack(format!(
"{name}: the pack {} depends on it; remove that pack first",
dependents.join(", ")
)));
}
let entries: Vec<config::PackEntry> = config::read_packs(root)?
.into_iter()
.filter(|e| e.name != name)
.collect();
let report = super::pack_run::run(
root,
&super::pack_run::Run {
entries: &entries,
fetching: super::pack_run::Fetching::Nothing,
remove_only: Some(name),
keep_existing: false,
home: &home,
config: config.clone(),
},
None,
&[],
)?;
let (removed, kept) = report
.undeclared
.into_iter()
.find(|u| u.name == name)
.map(|u| (u.removed, u.kept))
.unwrap_or_default();
Ok(PackRemoved {
name: name.to_string(),
undeclared: config.is_some(),
locked,
removed,
kept,
handed: report.packs,
instructions: report.instructions,
})
}
#[derive(Debug, Clone, Default)]
pub struct PackDiffOptions {
pub name: String,
pub accepted: bool,
pub new: Vec<String>,
pub cwd: PathBuf,
pub home: Option<PathBuf>,
}
pub fn pack_diff(root: &RepoRoot, options: &PackDiffOptions) -> Result<String> {
let name = options.name.as_str();
let (lock, entry) = locked(root, name)?;
let new = new_files(root, &lock, &entry, options)?;
let edited = edited_files(root, &entry);
let mut out = String::new();
for (rel, f) in &entry.files {
if !edited.contains(&f.path) || (!options.accepted && holds_accepted(root, rel, f)) {
continue;
}
let base_path = pack::base_path(name, rel).to_fs(root);
let base = fs::read(&base_path).map_err(|e| Error::io(&base_path, e))?;
let dest = RepoPath::parse(&f.path).map(|p| p.to_fs(root));
let current = dest.as_ref().and_then(|p| fs::read(p).ok());
let current = current.as_deref().map(pack::normalise);
let modes = dest
.as_deref()
.filter(|_| pack::carries_mode(rel))
.map(|p| (f.executable, pack::file_is_executable(p)));
out.push_str(&pack::diff_modes(
rel,
Some(&pack::normalise(&base)),
current.as_deref(),
modes,
)?);
}
for n in &new {
let modes = pack::carries_mode(&n.rel).then_some((false, n.executable));
out.push_str(&pack::diff_modes(
&n.rel,
None,
Some(&pack::normalise(&n.bytes)),
modes,
)?);
}
Ok(out)
}
struct NewFile {
rel: String,
bytes: Vec<u8>,
executable: bool,
}
fn new_files(
root: &RepoRoot,
lock: &pack::Lock,
entry: &pack::LockedPack,
options: &PackDiffOptions,
) -> Result<Vec<NewFile>> {
if options.new.is_empty() {
return Ok(Vec::new());
}
let config_roots = config::read_lenient(root)?.roots;
let roots: Vec<&str> = config_roots.iter().map(RepoPath::as_str).collect();
let dirs = super::pack::harness_dirs(root, &options.home);
let protected = super::harness_packs::written_paths(&dirs)?;
let mut refused = Vec::new();
let mut out: Vec<NewFile> = Vec::new();
let mut seen = BTreeSet::new();
for arg in &options.new {
let Some(dest) = config::PathArg(arg).resolve_new(root, &options.cwd) else {
refused.push(format!("{arg}: not a path in the repository"));
continue;
};
if !seen.insert(dest.clone()) {
continue;
}
let recorded = lock.packs.iter().find_map(|(owner, p)| {
p.files
.values()
.any(|f| f.path == dest.as_str())
.then_some(owner)
});
if let Some(owner) = recorded {
refused.push(format!(
"{dest}: the pack {owner} records the file already, so the patch carries its edits"
));
continue;
}
let rel = match pack::origin(&options.name, entry.store.as_deref(), &roots, dest.as_str()) {
Ok(rel) => rel,
Err(why) => {
refused.push(format!("{dest}: {why}"));
continue;
}
};
let path = dest.to_fs(root);
match fs::symlink_metadata(&path).map(|m| m.file_type()) {
Ok(t) if t.is_file() => {}
Ok(t) if t.is_symlink() => {
refused.push(format!(
"{dest}: the file is a symbolic link, and a pack holds only files"
));
continue;
}
_ => {
refused.push(format!("{dest}: no such file"));
continue;
}
}
let bytes = match fs::read(&path) {
Ok(b) => b,
Err(e) => {
refused.push(format!("{dest}: the file can't be read: {e}"));
continue;
}
};
if let Some(why) = pack::refusal(&rel, &bytes, &config_roots, &protected) {
refused.push(format!("{dest}: sync would refuse the file: {why}"));
continue;
}
let executable = pack::carries_mode(&rel) && pack::file_is_executable(&path);
out.push(NewFile {
rel,
bytes,
executable,
});
}
if !refused.is_empty() {
return Err(Error::Pack(refused.join("; ")));
}
Ok(out)
}
pub fn pack_export(name: &str, dir: &Path) -> Result<Vec<String>> {
pack_export_with(name, dir, EMBEDDED)
}
pub fn pack_export_with(name: &str, dir: &Path, embedded: &[EmbeddedPack]) -> Result<Vec<String>> {
let found = embedded
.iter()
.find(|p| p.read().is_ok_and(|f| f.manifest.name == name));
let Some(found) = found else {
pack::find_embedded(embedded, name)?;
return Err(Error::Internal(format!("no embedded pack {name}")));
};
if let Ok(mut entries) = fs::read_dir(dir)
&& entries.next().is_some()
{
return Err(Error::Pack(format!(
"{}: the directory is not empty",
dir.display()
)));
}
let mut written = Vec::new();
for (rel, text) in found.files {
let path = dir.join(rel);
agent_harness_adapter_core::fs::write_atomic(&path, text.as_bytes())?;
written.push(rel.to_string());
}
Ok(written)
}