use std::{
collections::BTreeSet,
path::{Path, PathBuf},
};
use serde::Serialize;
use super::pack_run::{Fetching, Run, run};
use crate::{
Error, PathArg, RepoPath, RepoRoot, Result,
config::{self, PackEntry},
pack::{self, EMBEDDED, EmbeddedPack, Fetched, FileAction, Lock, PackPlan, Source},
source::read_optional,
};
#[derive(Debug, Clone, Default)]
pub struct PackSyncOptions {
pub name: Option<String>,
pub keep_existing: bool,
pub home: Option<PathBuf>,
}
#[derive(Debug, Clone, Default)]
pub struct PackAddOptions {
pub source: String,
pub git_ref: Option<String>,
pub path: Option<String>,
pub store: Option<PathBuf>,
pub keep_existing: bool,
pub cwd: PathBuf,
pub home: Option<PathBuf>,
}
#[derive(Debug, Clone, Serialize)]
pub struct SyncedPack {
pub name: String,
pub version: String,
pub source: String,
pub store: Option<String>,
pub files: Vec<(String, FileAction)>,
pub notes: Vec<String>,
pub fetched: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct UndeclaredPack {
pub name: String,
pub removed: Vec<String>,
pub kept: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PackSyncReport {
pub declared: Option<String>,
pub undeclared: Vec<UndeclaredPack>,
pub packs: Vec<SyncedPack>,
pub instructions: Vec<String>,
}
impl PackSyncReport {
pub fn conflicted(&self) -> bool {
self.packs
.iter()
.any(|p| p.files.iter().any(|(_, a)| *a == FileAction::Conflicted))
}
pub fn to_text(&self) -> String {
let mut out = String::new();
if let Some(name) = &self.declared {
out.push_str(&format!("declared the pack {name} in /.sokf/config.toml\n"));
}
for u in &self.undeclared {
out.push_str(&format!(
"removed the pack {}, which no [[pack]] entry declares\n",
u.name
));
for p in &u.removed {
out.push_str(&format!("removed {p}\n"));
}
for p in &u.kept {
out.push_str(&format!("kept {p}: edited\n"));
}
}
for p in &self.packs {
let into = p
.store
.as_ref()
.map(|s| format!(" into {s}"))
.unwrap_or_default();
if p.fetched {
out.push_str(&format!(
"synced {} {} from {}{into}\n",
p.name, p.version, p.source
));
} else {
out.push_str(&format!(
"changed the owners of the files of {} {}\n",
p.name, p.version
));
}
for (path, action) in &p.files {
out.push_str(&format!("{} {path}\n", action.label()));
}
}
for line in &self.instructions {
out.push_str(&format!("{line}\n"));
}
for p in &self.packs {
for note in &p.notes {
out.push_str(&format!("{note}\n"));
}
}
if self.conflicted() {
out.push_str(
"error: a merge conflicts: resolve the conflict markers in each conflicted file\n",
);
}
let deleted = self
.packs
.iter()
.any(|p| p.files.iter().any(|(_, a)| *a == FileAction::Deleted));
if deleted {
out.push_str(
"note: a deleted file is your edit, so the sync keeps it deleted; to restore it, copy its base copy from /.sokf/packs/<NAME>/base/ back\n",
);
}
out.push_str("note: run `sokf validate --fix` to bring the store's indexes up to date\n");
out
}
}
pub fn pack_sync(root: &RepoRoot, opts: &PackSyncOptions) -> Result<PackSyncReport> {
pack_sync_with(root, opts, EMBEDDED)
}
pub fn pack_sync_with(
root: &RepoRoot,
opts: &PackSyncOptions,
embedded: &[EmbeddedPack],
) -> Result<PackSyncReport> {
let entries = config::read_packs(root)?;
refuse_undeclared_lock(root, &entries)?;
run(
root,
&Run {
entries: &entries,
fetching: match opts.name.as_deref() {
Some(n) => Fetching::One(n),
None => Fetching::All,
},
remove_only: None,
keep_existing: opts.keep_existing,
home: &opts.home,
config: None,
},
None,
embedded,
)
}
pub fn pack_add(root: &RepoRoot, opts: &PackAddOptions) -> Result<PackSyncReport> {
pack_add_with(root, opts, EMBEDDED)
}
pub fn pack_add_with(
root: &RepoRoot,
opts: &PackAddOptions,
embedded: &[EmbeddedPack],
) -> Result<PackSyncReport> {
let source = Source::parse(&opts.source);
let fetched = fetch(
&source,
opts.git_ref.as_deref(),
opts.path.as_deref(),
embedded,
)?;
let name = fetched.pack.manifest.name.clone();
let mut entries = config::read_packs(root)?;
refuse_undeclared_lock(root, &entries)?;
if entries.iter().any(|e| e.name == name) {
return Err(Error::Pack(format!(
"{name}: /.sokf/config.toml already declares the pack {name}; edit its [[pack]] entry to change its source"
)));
}
let store = match &opts.store {
Some(s) => Some(
PathArg(&s.to_string_lossy())
.resolve(root, &opts.cwd)
.ok_or_else(|| Error::Pack(format!("{}: no such directory", s.display())))?
.as_str()
.to_string(),
),
None => None,
};
let entry = PackEntry {
name: name.clone(),
source: source.label(),
git_ref: opts.git_ref.clone(),
path: fetched.path.clone(),
store,
};
let text = read_optional(&config::config_path().to_fs(root))?;
let config = config::add_entry(text.as_deref(), &entry)?;
entries.push(entry);
let mut report = run(
root,
&Run {
entries: &entries,
fetching: Fetching::One(&name),
remove_only: None,
keep_existing: opts.keep_existing,
home: &opts.home,
config: Some(config),
},
Some(fetched),
embedded,
)?;
report.declared = Some(name);
Ok(report)
}
fn refuse_undeclared_lock(root: &RepoRoot, entries: &[PackEntry]) -> Result<()> {
let lock = pack::read_lock(root)?;
if !entries.is_empty() || lock.packs.is_empty() {
return Ok(());
}
let mut text = String::new();
for (name, p) in &lock.packs {
text = config::add_entry(
Some(&text),
&PackEntry {
name: name.clone(),
source: p.source.clone(),
git_ref: p.git_ref.clone(),
path: p.path.clone(),
store: p.store.clone(),
},
)?;
}
Err(Error::Pack(format!(
"no [[pack]] entry of /.sokf/config.toml declares a pack, and the lock holds {}; add these entries to /.sokf/config.toml to keep them, or remove each with `sokf pack remove <NAME>`:\n\n{text}",
lock.packs.keys().cloned().collect::<Vec<_>>().join(", ")
)))
}
pub(super) fn harness_dirs(root: &RepoRoot, home: &Option<PathBuf>) -> super::HarnessDirs {
super::HarnessDirs {
repo: Some(root.clone()),
home: home.clone(),
}
}
pub(super) fn fetch(
source: &Source,
git_ref: Option<&str>,
path: Option<&str>,
embedded: &[EmbeddedPack],
) -> Result<Fetched> {
match source {
Source::Builtin(name) => {
if git_ref.is_some() || path.is_some() {
return Err(Error::Pack(format!(
"{}: an embedded pack takes no --ref and no --path",
source.label()
)));
}
Ok(Fetched {
pack: pack::find_embedded(embedded, name)?,
source: source.clone(),
git_ref: None,
path: None,
commit: pack::tool_version().to_string(),
offline: false,
})
}
Source::Git(url) => {
let path = path
.map(|p| p.trim_matches('/'))
.filter(|p| !p.is_empty() && *p != ".");
if let Some(p) = path
&& p.split('/').any(|s| s == "..")
{
return Err(Error::Pack(format!(
"--path {p}: the path leaves the repository"
)));
}
let clone = pack::shallow_clone(url, git_ref)?;
let dir = match path {
Some(p) => pack::clone_dir(&clone.worktree(), p)?,
None => clone.worktree(),
};
let label = match path {
Some(p) => format!("{url} at {p}"),
None => url.clone(),
};
let mut files = pack::read_dir(&dir, &label)?;
let prefix: String = path
.unwrap_or_default()
.split('/')
.filter(|s| !s.is_empty() && *s != ".")
.map(|s| format!("{s}/"))
.collect();
files.executable = clone
.executables()?
.into_iter()
.filter_map(|p| p.strip_prefix(&prefix).map(str::to_string))
.filter(|rel| rel.starts_with(pack::FILES) && files.files.contains_key(rel))
.collect();
Ok(Fetched {
pack: files,
source: source.clone(),
git_ref: Some(clone.git_ref.clone()),
path: path.map(str::to_string),
commit: clone.commit.clone(),
offline: false,
})
}
}
}
pub(super) fn apply(root: &RepoRoot, plans: &[PackPlan], lock: &Lock) -> Result<()> {
for plan in plans {
for (path, bytes) in &plan.writes {
write(root, path, bytes)?;
}
for (path, executable) in &plan.modes {
let fs_path = path.to_fs(root);
pack::set_executable(&fs_path, *executable).map_err(|e| Error::io(&fs_path, e))?;
}
for path in &plan.deletes {
remove(root, path)?;
}
}
write_lock(root, lock)
}
pub(super) fn write_lock(root: &RepoRoot, lock: &Lock) -> Result<()> {
if lock.packs.is_empty() {
remove(root, &pack::lock_path())?;
let _ = std::fs::remove_dir(root.as_path().join(pack::PACKS_DIR));
return Ok(());
}
write(root, &pack::lock_path(), pack::lock_text(lock)?.as_bytes())
}
pub(super) fn write(root: &RepoRoot, path: &RepoPath, bytes: &[u8]) -> Result<()> {
agent_harness_adapter_core::fs::write_atomic(&path.to_fs(root), bytes).map_err(Error::from)
}
pub(super) fn remove(root: &RepoRoot, path: &RepoPath) -> Result<()> {
let fs_path = path.to_fs(root);
match std::fs::remove_file(&fs_path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(Error::io(&fs_path, e)),
}
let packs = root.as_path().join(pack::PACKS_DIR);
let sokf = root.as_path().join(".sokf");
let stop = if fs_path.starts_with(&packs) {
packs
} else if fs_path.starts_with(&sokf) {
sokf
} else {
root.as_path().to_path_buf()
};
let mut dir = fs_path.parent().map(Path::to_path_buf);
while let Some(d) = dir {
if d == stop || !d.starts_with(&stop) || std::fs::remove_dir(&d).is_err() {
break;
}
dir = d.parent().map(Path::to_path_buf);
}
Ok(())
}
pub(super) fn edited_files(root: &RepoRoot, pack: &pack::LockedPack) -> BTreeSet<String> {
pack.files
.iter()
.filter(|(_, f)| f.shadowed_by.is_none())
.filter(|(rel, f)| {
let Some(path) = RepoPath::parse(&f.path).map(|p| p.to_fs(root)) else {
return true;
};
let Ok(bytes) = std::fs::read(&path) else {
return true;
};
!pack::is_base(&bytes, &f.base)
|| (cfg!(unix)
&& rel.starts_with(pack::FILES)
&& pack::file_is_executable(&path) != f.executable)
})
.map(|(_, f)| f.path.clone())
.collect()
}