use std::path::PathBuf;
use schemars::JsonSchema;
use serde::Serialize;
use crate::{
Error, PathArg, RepoPath, RepoRoot, Result,
config::{self, ConfigText},
markdown::is_slug,
scaffold,
};
#[derive(Debug, Clone)]
pub struct InitOptions {
pub dir: Option<PathBuf>,
pub cwd: PathBuf,
pub name: Option<String>,
pub scope: Option<String>,
pub description: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(title = "sokf init report")]
pub struct InitResult {
pub root: RepoPath,
pub created: Vec<RepoPath>,
pub updated: Vec<RepoPath>,
pub hand_written_indexes: Vec<RepoPath>,
}
pub fn init(root: &RepoRoot, opts: &InitOptions) -> Result<InitResult> {
let dir = match &opts.dir {
None => RepoPath::parse("/knowledge").expect("literal"),
Some(given) => {
let shown = given.display().to_string();
given
.to_str()
.and_then(|s| PathArg(s).resolve_new(root, &opts.cwd))
.ok_or_else(|| Error::Init(format!("{shown} lies outside the repository")))?
}
};
if dir.as_str() == "/" {
return Err(Error::Init(
"/ is the repository root, and a store there would hold every file of the repository. Pass a directory under the root.".into(),
));
}
let fs_dir = dir.to_fs(root);
if fs_dir.is_file() {
return Err(Error::Init(format!("{dir} is a file, not a directory")));
}
if fs_dir.join("manifest.sokf.yaml").exists() {
return Err(Error::Init(format!(
"{dir} is already a knowledge store: it holds manifest.sokf.yaml"
)));
}
let empty = !fs_dir.is_dir()
|| std::fs::read_dir(&fs_dir)
.map_err(|e| Error::io(&fs_dir, e))?
.next()
.is_none();
let name = name_of(opts, &dir)?;
let scope = scope_of(root, opts)?;
let config: ConfigText = config::read_lenient(root)?;
let existing: Vec<RepoPath> = config
.roots
.iter()
.filter(|r| r.to_fs(root).is_dir())
.cloned()
.collect();
if let Some(other) = config
.registered
.iter()
.find(|r| dir.starts_with(r) || r.starts_with(&dir))
{
return Err(Error::Init(format!(
"{dir} meets the registered knowledge root {other}; a store lies beside a registered store"
)));
}
let mut known = existing.clone();
known.extend(config.registered.iter().cloned());
check_identity(root, &known, &scope, &name)?;
let mut files = scaffold::store(&dir, &name, &scope, opts.description.as_deref());
let hand_written = if empty {
Vec::new()
} else {
files
.files
.retain(|(path, _)| path.file_name() == "manifest.sokf.yaml");
hand_written_indexes(root, &dir)?
};
let change = scaffold::register(&config, &existing, &dir)?;
let (created, updated) = scaffold::write(root, &files, &change)?;
Ok(InitResult {
root: dir,
created,
updated,
hand_written_indexes: hand_written,
})
}
fn name_of(opts: &InitOptions, dir: &RepoPath) -> Result<String> {
let name = opts
.name
.clone()
.unwrap_or_else(|| dir.file_name().to_string());
if name.is_empty() {
return Err(Error::Init("--name is empty".into()));
}
if !is_slug(&name) {
let from = match opts.name {
Some(_) => "--name".to_string(),
None => format!("the name `{name}`, the last segment of {dir},"),
};
return Err(Error::Init(format!(
"{from} is not a slug. A slug is lower-case letters and digits, joined by single hyphens. Pass --name with a slug."
)));
}
Ok(name)
}
fn scope_of(root: &RepoRoot, opts: &InitOptions) -> Result<String> {
match &opts.scope {
Some(scope) if is_slug(scope) => Ok(scope.clone()),
Some(scope) => Err(Error::Init(format!(
"--scope `{scope}` is not a slug. A slug is lower-case letters and digits, joined by single hyphens."
))),
None => remote_owner(root).ok_or_else(|| {
Error::Init(
"you passed no --scope, and the URL of the git remote `origin` has no owner to read. Pass --scope with the slug of the store's owner.".into(),
)
}),
}
}
fn check_identity(root: &RepoRoot, existing: &[RepoPath], scope: &str, name: &str) -> Result<()> {
for other in existing {
let Some(path) = other.join("manifest.sokf.yaml") else {
continue;
};
let Ok(text) = std::fs::read_to_string(path.to_fs(root)) else {
continue;
};
let manifest = crate::model::manifest(crate::yaml::parse(&text, 1), other);
let identity = format!("{scope}/{name}");
if manifest.scope.as_deref() == Some(scope) && manifest.name.as_deref() == Some(name) {
return Err(Error::Init(format!(
"the store at {other} already has the identity `{identity}`. Pass --name with another slug."
)));
}
if manifest
.renamed_from
.iter()
.any(|(old, _)| *old == identity)
{
return Err(Error::Init(format!(
"the store at {other} was once `{identity}`, and references to that identity still resolve to that store. Pass --name with another slug."
)));
}
}
Ok(())
}
fn hand_written_indexes(root: &RepoRoot, dir: &RepoPath) -> Result<Vec<RepoPath>> {
let mut found = Vec::new();
let mut pending = vec![dir.clone()];
while let Some(next) = pending.pop() {
let fs_dir = next.to_fs(root);
let entries = std::fs::read_dir(&fs_dir).map_err(|e| Error::io(&fs_dir, e))?;
for entry in entries {
let entry = entry.map_err(|e| Error::io(&fs_dir, e))?;
let kind = entry.file_type().map_err(|e| Error::io(entry.path(), e))?;
let Some(path) = entry.file_name().to_str().and_then(|n| next.join(n)) else {
continue;
};
if kind.is_dir() {
pending.push(path);
} else if kind.is_file() && path.file_name() == "index.md" {
let generated = crate::source::load(root, &path)
.is_ok_and(|source| crate::index::is_generated(&source.text));
if !generated {
found.push(path);
}
}
}
}
found.sort();
Ok(found)
}
fn remote_owner(root: &RepoRoot) -> Option<String> {
let out = crate::git::command()
.arg("-C")
.arg(root.as_path())
.args(["config", "--get", "remote.origin.url"])
.output()
.ok()?;
owner_of(String::from_utf8(out.stdout).ok()?.trim())
}
fn owner_of(url: &str) -> Option<String> {
let path = match url.split_once("://") {
Some((_, rest)) => rest.split_once('/')?.1,
None => url.split_once(':')?.1,
};
let owner = path
.trim_start_matches('/')
.split('/')
.next()?
.to_lowercase();
is_slug(&owner).then_some(owner)
}
#[cfg(test)]
mod tests {
use std::fs;
use super::*;
fn temp(name: &str) -> PathBuf {
crate::test_support::fresh_dir(&format!("init-{name}"))
}
fn opts(dir: &std::path::Path, given: Option<&str>, name: Option<&str>) -> InitOptions {
InitOptions {
dir: given.map(PathBuf::from),
cwd: dir.to_path_buf(),
name: name.map(str::to_string),
scope: Some("test".into()),
description: None,
}
}
fn message(r: Result<InitResult>) -> String {
match r {
Err(Error::Init(m)) => m,
other => panic!("expected an init refusal, got {other:?}"),
}
}
#[test]
fn refuses_in_order_and_writes_nothing() {
let dir = temp("refuse");
let root = RepoRoot::new(dir.clone());
fs::write(dir.join("file.md"), "").unwrap();
fs::create_dir_all(dir.join("full")).unwrap();
fs::write(dir.join("full/manifest.sokf.yaml"), "").unwrap();
fs::create_dir_all(dir.join("empty")).unwrap();
fs::create_dir_all(dir.join(".sokf")).unwrap();
assert_eq!(
message(init(&root, &opts(&dir, Some("../outside"), None))),
"../outside lies outside the repository"
);
assert_eq!(
message(init(&root, &opts(&dir, Some("file.md"), None))),
"/file.md is a file, not a directory"
);
assert_eq!(
message(init(&root, &opts(&dir, Some("."), None))),
"/ is the repository root, and a store there would hold every file of the repository. Pass a directory under the root."
);
assert_eq!(
message(init(&root, &opts(&dir, Some("full"), None))),
"/full is already a knowledge store: it holds manifest.sokf.yaml"
);
assert_eq!(
message(init(&root, &opts(&dir, Some("empty"), Some("")))),
"--name is empty"
);
assert_eq!(
message(init(&root, &opts(&dir, Some("empty"), Some("Project KB")))),
"--name is not a slug. A slug is lower-case letters and digits, joined by single hyphens. Pass --name with a slug."
);
let mut unscoped = opts(&dir, Some("empty"), None);
unscoped.scope = Some("Acme Inc".into());
assert!(message(init(&root, &unscoped)).starts_with("--scope `Acme Inc` is not a slug"));
fs::write(dir.join(".sokf/config.toml"), "not toml [").unwrap();
let m = message(init(&root, &opts(&dir, Some("empty"), None)));
assert!(m.starts_with("/.sokf/config.toml: "), "{m}");
assert!(!dir.join("empty/manifest.sokf.yaml").exists());
assert!(!dir.join("knowledge").exists());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_name_defaults_to_the_last_segment() {
let dir = temp("name");
let root = RepoRoot::new(dir.clone());
let out = init(&root, &opts(&dir, Some("docs/kb/"), None)).unwrap();
assert_eq!(out.root, RepoPath::parse("/docs/kb").unwrap());
assert_eq!(
fs::read_to_string(dir.join("docs/kb/manifest.sokf.yaml")).unwrap(),
"sokf: \"0.6\"\nname: kb\nscope: test\n"
);
let out = init(&root, &opts(&dir, None, Some("project-kb"))).unwrap();
assert_eq!(out.root, RepoPath::parse("/knowledge").unwrap());
assert!(
fs::read_to_string(dir.join("knowledge/index.md"))
.unwrap()
.starts_with("# project-kb\n")
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_owner_is_read_from_a_remote_url() {
for url in [
"https://github.com/ncoderz/sokf",
"https://github.com/NCoderz/sokf.git",
"git@github.com:ncoderz/sokf.git",
"ssh://git@github.com/ncoderz/sokf",
] {
assert_eq!(owner_of(url).as_deref(), Some("ncoderz"), "{url}");
}
assert_eq!(owner_of(""), None);
assert_eq!(owner_of("https://host/under_score/x"), None);
}
#[test]
fn a_name_its_scope_already_holds_is_refused() {
let dir = temp("clash");
let root = RepoRoot::new(dir.clone());
init(&root, &opts(&dir, Some("a/knowledge"), None)).unwrap();
assert_eq!(
message(init(&root, &opts(&dir, Some("b/knowledge"), None))),
"the store at /a/knowledge already has the identity `test/knowledge`. Pass --name with another slug."
);
init(&root, &opts(&dir, Some("b/knowledge"), Some("b-knowledge"))).unwrap();
fs::write(
dir.join("a/knowledge/manifest.sokf.yaml"),
"sokf: \"0.6\"\nname: knowledge\nscope: test\nrenamed-from: [test/old]\n",
)
.unwrap();
assert_eq!(
message(init(&root, &opts(&dir, Some("c/kb"), Some("old")))),
"the store at /a/knowledge was once `test/old`, and references to that identity still resolve to that store. Pass --name with another slug."
);
fs::remove_dir_all(&dir).unwrap();
}
}