use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::{Error, RepoPath, RepoRoot, Result, source::read_optional};
const HEADER: &str = "# sokf pack sync writes this file. Do not edit it.\n";
pub fn lock_path() -> RepoPath {
RepoPath::parse("/.sokf/packs.lock").expect("literal")
}
pub const PACKS_DIR: &str = ".sokf/packs";
pub fn pack_dir(name: &str) -> RepoPath {
RepoPath::parse(&format!("/{PACKS_DIR}/{name}")).expect("a pack name is a slug")
}
pub fn base_path(name: &str, rel: &str) -> RepoPath {
RepoPath::parse(&format!("/{PACKS_DIR}/{name}/base/{rel}")).expect("a pack path is relative")
}
pub fn formats_of(name: &str) -> RepoPath {
RepoPath::parse(&format!("/{PACKS_DIR}/{name}/formats.yaml")).expect("a pack name is a slug")
}
pub fn instructions_of(name: &str) -> RepoPath {
RepoPath::parse(&format!("/{PACKS_DIR}/{name}/instructions.md")).expect("a pack name is a slug")
}
pub fn fragments(root: &RepoRoot, lock: &Lock) -> Result<Vec<(String, String)>> {
let mut out = Vec::new();
for name in lock.packs.keys() {
if let Some(text) = read_optional(&instructions_of(name).to_fs(root))? {
out.push((name.clone(), text));
}
}
Ok(out)
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Lock {
#[serde(default)]
pub packs: BTreeMap<String, LockedPack>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedPack {
pub source: String,
#[serde(rename = "ref", default, skip_serializing_if = "Option::is_none")]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
pub store: String,
pub commit: String,
pub version: String,
#[serde(default)]
pub files: BTreeMap<String, LockedFile>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedFile {
pub path: String,
pub base: String,
}
impl Lock {
pub fn owner_of(&self, dest: &str) -> Option<(&str, &str)> {
self.packs.iter().find_map(|(name, pack)| {
pack.files
.iter()
.find(|(_, f)| f.path == dest)
.map(|(rel, _)| (name.as_str(), rel.as_str()))
})
}
}
pub fn hash_of(bytes: &[u8]) -> String {
format!("fnv1a64:{:016x}", crate::source::fnv1a64(bytes))
}
pub fn read_lock(root: &RepoRoot) -> Result<Lock> {
let path = lock_path();
let Some(text) = read_optional(&path.to_fs(root))? else {
return Ok(Lock::default());
};
let lock: Lock = toml::from_str(&text).map_err(|e| Error::config(path.clone(), e.message()))?;
for name in lock.packs.keys() {
if !super::manifest::is_slug(name) {
return Err(Error::config(
path,
format!("the pack name `{name}` is not a slug"),
));
}
}
Ok(lock)
}
pub fn lock_text(lock: &Lock) -> Result<String> {
let body = toml::to_string(lock).map_err(|e| Error::Internal(e.to_string()))?;
Ok(format!("{HEADER}{body}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_lock_round_trips_through_its_text() {
let mut lock = Lock::default();
let mut pack = LockedPack {
source: "https://example.com/method.git".into(),
git_ref: Some("main".into()),
path: None,
store: "/knowledge".into(),
commit: "0123abcd".into(),
version: "1.0.0".into(),
files: BTreeMap::new(),
};
pack.files.insert(
"schemas/issue.md".into(),
LockedFile {
path: "/knowledge/schemas/issue.md".into(),
base: hash_of(b"x"),
},
);
lock.packs.insert("method".into(), pack);
let text = lock_text(&lock).unwrap();
assert!(text.starts_with(HEADER), "{text}");
assert!(text.contains("[packs.method]"), "{text}");
assert!(text.contains("ref = \"main\""), "{text}");
assert!(!text.contains("path = \"\""), "{text}");
let back: Lock = toml::from_str(&text).unwrap();
assert_eq!(back, lock);
assert_eq!(
lock.owner_of("/knowledge/schemas/issue.md"),
Some(("method", "schemas/issue.md"))
);
assert_eq!(lock.owner_of("/knowledge/schemas/other.md"), None);
}
#[test]
fn the_paths_of_a_pack_lie_under_its_directory() {
assert_eq!(pack_dir("sokf").as_str(), "/.sokf/packs/sokf");
assert_eq!(
base_path("sokf", "schemas/issue.md").as_str(),
"/.sokf/packs/sokf/base/schemas/issue.md"
);
assert_eq!(
formats_of("sokf").as_str(),
"/.sokf/packs/sokf/formats.yaml"
);
assert_eq!(
instructions_of("sokf").as_str(),
"/.sokf/packs/sokf/instructions.md"
);
assert_eq!(hash_of(b""), "fnv1a64:cbf29ce484222325");
}
}