use std::{
collections::BTreeSet,
fs,
path::{Path, PathBuf},
};
use serde::Serialize;
use super::pack::{SyncedPack, edited_files, 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,
}
impl PackFileState {
pub fn label(self) -> &'static str {
match self {
PackFileState::Edited => "edited",
PackFileState::Conflicted => "conflicted",
PackFileState::Deleted => "deleted",
}
}
}
#[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<(String, PackFileState)>,
pub shadowed: Vec<ShadowedFile>,
}
#[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.is_empty())
}
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 (path, state) in &p.files {
out.push_str(&format!("{} {path}\n", state.label()));
}
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 = lock
.packs
.iter()
.map(|(name, p)| {
let edited = edited_files(root, p);
let files = edited
.into_iter()
.map(|path| {
let text = RepoPath::parse(&path)
.and_then(|rp| fs::read_to_string(rp.to_fs(root)).ok().map(|t| (rp, t)));
let state = match text {
None => PackFileState::Deleted,
Some((rp, t)) if !check::conflict_lines(&rp, &t).is_empty() => {
PackFileState::Conflicted
}
Some(_) => PackFileState::Edited,
};
(path, state)
})
.collect();
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: name.clone(),
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 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 fragment = pack::instructions_of(name);
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) && f.path != fragment.as_str() {
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,
})
}
pub fn pack_diff(root: &RepoRoot, name: &str) -> Result<String> {
let (_, entry) = locked(root, name)?;
let edited = edited_files(root, &entry);
let mut out = String::new();
for (rel, f) in &entry.files {
if !edited.contains(&f.path) {
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 current = RepoPath::parse(&f.path).and_then(|p| fs::read(p.to_fs(root)).ok());
let current = current.as_deref().map(pack::normalise);
out.push_str(&pack::diff(
rel,
&pack::normalise(&base),
current.as_deref(),
)?);
}
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)
}