1
//! The declared directory of shipped source files (`.org` with `lisp` blocks,
2
//! `.nms`, `.lisp`), scanned for string literals that name an entity.
3

            
4
use std::path::Path;
5

            
6
use nomiscript::{Expr, Reader};
7
use uuid::Uuid;
8

            
9
use super::templates::judge;
10
use super::{Finding, Subject, TenantReport};
11
use crate::lookup_log::{Lookup, LookupKind};
12
use crate::resolve::Directory;
13

            
14
#[derive(Debug)]
15
pub struct Source {
16
    pub name: String,
17
    pub lookups: Vec<Lookup>,
18
}
19

            
20
/// The lisp text of an `.org` file: the bodies of its `lisp` source blocks.
21
2
fn lisp_blocks(org: &str) -> String {
22
2
    let mut inside = false;
23
2
    let mut text = String::new();
24
2
    for line in org.lines() {
25
16
        let directive = line.trim_start().to_ascii_lowercase();
26
16
        match (inside, directive.as_str()) {
27
12
            (false, d) if d.starts_with("#+begin_src lisp") => inside = true,
28
4
            (true, d) if d.starts_with("#+end_src") => inside = false,
29
            (true, _) => {
30
2
                text.push_str(line);
31
2
                text.push('\n');
32
            }
33
10
            _ => {}
34
        }
35
    }
36
2
    text
37
2
}
38

            
39
17
fn is_head(items: &[Expr], names: &[&str]) -> bool {
40
17
    matches!(items.first(), Some(Expr::Symbol(head)) if names.iter().any(|n| head.eq_ignore_ascii_case(n)))
41
17
}
42

            
43
7
fn keyed_kind(keyword: &str) -> Option<LookupKind> {
44
7
    match keyword
45
7
        .trim_start_matches(':')
46
7
        .to_ascii_lowercase()
47
7
        .as_str()
48
    {
49
3
        "from" | "to" => Some(LookupKind::Account),
50
3
        "from-commodity" | "to-commodity" => Some(LookupKind::Commodity),
51
1
        _ => None,
52
    }
53
7
}
54

            
55
/// The lookups one list form makes: `(get-account "k")`, `(get-commodity "k")`
56
/// or the `:from` / `:to` / `:from-commodity` / `:to-commodity` keys of a
57
/// logical row.
58
28
fn form_lookups(items: &[Expr]) -> Vec<Lookup> {
59
28
    let head = match items {
60
14
        [Expr::Symbol(_), Expr::String(key), ..] if is_head(items, &["get-account"]) => {
61
11
            Some((LookupKind::Account, key, false))
62
        }
63
3
        [Expr::Symbol(_), Expr::String(key), ..] if is_head(items, &["get-commodity"]) => {
64
2
            Some((LookupKind::Commodity, key, false))
65
        }
66
15
        _ => None,
67
    };
68
44
    let keyed = items.windows(2).filter_map(|pair| match pair {
69
7
        [Expr::Keyword(name), Expr::String(key)] => Some((keyed_kind(name)?, key, true)),
70
37
        _ => None,
71
44
    });
72
28
    head.into_iter()
73
28
        .chain(keyed)
74
        .map(|(kind, key, row_key)| Lookup {
75
19
            kind,
76
19
            key: key.clone(),
77
19
            row_key,
78
19
        })
79
        .collect()
80
28
}
81

            
82
13
fn lookups(source: &str) -> Result<Vec<Lookup>, String> {
83
13
    let program = Reader::parse(source).map_err(|err| format!("does not parse: {err}"))?;
84
11
    let mut found: Vec<Lookup> = Vec::new();
85
11
    let mut pending: Vec<&Expr> = program.exprs.iter().collect();
86
105
    while let Some(expr) = pending.pop() {
87
94
        match expr {
88
            Expr::List(items) => {
89
28
                found.extend(form_lookups(items));
90
28
                pending.extend(items);
91
            }
92
            Expr::Cons(car, cdr) => pending.extend([&**car, &**cdr]),
93
            Expr::Quote(inner)
94
            | Expr::Quasiquote(inner)
95
            | Expr::Unquote(inner)
96
            | Expr::UnquoteSplicing(inner)
97
2
            | Expr::Lambda(_, inner) => pending.push(inner),
98
64
            _ => {}
99
        }
100
    }
101
11
    Ok(found)
102
13
}
103

            
104
10
fn load_file(path: &Path) -> Result<Option<Source>, String> {
105
10
    let extension = path.extension().and_then(|e| e.to_str());
106
10
    if !matches!(extension, Some("org" | "nms" | "lisp")) {
107
1
        return Ok(None);
108
9
    }
109
9
    let text = std::fs::read_to_string(path).map_err(|err| format!("cannot read: {err}"))?;
110
9
    let code = match extension {
111
1
        Some("org") => lisp_blocks(&text),
112
8
        _ => text,
113
    };
114
    Ok(Some(Source {
115
9
        name: path.display().to_string(),
116
9
        lookups: lookups(&code)?,
117
    }))
118
10
}
119

            
120
2
fn unreadable(path: &Path, reason: String) -> Finding {
121
2
    Finding {
122
2
        user: None,
123
2
        subject: Subject::Source(path.display().to_string()),
124
2
        reason,
125
2
    }
126
2
}
127

            
128
/// The sources of `dir` in name order, and a finding for each that cannot be
129
/// read, or for the directory itself.
130
7
pub fn load(dir: &Path) -> (Vec<Source>, Vec<Finding>) {
131
7
    let entries = match std::fs::read_dir(dir) {
132
6
        Ok(entries) => entries,
133
        Err(err) => {
134
1
            return (
135
1
                Vec::new(),
136
1
                vec![unreadable(dir, format!("cannot list: {err}"))],
137
1
            );
138
        }
139
    };
140
6
    let mut paths: Vec<_> = entries
141
11
        .filter_map(|entry| Some(entry.ok()?.path()))
142
        .collect();
143
6
    paths.sort();
144
6
    let mut sources = Vec::new();
145
6
    let mut findings = Vec::new();
146
11
    let mirrors = |path: &std::path::PathBuf| {
147
11
        path.extension().is_some_and(|e| e == "nms") && path.with_extension("org").is_file()
148
11
    };
149
11
    for path in paths.iter().filter(|path| path.is_file() && !mirrors(path)) {
150
10
        match load_file(path) {
151
9
            Ok(source) => sources.extend(source),
152
1
            Err(reason) => findings.push(unreadable(path, reason)),
153
        }
154
    }
155
6
    (sources, findings)
156
7
}
157

            
158
9
pub(super) fn check(
159
9
    user: Uuid,
160
9
    directory: &Directory,
161
9
    declared: &[Source],
162
9
    report: &mut TenantReport,
163
9
) {
164
9
    report.coverage.sources = declared.len();
165
9
    for source in declared {
166
6
        let subject = Subject::Source(source.name.clone());
167
6
        judge(user, &subject, directory, source.lookups.clone(), report);
168
    }
169
9
}
170

            
171
#[cfg(test)]
172
mod tests;