1use std::path::PathBuf;
9
10use schemars::JsonSchema;
11use serde::Serialize;
12
13use crate::{
14 Error, PathArg, RepoPath, RepoRoot, Result,
15 config::{self, ConfigText},
16 markdown::is_slug,
17 scaffold,
18};
19
20#[derive(Debug, Clone)]
22pub struct InitOptions {
23 pub dir: Option<PathBuf>,
26 pub cwd: PathBuf,
28 pub name: Option<String>,
31 pub scope: Option<String>,
34 pub description: Option<String>,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
42#[schemars(title = "sokf init report")]
43pub struct InitResult {
44 pub root: RepoPath,
46 pub created: Vec<RepoPath>,
48 pub updated: Vec<RepoPath>,
52 pub hand_written_indexes: Vec<RepoPath>,
57}
58
59pub fn init(root: &RepoRoot, opts: &InitOptions) -> Result<InitResult> {
67 let dir = match &opts.dir {
70 None => RepoPath::parse("/knowledge").expect("literal"),
71 Some(given) => {
72 let shown = given.display().to_string();
73 given
74 .to_str()
75 .and_then(|s| PathArg(s).resolve_new(root, &opts.cwd))
76 .ok_or_else(|| Error::Init(format!("{shown} lies outside the repository")))?
77 }
78 };
79 if dir.as_str() == "/" {
81 return Err(Error::Init(
82 "/ is the repository root, and a store there would hold every file of the repository. Pass a directory under the root.".into(),
83 ));
84 }
85 let fs_dir = dir.to_fs(root);
86 if fs_dir.is_file() {
88 return Err(Error::Init(format!("{dir} is a file, not a directory")));
89 }
90 if fs_dir.join("manifest.sokf.yaml").exists() {
92 return Err(Error::Init(format!(
93 "{dir} is already a knowledge store: it holds manifest.sokf.yaml"
94 )));
95 }
96 let empty = !fs_dir.is_dir()
97 || std::fs::read_dir(&fs_dir)
98 .map_err(|e| Error::io(&fs_dir, e))?
99 .next()
100 .is_none();
101 let name = name_of(opts, &dir)?;
102 let scope = scope_of(root, opts)?;
103 let config: ConfigText = config::read_lenient(root)?;
104 let existing: Vec<RepoPath> = config
105 .roots
106 .iter()
107 .filter(|r| r.to_fs(root).is_dir())
108 .cloned()
109 .collect();
110 if let Some(other) = config
114 .registered
115 .iter()
116 .find(|r| dir.starts_with(r) || r.starts_with(&dir))
117 {
118 return Err(Error::Init(format!(
119 "{dir} meets the registered knowledge root {other}; a store lies beside a registered store"
120 )));
121 }
122 let mut known = existing.clone();
123 known.extend(config.registered.iter().cloned());
124 check_identity(root, &known, &scope, &name)?;
125 let mut files = scaffold::store(&dir, &name, &scope, opts.description.as_deref());
126 let hand_written = if empty {
131 Vec::new()
132 } else {
133 files
134 .files
135 .retain(|(path, _)| path.file_name() == "manifest.sokf.yaml");
136 hand_written_indexes(root, &dir)?
137 };
138 let change = scaffold::register(&config, &existing, &dir)?;
139 let (created, updated) = scaffold::write(root, &files, &change)?;
140 Ok(InitResult {
141 root: dir,
142 created,
143 updated,
144 hand_written_indexes: hand_written,
145 })
146}
147
148fn name_of(opts: &InitOptions, dir: &RepoPath) -> Result<String> {
152 let name = opts
154 .name
155 .clone()
156 .unwrap_or_else(|| dir.file_name().to_string());
157 if name.is_empty() {
159 return Err(Error::Init("--name is empty".into()));
160 }
161 if !is_slug(&name) {
163 let from = match opts.name {
164 Some(_) => "--name".to_string(),
165 None => format!("the name `{name}`, the last segment of {dir},"),
166 };
167 return Err(Error::Init(format!(
168 "{from} is not a slug. A slug is lower-case letters and digits, joined by single hyphens. Pass --name with a slug."
169 )));
170 }
171 Ok(name)
172}
173
174fn scope_of(root: &RepoRoot, opts: &InitOptions) -> Result<String> {
182 match &opts.scope {
183 Some(scope) if is_slug(scope) => Ok(scope.clone()),
184 Some(scope) => Err(Error::Init(format!(
185 "--scope `{scope}` is not a slug. A slug is lower-case letters and digits, joined by single hyphens."
186 ))),
187 None => remote_owner(root).ok_or_else(|| {
188 Error::Init(
189 "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(),
190 )
191 }),
192 }
193}
194
195fn check_identity(root: &RepoRoot, existing: &[RepoPath], scope: &str, name: &str) -> Result<()> {
198 for other in existing {
204 let Some(path) = other.join("manifest.sokf.yaml") else {
205 continue;
206 };
207 let Ok(text) = std::fs::read_to_string(path.to_fs(root)) else {
208 continue;
209 };
210 let manifest = crate::model::manifest(crate::yaml::parse(&text, 1), other);
211 let identity = format!("{scope}/{name}");
212 if manifest.scope.as_deref() == Some(scope) && manifest.name.as_deref() == Some(name) {
213 return Err(Error::Init(format!(
214 "the store at {other} already has the identity `{identity}`. Pass --name with another slug."
215 )));
216 }
217 if manifest
220 .renamed_from
221 .iter()
222 .any(|(old, _)| *old == identity)
223 {
224 return Err(Error::Init(format!(
225 "the store at {other} was once `{identity}`, and references to that identity still resolve to that store. Pass --name with another slug."
226 )));
227 }
228 }
229 Ok(())
230}
231
232fn hand_written_indexes(root: &RepoRoot, dir: &RepoPath) -> Result<Vec<RepoPath>> {
237 let mut found = Vec::new();
238 let mut pending = vec![dir.clone()];
239 while let Some(next) = pending.pop() {
240 let fs_dir = next.to_fs(root);
241 let entries = std::fs::read_dir(&fs_dir).map_err(|e| Error::io(&fs_dir, e))?;
242 for entry in entries {
243 let entry = entry.map_err(|e| Error::io(&fs_dir, e))?;
244 let kind = entry.file_type().map_err(|e| Error::io(entry.path(), e))?;
245 let Some(path) = entry.file_name().to_str().and_then(|n| next.join(n)) else {
246 continue;
247 };
248 if kind.is_dir() {
249 pending.push(path);
250 } else if kind.is_file() && path.file_name() == "index.md" {
251 let generated = crate::source::load(root, &path)
253 .is_ok_and(|source| crate::index::is_generated(&source.text));
254 if !generated {
255 found.push(path);
256 }
257 }
258 }
259 }
260 found.sort();
261 Ok(found)
262}
263
264fn remote_owner(root: &RepoRoot) -> Option<String> {
270 let out = crate::git::command()
271 .arg("-C")
272 .arg(root.as_path())
273 .args(["config", "--get", "remote.origin.url"])
274 .output()
275 .ok()?;
276 owner_of(String::from_utf8(out.stdout).ok()?.trim())
277}
278
279fn owner_of(url: &str) -> Option<String> {
283 let path = match url.split_once("://") {
284 Some((_, rest)) => rest.split_once('/')?.1,
285 None => url.split_once(':')?.1,
286 };
287 let owner = path
288 .trim_start_matches('/')
289 .split('/')
290 .next()?
291 .to_lowercase();
292 is_slug(&owner).then_some(owner)
293}
294
295#[cfg(test)]
296mod tests {
297 use std::fs;
298
299 use super::*;
300
301 fn temp(name: &str) -> PathBuf {
302 crate::test_support::fresh_dir(&format!("init-{name}"))
303 }
304
305 fn opts(dir: &std::path::Path, given: Option<&str>, name: Option<&str>) -> InitOptions {
306 InitOptions {
307 dir: given.map(PathBuf::from),
308 cwd: dir.to_path_buf(),
309 name: name.map(str::to_string),
310 scope: Some("test".into()),
311 description: None,
312 }
313 }
314
315 fn message(r: Result<InitResult>) -> String {
316 match r {
317 Err(Error::Init(m)) => m,
318 other => panic!("expected an init refusal, got {other:?}"),
319 }
320 }
321
322 #[test]
331 fn refuses_in_order_and_writes_nothing() {
332 let dir = temp("refuse");
333 let root = RepoRoot::new(dir.clone());
334 fs::write(dir.join("file.md"), "").unwrap();
335 fs::create_dir_all(dir.join("full")).unwrap();
336 fs::write(dir.join("full/manifest.sokf.yaml"), "").unwrap();
337 fs::create_dir_all(dir.join("empty")).unwrap();
338 fs::create_dir_all(dir.join(".sokf")).unwrap();
339 assert_eq!(
340 message(init(&root, &opts(&dir, Some("../outside"), None))),
341 "../outside lies outside the repository"
342 );
343 assert_eq!(
344 message(init(&root, &opts(&dir, Some("file.md"), None))),
345 "/file.md is a file, not a directory"
346 );
347 assert_eq!(
348 message(init(&root, &opts(&dir, Some("."), None))),
349 "/ is the repository root, and a store there would hold every file of the repository. Pass a directory under the root."
350 );
351 assert_eq!(
352 message(init(&root, &opts(&dir, Some("full"), None))),
353 "/full is already a knowledge store: it holds manifest.sokf.yaml"
354 );
355 assert_eq!(
356 message(init(&root, &opts(&dir, Some("empty"), Some("")))),
357 "--name is empty"
358 );
359 assert_eq!(
360 message(init(&root, &opts(&dir, Some("empty"), Some("Project KB")))),
361 "--name is not a slug. A slug is lower-case letters and digits, joined by single hyphens. Pass --name with a slug."
362 );
363 let mut unscoped = opts(&dir, Some("empty"), None);
364 unscoped.scope = Some("Acme Inc".into());
365 assert!(message(init(&root, &unscoped)).starts_with("--scope `Acme Inc` is not a slug"));
366 fs::write(dir.join(".sokf/config.toml"), "not toml [").unwrap();
367 let m = message(init(&root, &opts(&dir, Some("empty"), None)));
368 assert!(m.starts_with("/.sokf/config.toml: "), "{m}");
369 assert!(!dir.join("empty/manifest.sokf.yaml").exists());
370 assert!(!dir.join("knowledge").exists());
371 fs::remove_dir_all(&dir).unwrap();
372 }
373
374 #[test]
377 fn the_name_defaults_to_the_last_segment() {
378 let dir = temp("name");
379 let root = RepoRoot::new(dir.clone());
380 let out = init(&root, &opts(&dir, Some("docs/kb/"), None)).unwrap();
381 assert_eq!(out.root, RepoPath::parse("/docs/kb").unwrap());
382 assert_eq!(
383 fs::read_to_string(dir.join("docs/kb/manifest.sokf.yaml")).unwrap(),
384 "sokf: \"0.7\"\nname: kb\nscope: test\n"
385 );
386 let out = init(&root, &opts(&dir, None, Some("project-kb"))).unwrap();
387 assert_eq!(out.root, RepoPath::parse("/knowledge").unwrap());
388 assert!(
389 fs::read_to_string(dir.join("knowledge/index.md"))
390 .unwrap()
391 .starts_with("# project-kb\n")
392 );
393 fs::remove_dir_all(&dir).unwrap();
394 }
395
396 #[test]
398 fn the_owner_is_read_from_a_remote_url() {
399 for url in [
400 "https://github.com/ncoderz/sokf",
401 "https://github.com/NCoderz/sokf.git",
402 "git@github.com:ncoderz/sokf.git",
403 "ssh://git@github.com/ncoderz/sokf",
404 ] {
405 assert_eq!(owner_of(url).as_deref(), Some("ncoderz"), "{url}");
406 }
407 assert_eq!(owner_of(""), None);
408 assert_eq!(owner_of("https://host/under_score/x"), None);
409 }
410
411 #[test]
413 fn a_name_its_scope_already_holds_is_refused() {
414 let dir = temp("clash");
415 let root = RepoRoot::new(dir.clone());
416 init(&root, &opts(&dir, Some("a/knowledge"), None)).unwrap();
417 assert_eq!(
418 message(init(&root, &opts(&dir, Some("b/knowledge"), None))),
419 "the store at /a/knowledge already has the identity `test/knowledge`. Pass --name with another slug."
420 );
421 init(&root, &opts(&dir, Some("b/knowledge"), Some("b-knowledge"))).unwrap();
422 fs::write(
423 dir.join("a/knowledge/manifest.sokf.yaml"),
424 "sokf: \"0.7\"\nname: knowledge\nscope: test\nrenamed-from: [test/old]\n",
425 )
426 .unwrap();
427 assert_eq!(
428 message(init(&root, &opts(&dir, Some("c/kb"), Some("old")))),
429 "the store at /a/knowledge was once `test/old`, and references to that identity still resolve to that store. Pass --name with another slug."
430 );
431 fs::remove_dir_all(&dir).unwrap();
432 }
433}