sokf-core 0.5.1

sokf-core holds the logic of the sokf command-line tool: it loads and validates Superdev Open Knowledge Format (SOKF) knowledge stores, and runs each sokf command.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! This module reads and writes `/.sokf/packs.lock`, the record of each
//! schema pack that `sokf pack sync` copied into the repository (CONF-8).

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use super::eol::{is_base, normalise};
use crate::{Error, RepoPath, RepoRoot, Result, source::read_optional};

/// `HEADER` is the comment at the top of the lock.
const HEADER: &str = "# sokf pack sync writes this file. Do not edit it.\n";

/// `LOCK_VERSION` is the version of the lock's format that this tool reads
/// and writes. A lock without `lock-version` has the version 1.
pub const LOCK_VERSION: u32 = 3;

/// `lock_path` returns the path of the lock.
pub fn lock_path() -> RepoPath {
    RepoPath::parse("/.sokf/packs.lock").expect("literal")
}

/// `PACKS_DIR` is the directory, relative to the repository root, that holds
/// a directory for each pack: its formats file and its base copies.
pub const PACKS_DIR: &str = ".sokf/packs";

/// `pack_dir` returns the directory of the pack `name` under `/.sokf/packs/`.
pub fn pack_dir(name: &str) -> RepoPath {
    RepoPath::parse(&format!("/{PACKS_DIR}/{name}")).expect("a pack name is a slug")
}

/// `base_path` returns the path of the base copy of the file `rel` of the
/// pack `name`.
pub fn base_path(name: &str, rel: &str) -> RepoPath {
    RepoPath::parse(&format!("/{PACKS_DIR}/{name}/base/{rel}")).expect("a pack path is relative")
}

/// `formats_of` returns the path of the formats file of the pack `name`.
pub fn formats_of(name: &str) -> RepoPath {
    RepoPath::parse(&format!("/{PACKS_DIR}/{name}/formats.yaml")).expect("a pack name is a slug")
}

/// `instructions_of` returns the path of the copy of the instructions
/// fragment of the pack `name`, which `sokf harness install` reads.
pub fn instructions_of(name: &str) -> RepoPath {
    RepoPath::parse(&format!("/{PACKS_DIR}/{name}/instructions.md")).expect("a pack name is a slug")
}

/// `fragments` returns the instructions fragment of each pack in `lock` that
/// has one, by the pack's name, in the order of the packs, from the lowest
/// to the highest. It reads only the configuration and the copies under
/// `/.sokf/packs/`, so it needs no network.
// sokf-implements: CLI-3_AC-74
pub fn fragments(root: &RepoRoot, lock: &Lock) -> Result<Vec<(String, String)>> {
    let mut out = Vec::new();
    for name in &ordered(root, lock) {
        if let Some(text) = read_optional(&instructions_of(name).to_fs(root))? {
            out.push((name.clone(), text));
        }
    }
    Ok(out)
}

/// `ordered` returns the names of the packs of `lock` in the order of the
/// packs: the packs that the configuration declares, sorted by their
/// dependencies and their entries, then any other pack by its name.
/// Dependencies that form a cycle leave the declared packs in the order of
/// their entries, and a configuration that doesn't parse leaves every pack
/// in the order of its name, because a sync refuses both before it writes.
pub(crate) fn ordered(root: &RepoRoot, lock: &Lock) -> Vec<String> {
    let list: Vec<String> = crate::config::read_packs(root)
        .unwrap_or_default()
        .into_iter()
        .map(|e| e.name)
        .filter(|n| lock.packs.contains_key(n))
        .collect();
    let depends = lock
        .packs
        .iter()
        .map(|(n, p)| (n.clone(), p.depends.keys().cloned().collect()))
        .collect();
    let mut out = super::order::precedence(&list, &depends).unwrap_or(list);
    for name in lock.packs.keys() {
        if !out.contains(name) {
            out.push(name.clone());
        }
    }
    out
}

/// A `Lock` is the content of `/.sokf/packs.lock`: one entry for each pack,
/// by name.
// sokf-implements: CONF-8_AC-1
// sokf:begin lock
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Lock {
    /// The version of the lock's format.
    #[serde(rename = "lock-version", default = "first_version")]
    pub lock_version: u32,
    /// The packs, by name.
    #[serde(default)]
    pub packs: BTreeMap<String, LockedPack>,
}

/// A `LockedPack` is the record of one pack.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedPack {
    /// The source: a git URL or path, or `builtin:<NAME>`.
    pub source: String,
    /// The branch, tag, or commit of a git source.
    #[serde(rename = "ref", default, skip_serializing_if = "Option::is_none")]
    pub git_ref: Option<String>,
    /// The pack's directory in the source, when it isn't the source's root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// The knowledge root that holds the pack's schemas and documents, when
    /// the pack has any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store: Option<String>,
    /// The resolved commit, or the tool's version for an embedded pack.
    pub commit: String,
    /// The version that the pack's manifest gives.
    pub version: String,
    /// The packs that the pack depends on, each with its oldest version.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub depends: BTreeMap<String, String>,
    /// The pack's files, by their paths in the pack.
    #[serde(default)]
    pub files: BTreeMap<String, LockedFile>,
}

/// A `LockedFile` is the record of one file of a pack.
// sokf-implements: CONF-8_AC-2
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LockedFile {
    /// The file's path in the repository.
    pub path: String,
    /// The hash of the file's base: the pack's version of the file at the
    /// last sync, as `fnv1a64:<HEX>`.
    pub base: String,
    /// Whether the pack's version of a file of `files/` is executable.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub executable: bool,
    /// The pack higher in the order that owns the file's destination or
    /// its schema type, so that the file holds that pack's version and not
    /// this one.
    #[serde(
        rename = "shadowed-by",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub shadowed_by: Option<String>,
    /// Whether the last sync changed this pack's version of a shadowed file.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub changed: bool,
    /// The edit or the deletion of the file that a maintainer accepted with
    /// `sokf pack accept`, so that `pack status --check` passes on it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accepted: Option<Accepted>,
}

/// An `Accepted` is the record of an accepted edit: the version of the file
/// that the project keeps on purpose, or its deletion, with the reason.
// sokf-implements: CONF-8_AC-8
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Accepted {
    /// The hash of the accepted version, with each CRLF read as LF, as
    /// `fnv1a64:<HEX>`, or none for an accepted deletion.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
    /// Whether the accepted version of a file of `files/` is executable.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub executable: bool,
    /// Whether the project deleted the file on purpose.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub deleted: bool,
    /// Why the project keeps the edit.
    pub note: String,
}
// sokf:end lock

impl Accepted {
    /// `of` returns the acceptance of a file that holds `bytes`, or of a
    /// deleted file when `bytes` is none, with the executable bit `bit` of a
    /// file of `files/`.
    pub fn of(bytes: Option<&[u8]>, bit: bool, note: &str) -> Accepted {
        Accepted {
            hash: bytes.map(|b| hash_of(&normalise(b))),
            executable: bytes.is_some() && bit,
            deleted: bytes.is_none(),
            note: note.to_string(),
        }
    }

    /// `holds` returns whether a file that holds `bytes`, or that is deleted
    /// when `bytes` is none, holds the accepted version. `bit` is the
    /// executable bit of a file of `files/`, and none for any other file.
    // sokf-implements: CLI-13_AC-101
    pub fn holds(&self, bytes: Option<&[u8]>, bit: Option<bool>) -> bool {
        match (bytes, &self.hash) {
            (None, _) => self.deleted,
            (Some(_), None) => false,
            (Some(b), Some(h)) => is_base(b, h) && bit.is_none_or(|x| x == self.executable),
        }
    }
}

impl Default for Lock {
    fn default() -> Self {
        Lock {
            lock_version: LOCK_VERSION,
            packs: BTreeMap::new(),
        }
    }
}

/// `first_version` is the version of a lock without `lock-version`.
fn first_version() -> u32 {
    1
}

impl Lock {
    /// `owner_of` returns the pack whose version of the destination `dest`
    /// the file holds, which is the one pack whose record of it isn't
    /// shadowed, and the file's path in that pack.
    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 && f.shadowed_by.is_none())
                .map(|(rel, _)| (name.as_str(), rel.as_str()))
        })
    }
}

/// `hash_of` returns the hash of `bytes` as the lock records it.
pub fn hash_of(bytes: &[u8]) -> String {
    format!("fnv1a64:{:016x}", crate::source::fnv1a64(bytes))
}

/// `read_lock` reads the lock, and returns an empty lock when the file is
/// absent. It refuses a lock that doesn't parse.
// sokf-implements: CONF-8_AC-3
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());
    };
    // The version is read first, so that a lock of a newer format gives an
    // error that says to upgrade, and not one about an unknown key.
    // sokf-implements: CONF-8_AC-7
    let table: toml::Table =
        toml::from_str(&text).map_err(|e| Error::config(path.clone(), e.message()))?;
    if let Some(v) = table.get("lock-version").and_then(toml::Value::as_integer)
        && v > i64::from(LOCK_VERSION)
    {
        return Err(Error::config(
            path,
            format!(
                "the lock has the format {v}, and this sokf reads the format {LOCK_VERSION} at most; upgrade sokf"
            ),
        ));
    }
    let mut 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"),
            ));
        }
    }
    // A lock that this tool writes again takes its format.
    lock.lock_version = LOCK_VERSION;
    Ok(lock)
}

/// `lock_text` returns the text of the lock, with its header and the
/// version of its format.
// sokf-implements: CONF-8_AC-6
pub fn lock_text(lock: &Lock) -> Result<String> {
    let lock = Lock {
        lock_version: LOCK_VERSION,
        ..lock.clone()
    };
    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: Some("/knowledge".into()),
            commit: "0123abcd".into(),
            version: "1.0.0".into(),
            depends: BTreeMap::new(),
            files: BTreeMap::new(),
        };
        pack.files.insert(
            "schemas/issue.md".into(),
            LockedFile {
                path: "/knowledge/schemas/issue.md".into(),
                base: hash_of(b"x"),
                executable: false,
                shadowed_by: None,
                changed: false,
                accepted: None,
            },
        );
        pack.files.insert(
            "files/.gitignore".into(),
            LockedFile {
                path: "/.gitignore".into(),
                base: hash_of(b"y"),
                executable: false,
                shadowed_by: None,
                changed: false,
                accepted: Some(Accepted::of(Some(b"y\nz\n"), false, "the project's binary")),
            },
        );
        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("lock-version = 3\n"), "{text}");
        assert!(text.contains("note = \"the project's binary\""), "{text}");
        assert!(!text.contains("deleted"), "{text}");
        assert!(!text.contains("executable"), "{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);
    }

    // sokf-tests: CLI-13_AC-101
    #[test]
    fn a_file_holds_its_accepted_version_with_either_line_ending() {
        let a = Accepted::of(Some(b"a\nb\n"), true, "why");
        assert!(a.holds(Some(b"a\nb\n"), Some(true)));
        assert!(a.holds(Some(b"a\r\nb\r\n"), Some(true)));
        assert!(a.holds(Some(b"a\nb\n"), None));
        assert!(!a.holds(Some(b"a\nb\n"), Some(false)));
        assert!(!a.holds(Some(b"a\nc\n"), Some(true)));
        assert!(!a.holds(None, None));
        let crlf = Accepted::of(Some(b"a\r\nb\r\n"), false, "why");
        assert!(crlf.holds(Some(b"a\nb\n"), None));
        let gone = Accepted::of(None, true, "unused");
        assert!(gone.deleted && !gone.executable && gone.hash.is_none());
        assert!(gone.holds(None, None));
        assert!(!gone.holds(Some(b""), None));
    }

    // sokf-tests: CONF-8_AC-6
    #[test]
    fn a_lock_of_the_version_2_reads_and_writes_the_version_3() {
        let dir = crate::test_support::fresh_dir("lock-v2");
        let root = RepoRoot::new(dir.clone());
        std::fs::create_dir_all(dir.join(".sokf")).unwrap();
        std::fs::write(
            dir.join(".sokf/packs.lock"),
            "lock-version = 2\n[packs.p]\nsource = \"builtin:p\"\ncommit = \"1\"\nversion = \"1\"\n",
        )
        .unwrap();
        let lock = read_lock(&root).unwrap();
        assert!(lock_text(&lock).unwrap().contains("lock-version = 3\n"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[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");
    }
}