Skip to main content

sokf_core/model/
plans.rs

1//! This module holds the files that the documents plan: the repository paths
2//! that a planning section of a document links while the document is in the
3//! states of its plan (`SOKF_SCHEMA_53`). A check accepts a planned path that
4//! doesn't exist yet, and every path under a planned directory
5//! (`SOKF_SCHEMA_55`).
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use super::{Model, Query};
10use crate::RepoPath;
11
12/// A `Planned` is one path that a document plans.
13#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
14pub struct Planned {
15    /// The path, without the trailing `/` characters of its link.
16    pub path: RepoPath,
17    /// Whether the link ends with `/`, so that the plan names a directory
18    /// and every path under it.
19    pub dir: bool,
20}
21
22impl Planned {
23    /// `key` returns the planned path as one line of text, the form in which
24    /// the store keeps it: the path, with a `/` after it for a directory.
25    pub fn key(&self) -> String {
26        if self.dir {
27            format!("{}/", self.path)
28        } else {
29            self.path.to_string()
30        }
31    }
32
33    /// `parse` reads the text that `key` returns.
34    pub fn parse(key: &str) -> Option<Planned> {
35        match key.strip_suffix('/').filter(|rest| !rest.is_empty()) {
36            Some(path) => Some(Planned {
37                path: RepoPath::parse(path)?,
38                dir: true,
39            }),
40            None => Some(Planned {
41                path: RepoPath::parse(key)?,
42                dir: false,
43            }),
44        }
45    }
46}
47
48/// `PlanIndex` maps each planned path to the documents that plan it.
49#[derive(Debug, Default, Clone, PartialEq, Eq)]
50pub struct PlanIndex {
51    by_target: BTreeMap<Planned, BTreeSet<RepoPath>>,
52}
53
54impl PlanIndex {
55    /// `add` records that the document at `planner` plans `target`.
56    pub fn add(&mut self, planner: &RepoPath, target: &Planned) {
57        self.by_target
58            .entry(target.clone())
59            .or_default()
60            .insert(planner.clone());
61    }
62
63    /// `contains` reports whether some document plans `target`: the path
64    /// itself, or a directory that holds it.
65    // sokf-implements: SOKF_SCHEMA_55
66    pub fn contains(&self, target: &RepoPath) -> bool {
67        let planned = |path: &RepoPath, dir: bool| {
68            self.by_target.contains_key(&Planned {
69                path: path.clone(),
70                dir,
71            })
72        };
73        planned(target, false)
74            || std::iter::successors(Some(target.clone()), RepoPath::parent)
75                .any(|path| planned(&path, true))
76    }
77
78    /// `targets` returns every planned path.
79    pub fn targets(&self) -> Vec<Planned> {
80        self.by_target.keys().cloned().collect()
81    }
82
83    /// `planners` returns the documents that plan `target`.
84    pub fn planners(&self, target: &Planned) -> Vec<RepoPath> {
85        self.by_target
86            .get(target)
87            .map(|p| p.iter().cloned().collect())
88            .unwrap_or_default()
89    }
90
91    /// `of` returns the paths that the document at `planner` plans.
92    pub fn of(&self, planner: &RepoPath) -> BTreeSet<Planned> {
93        self.by_target
94            .iter()
95            .filter(|(_, planners)| planners.contains(planner))
96            .map(|(target, _)| target.clone())
97            .collect()
98    }
99}
100
101impl Model {
102    /// `is_planned` reports whether a document plans a file at `path`, and
103    /// records the query for `path` and for each directory above it, so
104    /// that the reader is checked again when the plan of the path or of a
105    /// directory that holds it changes.
106    pub fn is_planned(&self, path: &RepoPath) -> bool {
107        for planned in std::iter::successors(Some(path.clone()), RepoPath::parent) {
108            self.note(Query::Planned(planned));
109        }
110        self.plans.contains(path)
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    fn planned(path: &str, dir: bool) -> Planned {
119        Planned {
120            path: RepoPath::parse(path).unwrap(),
121            dir,
122        }
123    }
124
125    #[test]
126    fn a_planned_path_keeps_its_slash_in_the_store() {
127        for (path, dir) in [("/a/b", false), ("/a/b", true), ("/", false), ("/", true)] {
128            let p = planned(path, dir);
129            assert_eq!(Planned::parse(&p.key()), Some(p.clone()), "{}", p.key());
130        }
131        assert_eq!(planned("/a", true).key(), "/a/");
132        assert_eq!(planned("/", true).key(), "//");
133    }
134
135    // sokf-tests: SOKF_SCHEMA_55
136    #[test]
137    fn a_planned_directory_plans_every_path_under_it() {
138        let mut plans = PlanIndex::default();
139        let planner = RepoPath::parse("/k/issue.md").unwrap();
140        plans.add(&planner, &planned("/x/fixtures", true));
141        plans.add(&planner, &planned("/y/one.rs", false));
142        let has = |p: &str| plans.contains(&RepoPath::parse(p).unwrap());
143        assert!(has("/x/fixtures"));
144        assert!(has("/x/fixtures/a.json"));
145        assert!(has("/x/fixtures/deep/b.json"));
146        assert!(!has("/x/fixturesmore"));
147        assert!(!has("/x"));
148        assert!(has("/y/one.rs"));
149        assert!(!has("/y/one.rs/under"));
150    }
151}