Skip to main content

sokf_core/cache/
markers.rs

1//! This module finds the markers in files outside the knowledge roots and
2//! keeps them in the store. The store holds one row for each marker or
3//! fault that a scan found, so that a later run can check the file again
4//! without reading it.
5
6use rusqlite::params;
7
8use super::{Cache, conn::Conn, sync::SyncState};
9use crate::{
10    FileKind, RepoPath,
11    markers::{IgnoreFault, MarkerRow, RowKind},
12};
13
14/// `encode` returns the code that the store keeps for a row's kind and
15/// the text of the row's two text columns.
16fn encode(kind: &RowKind) -> (i64, &str, &str) {
17    match kind {
18        RowKind::Marker { rel, target } => (0, rel, target),
19        RowKind::Malformed(tag) => (1, tag, ""),
20        RowKind::Rel(tag) => (6, tag, ""),
21        RowKind::Ignore(IgnoreFault::BeginInside) => (3, "", ""),
22        RowKind::Ignore(IgnoreFault::EndOutside) => (4, "", ""),
23        RowKind::Ignore(IgnoreFault::NeverEnds) => (5, "", ""),
24    }
25}
26
27/// `decode` returns the kind of a stored row, or `None` for a code that no
28/// release writes.
29fn decode(code: i64, rel: String, target: String) -> Option<RowKind> {
30    Some(match code {
31        0 => RowKind::Marker { rel, target },
32        1 => RowKind::Malformed(rel),
33        3 => RowKind::Ignore(IgnoreFault::BeginInside),
34        4 => RowKind::Ignore(IgnoreFault::EndOutside),
35        5 => RowKind::Ignore(IgnoreFault::NeverEnds),
36        6 => RowKind::Rel(rel),
37        _ => return None,
38    })
39}
40
41impl Cache {
42    /// `outside_to_read` returns the files outside the knowledge roots that
43    /// this run must read for markers. A file is one of them when:
44    ///
45    /// - it is new
46    /// - its stat changed
47    /// - its modification time is so close to the last sync that a change
48    ///   might not show in the stat
49    // sokf-implements: CACHE-1_AC-32
50    pub fn outside_to_read(&self) -> Vec<RepoPath> {
51        let state = self.state.borrow();
52        let mut paths: Vec<RepoPath> = state
53            .known
54            .keys()
55            .filter(|p| {
56                Self::listed(&state, p).is_some_and(|(kind, root)| {
57                    root.is_none() && super::sync::kind_of(kind) == FileKind::Candidate
58                })
59            })
60            .cloned()
61            .collect();
62        paths.sort();
63        paths
64    }
65
66    /// `unread` records a file that the scan could not read. The store keeps
67    /// the file's old row, so that the next run reads the file again, for
68    /// example when its permissions change and its stat does not.
69    pub fn unread(&self, path: &RepoPath) {
70        self.state.borrow_mut().candidates.remove(path);
71    }
72
73    /// `record_markers` records the markers that a scan of `path` found. The
74    /// commit writes them in place of the rows that the store holds for the
75    /// file.
76    pub fn record_markers(&self, path: &RepoPath, rows: Vec<MarkerRow>) {
77        self.state.borrow_mut().markers.insert(path.clone(), rows);
78    }
79
80    /// `stored_markers` returns the markers of `path` that the store keeps,
81    /// in line order.
82    // sokf-implements: CACHE-1_AC-33
83    pub fn stored_markers(&self, path: &RepoPath) -> Vec<MarkerRow> {
84        let mut out: Vec<MarkerRow> = self
85            .conn()
86            .rows(
87                "SELECT line, kind, rel, target FROM markers WHERE path = ?1",
88                [path.as_str()],
89                |r| {
90                    let line = r.get::<_, usize>(0)?;
91                    let kind = decode(r.get(1)?, r.get(2)?, r.get(3)?);
92                    Ok(kind.map(|kind| MarkerRow { line, kind }))
93                },
94            )
95            .into_iter()
96            .flatten()
97            .collect();
98        out.sort();
99        out
100    }
101
102    /// `has_markers` reports whether the store holds a row for any marker or
103    /// fault in `path`.
104    pub fn has_markers(&self, path: &RepoPath) -> bool {
105        self.conn()
106            .query_row(
107                "SELECT 1 FROM markers WHERE path = ?1 LIMIT 1",
108                [path.as_str()],
109                |_| Ok(()),
110            )
111            .is_ok()
112    }
113
114    /// `commit_markers` writes the markers inside the commit's transaction.
115    /// It replaces all the rows of each file that the run scanned, and it
116    /// deletes the rows of each removed file.
117    pub(super) fn commit_markers(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
118        let mut delete = conn.prepare("DELETE FROM markers WHERE path = ?1")?;
119        for path in &state.removed {
120            delete.execute([path.as_str()])?;
121        }
122        let mut put = conn.prepare(
123            "INSERT INTO markers (path, line, kind, rel, target) VALUES (?1, ?2, ?3, ?4, ?5)",
124        )?;
125        for (path, rows) in &state.markers {
126            delete.execute([path.as_str()])?;
127            for row in rows {
128                let (code, rel, target) = encode(&row.kind);
129                put.execute(params![path.as_str(), row.line, code, rel, target])?;
130            }
131        }
132        Ok(())
133    }
134}