Skip to main content

sokf_core/api/
init.rs

1//! This module runs `sokf init`. It resolves `DIR`, reads the config
2//! without requiring its roots to exist, and refuses bad input in the order
3//! that CLI-2 sets out. After the checks pass, it builds the files of the
4//! store, works out the change to the config, and writes both. In a
5//! directory that already holds files, it writes only the manifest, and
6//! lists each `index.md` there that is not a generated index.
7
8use 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/// `InitOptions` holds the options of `sokf init`.
21#[derive(Debug, Clone)]
22pub struct InitOptions {
23    /// `dir` is `DIR`, a path in the repository or a path relative to `cwd`.
24    /// The default is `/knowledge`.
25    pub dir: Option<PathBuf>,
26    /// `cwd` is the current directory, from which a relative `DIR` resolves.
27    pub cwd: PathBuf,
28    /// `name` holds the value of `--name`. The default is the last segment of
29    /// `DIR`.
30    pub name: Option<String>,
31    /// `scope` holds the value of `--scope`. The default is the owner in the
32    /// URL of the git remote `origin`.
33    pub scope: Option<String>,
34    /// `description` holds the value of `--description`.
35    pub description: Option<String>,
36}
37
38/// `InitResult` is the report of `sokf init --json`: it holds the directory
39/// of the store that the command created. It also holds the files that the
40/// command wrote (CLI-2_AC-12).
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
42#[schemars(title = "sokf init report")]
43pub struct InitResult {
44    /// `root` is the directory of the store that the command created.
45    pub root: RepoPath,
46    /// `created` holds the files that the command created, ordered by path.
47    pub created: Vec<RepoPath>,
48    /// `updated` holds the files that the command changed, ordered by path.
49    /// The list holds `/.sokf/config.toml` when the command added the store
50    /// to `knowledge.roots`, and is empty otherwise.
51    pub updated: Vec<RepoPath>,
52    /// `hand_written_indexes` holds each `index.md` under the directory that
53    /// is not in the generated form of an index, ordered by path. `validate
54    /// --fix` doesn't overwrite such a file, and `validate` reports it until
55    /// its content moves into a document (CLI-2_AC-32).
56    pub hand_written_indexes: Vec<RepoPath>,
57}
58
59/// `init` creates a knowledge store and registers it as a root in
60/// `knowledge.roots`. It checks for every reason to refuse before it writes
61/// anything.
62// sokf-implements: CLI-9_AC-1
63// sokf-implements: CONF-1_AC-3
64// sokf-implements: CONF-2_AC-8
65// sokf-implements: CLI-2_AC-11
66pub fn init(root: &RepoRoot, opts: &InitOptions) -> Result<InitResult> {
67    // sokf-implements: CLI-2_AC-8
68    // sokf-implements: CLI-2_AC-13
69    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    // sokf-implements: CLI-2_AC-33
80    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    // sokf-implements: CLI-2_AC-14
87    if fs_dir.is_file() {
88        return Err(Error::Init(format!("{dir} is a file, not a directory")));
89    }
90    // sokf-implements: CLI-2_AC-30
91    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    // A registered store lies beside every other store, so `init` puts no
111    // store inside or around one, and takes none of their identities.
112    // sokf-implements: CLI-2_AC-73
113    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    // In a directory that holds files, `init` writes the manifest alone:
127    // listing the files in the indexes is the work of `--fix`.
128    // sokf-implements: CLI-2_AC-6
129    // sokf-implements: CLI-2_AC-31
130    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
148/// `name_of` returns the name of the store in `dir`: the value of `--name`,
149/// or else the last segment of `dir`. It refuses a name that is empty or
150/// that is not a slug.
151fn name_of(opts: &InitOptions, dir: &RepoPath) -> Result<String> {
152    // sokf-implements: CLI-2_AC-3
153    let name = opts
154        .name
155        .clone()
156        .unwrap_or_else(|| dir.file_name().to_string());
157    // sokf-implements: CLI-2_AC-15
158    if name.is_empty() {
159        return Err(Error::Init("--name is empty".into()));
160    }
161    // sokf-implements: CLI-2_AC-18
162    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
174/// `scope_of` returns the scope of the store: the value of `--scope`, or
175/// else the owner in the URL of the git remote `origin`. It refuses a scope
176/// that is not a slug, and a missing scope that the remote can't supply.
177// sokf-implements: CLI-2_AC-16
178// sokf-implements: CLI-2_AC-17
179// sokf-implements: CLI-2_AC-18
180// sokf-implements: CLI-2_AC-19
181fn 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
195/// `check_identity` refuses the identity `scope/name` when a store of
196/// `existing` holds it or once held it.
197fn check_identity(root: &RepoRoot, existing: &[RepoPath], scope: &str, name: &str) -> Result<()> {
198    // The identity of a store is unique among the roots (SOKF_FORMAT_12). The
199    // default name, the last segment of the directory, is the name most likely
200    // to clash with another store.
201    // sokf-implements: CLI-2_AC-10
202    // sokf-implements: CLI-2_AC-20
203    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        // A reference to a former identity still resolves to its store
218        // (SOKF_FORMAT_12), so a new store can't take that identity.
219        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
232/// `hand_written_indexes` returns each `index.md` under `dir` that is not in
233/// the generated form of an index, ordered by path. `--fix` leaves such a
234/// file as it is (`SOKF_VALIDATION_56`). The walk follows no symbolic link.
235// sokf-implements: CLI-2_AC-32
236fn 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                // A file that isn't UTF-8 text is no generated index either.
252                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
264/// `remote_owner` returns the owner in the URL of the git remote `origin`,
265/// in lower case, when the owner is a slug. For example,
266/// `https://github.com/ncoderz/sokf`, `git@github.com:ncoderz/sokf.git`, and
267/// `ssh://git@host/ncoderz/sokf` all return `ncoderz`. It reads the remote
268/// of the repository at `root`, whatever `GIT_DIR` the environment holds.
269fn 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
279/// `owner_of` returns the owner in a remote URL, which is the first segment
280/// of its path, in lower case, when the owner is a slug.
281// sokf-implements: CLI-2_AC-28
282fn 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    // sokf-tests: CLI-2_AC-13
323    // sokf-tests: CLI-2_AC-14
324    // sokf-tests: CLI-2_AC-15
325    // sokf-tests: CLI-2_AC-18
326    // sokf-tests: CLI-2_AC-30
327    // sokf-tests: CLI-2_AC-33
328    // sokf-tests: CONF-1_AC-3
329    // sokf-tests: CLI-9_AC-1
330    #[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    // sokf-tests: CLI-2_AC-3
375    // sokf-tests: CLI-2_AC-8
376    #[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    // sokf-tests: CLI-2_AC-17
397    #[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    // sokf-tests: CLI-2_AC-20
412    #[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}