Skip to main content

sokf_core/model/
archive.rs

1//! This module reads `archived`, the key with which a schema declares which
2//! documents of its type are archived. It reads `archived` from a schema
3//! before sokf compiles the schema, in the same way that it reads the
4//! globs. As a result, the graph can leave out archived documents without
5//! compiling a schema or reading a document (CLI-7_AC-67).
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use super::{Document, Model};
10use crate::{RepoPath, Spanned, Yaml};
11
12/// `Archived` says which documents of a type are archived.
13#[derive(Debug, Clone, PartialEq, Eq, Default)]
14pub enum Archived {
15    /// No document is archived, because the schema declares no `archived`.
16    #[default]
17    None,
18    /// Every document is archived, because the schema has no lifecycle and
19    /// declares `archived: true`.
20    All,
21    /// A document is archived when it is in an archived state of any
22    /// dimension. Each entry holds the key of a dimension and its archived
23    /// states, in lifecycle order.
24    States(Vec<(String, Vec<String>)>),
25}
26
27impl Archived {
28    /// `of_schema` returns the `archived` of the schema `yaml`: `All` for
29    /// `archived: true` on a schema with no lifecycle, `States` for the
30    /// `archived` lists of its lifecycle dimensions, or `None` when it
31    /// declares neither.
32    pub fn of_schema(yaml: &Spanned) -> Archived {
33        // The schema grammar rejects `archived: true` beside a lifecycle, so
34        // for such a schema no document is archived.
35        if yaml.get("archived").and_then(Spanned::as_bool) == Some(true) {
36            let lifecycle = yaml
37                .get("lifecycle")
38                .and_then(Spanned::as_seq)
39                .is_some_and(|d| !d.is_empty());
40            return if lifecycle {
41                Archived::None
42            } else {
43                Archived::All
44            };
45        }
46        let dimensions: Vec<(String, Vec<String>)> = yaml
47            .get("lifecycle")
48            .and_then(Spanned::as_seq)
49            .unwrap_or(&[])
50            .iter()
51            .filter_map(|d| {
52                let key = d.get("key")?.as_str()?.to_string();
53                let states = d.get("archived")?.as_str_or_list()?;
54                Some((key, states))
55            })
56            .collect();
57        if dimensions.is_empty() {
58            Archived::None
59        } else {
60            Archived::States(dimensions)
61        }
62    }
63
64    /// `encode` returns the text that the store keeps: an empty string for
65    /// `None`, `*` for `All`, or one line for each dimension, with the
66    /// dimension's key and its states separated by tabs.
67    pub fn encode(&self) -> String {
68        match self {
69            Archived::None => String::new(),
70            Archived::All => "*".to_string(),
71            Archived::States(dimensions) => dimensions
72                .iter()
73                .map(|(key, states)| format!("{key}\t{}", states.join("\t")))
74                .collect::<Vec<_>>()
75                .join("\n"),
76        }
77    }
78
79    /// `decode` returns the `Archived` from which `encode` wrote `text`.
80    pub fn decode(text: &str) -> Archived {
81        match text {
82            "" => Archived::None,
83            "*" => Archived::All,
84            _ => Archived::States(
85                text.lines()
86                    .filter_map(|line| {
87                        let mut parts = line.split('\t');
88                        let key = parts.next()?.to_string();
89                        Some((key, parts.map(str::to_string).collect()))
90                    })
91                    .collect(),
92            ),
93        }
94    }
95
96    /// `holds` says whether a document is archived, where `values` holds
97    /// the scalar values of the document's frontmatter. For `All`, every
98    /// document is archived. For `States`, a document is archived when its
99    /// value for the key of any dimension is one of that dimension's
100    /// archived states.
101    // sokf-implements: EXT-2_AC-4
102    // sokf-implements: EXT-7_AC-3
103    pub fn holds(&self, values: &[(String, String)]) -> bool {
104        match self {
105            Archived::None => false,
106            Archived::All => true,
107            Archived::States(dimensions) => dimensions.iter().any(|(key, states)| {
108                values
109                    .iter()
110                    .find(|(k, _)| k == key)
111                    .is_some_and(|(_, v)| states.contains(v))
112            }),
113        }
114    }
115}
116
117/// `scalars` returns the scalar values of a document's frontmatter that the
118/// store keeps, so that the graph can find a lifecycle state without
119/// reading the file. It returns each top-level key whose value is a
120/// string, an integer, or a boolean, with the value as text. It leaves out
121/// `id`, `type`, `title`, and `description`, which the store keeps as
122/// columns.
123pub fn scalars(doc: &Document) -> Vec<(String, String)> {
124    scalars_of(doc.frontmatter.as_ref())
125}
126
127/// `scalars_of` returns the scalar values of `frontmatter`, as `scalars`
128/// does for a document.
129pub fn scalars_of(frontmatter: Option<&Spanned>) -> Vec<(String, String)> {
130    let Some(entries) = frontmatter.and_then(Spanned::as_map) else {
131        return Vec::new();
132    };
133    entries
134        .iter()
135        .filter(|(k, _)| !matches!(k.value.as_str(), "id" | "type" | "title" | "description"))
136        .filter_map(|(k, v)| {
137            let text = match &v.value {
138                Yaml::Str(s) => s.clone(),
139                Yaml::Int(i) => i.to_string(),
140                Yaml::Bool(b) => b.to_string(),
141                _ => return None,
142            };
143            Some((k.value.clone(), text))
144        })
145        .collect()
146}
147
148/// `encode_scalars` returns the text that the store keeps for `scalars`:
149/// one line for each key. Each line holds the key and its value separated
150/// by a tab. It writes each line break in a value as a space.
151pub fn encode_scalars(scalars: &[(String, String)]) -> String {
152    scalars
153        .iter()
154        .map(|(k, v)| format!("{k}\t{}", v.replace(['\n', '\r'], " ")))
155        .collect::<Vec<_>>()
156        .join("\n")
157}
158
159/// `decode_scalars` returns the scalars from which `encode_scalars` wrote
160/// `text`.
161pub fn decode_scalars(text: &str) -> Vec<(String, String)> {
162    text.lines()
163        .filter_map(|l| l.split_once('\t'))
164        .map(|(k, v)| (k.to_string(), v.to_string()))
165        .collect()
166}
167
168impl Model {
169    /// `archive_rules` returns the `archived` of each type, in each store,
170    /// whose schema declares one.
171    fn archive_rules(&self) -> BTreeMap<(usize, String), Archived> {
172        let mut rules = BTreeMap::new();
173        for (k, knowledge) in self.knowledges.iter().enumerate() {
174            // A store's own schemas, then those that it inherits, whose
175            // types it declares in no schema of its own (SOKF_SCHEMA_96).
176            let own = knowledge.schemas.iter();
177            let inherited = self.inherited(k).into_iter().map(|r| self.schema(r));
178            for schema in own.chain(inherited) {
179                if let Some(t) = &schema.type_const
180                    && schema.archived != Archived::None
181                {
182                    rules
183                        .entry((k, t.clone()))
184                        .or_insert_with(|| schema.archived.clone());
185                }
186            }
187        }
188        rules
189    }
190
191    /// `is_archived` returns whether a document of store `knowledge` is
192    /// archived, from its type and its frontmatter, as `archived_documents`
193    /// decides it.
194    pub fn is_archived(
195        &self,
196        knowledge: usize,
197        type_name: Option<&str>,
198        frontmatter: Option<&Spanned>,
199    ) -> bool {
200        let Some(type_name) = type_name else {
201            return false;
202        };
203        self.archive_rules()
204            .get(&(knowledge, type_name.to_string()))
205            .is_some_and(|rule| rule.holds(&scalars_of(frontmatter)))
206    }
207
208    /// `archived_documents` returns the archived documents of every store.
209    /// For each document that this run loaded, it reads the frontmatter to
210    /// decide whether the document is archived. For every other document, it
211    /// reads the store's rows.
212    // sokf-implements: CLI-7_AC-67
213    pub fn archived_documents(&self) -> BTreeSet<RepoPath> {
214        let rules = self.archive_rules();
215        let mut out = BTreeSet::new();
216        if rules.is_empty() {
217            return out;
218        }
219        let mut held = BTreeSet::new();
220        for (k, doc) in self.documents() {
221            held.insert(doc.path.clone());
222            let Some(rule) = doc.type_name().and_then(|t| rules.get(&(k, t.to_string()))) else {
223                continue;
224            };
225            if rule.holds(&scalars(doc)) {
226                out.insert(doc.path.clone());
227            }
228        }
229        if let Some(fallback) = &self.fallback {
230            for ((k, type_name), rule) in &rules {
231                for (path, values) in fallback.scalars_of_type(*k, type_name) {
232                    if held.contains(&path) {
233                        continue;
234                    }
235                    if rule.holds(&values) {
236                        out.insert(path);
237                    }
238                }
239            }
240        }
241        out
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    fn schema(text: &str) -> Spanned {
250        crate::yaml::parse(text, 1).unwrap()
251    }
252
253    // sokf-tests: EXT-2_AC-4
254    // sokf-tests: EXT-7_AC-3
255    #[test]
256    fn archived_reads_encodes_and_holds() {
257        let states = Archived::of_schema(&schema(
258            "lifecycle:\n  - key: state\n    states: [open, closed]\n    archived: [closed]\n  - key: kind\n    states: [a]\n",
259        ));
260        assert_eq!(
261            states,
262            Archived::States(vec![("state".into(), vec!["closed".into()])])
263        );
264        assert_eq!(Archived::decode(&states.encode()), states);
265        let state = |v: &str| [("state".to_string(), v.to_string())];
266        assert!(states.holds(&state("closed")));
267        assert!(!states.holds(&state("open")));
268        assert!(!states.holds(&[]));
269        let all = Archived::of_schema(&schema("archived: true\n"));
270        assert_eq!(all, Archived::All);
271        assert_eq!(Archived::decode(&all.encode()), all);
272        assert!(all.holds(&[]));
273        // An empty lifecycle counts as no lifecycle, so with `archived: true`
274        // every document is archived.
275        assert_eq!(
276            Archived::of_schema(&schema("lifecycle: []\narchived: true\n")),
277            Archived::All
278        );
279        let none = Archived::of_schema(&schema("archived: false\n"));
280        assert_eq!(none, Archived::None);
281        assert_eq!(Archived::decode(&none.encode()), none);
282        assert!(!none.holds(&state("x")));
283    }
284
285    #[test]
286    fn scalars_keep_the_values_the_columns_do_not() {
287        let source = crate::Source::from_text(
288            RepoPath::parse("/k/a.md").unwrap(),
289            "---\ntype: A\nid: a\ntitle: T\nstate: closed\nseq: 3\ndone: true\ntags: [x]\n---\n\n# T\n",
290        );
291        let parsed = super::super::parse_source(&source, super::super::ParseMode::Document);
292        let doc = Document::new(source, parsed);
293        let values = scalars(&doc);
294        assert_eq!(
295            values,
296            vec![
297                ("state".to_string(), "closed".to_string()),
298                ("seq".to_string(), "3".to_string()),
299                ("done".to_string(), "true".to_string()),
300            ]
301        );
302        assert_eq!(decode_scalars(&encode_scalars(&values)), values);
303    }
304}