Lines
99.07 %
Functions
47.37 %
Branches
100 %
//! The declared directory of shipped source files (`.org` with `lisp` blocks,
//! `.nms`, `.lisp`), scanned for string literals that name an entity.
use std::path::Path;
use nomiscript::{Expr, Reader};
use uuid::Uuid;
use super::templates::judge;
use super::{Finding, Subject, TenantReport};
use crate::lookup_log::{Lookup, LookupKind};
use crate::resolve::Directory;
#[derive(Debug)]
pub struct Source {
pub name: String,
pub lookups: Vec<Lookup>,
}
/// The lisp text of an `.org` file: the bodies of its `lisp` source blocks.
fn lisp_blocks(org: &str) -> String {
let mut inside = false;
let mut text = String::new();
for line in org.lines() {
let directive = line.trim_start().to_ascii_lowercase();
match (inside, directive.as_str()) {
(false, d) if d.starts_with("#+begin_src lisp") => inside = true,
(true, d) if d.starts_with("#+end_src") => inside = false,
(true, _) => {
text.push_str(line);
text.push('\n');
_ => {}
text
fn is_head(items: &[Expr], names: &[&str]) -> bool {
matches!(items.first(), Some(Expr::Symbol(head)) if names.iter().any(|n| head.eq_ignore_ascii_case(n)))
fn keyed_kind(keyword: &str) -> Option<LookupKind> {
match keyword
.trim_start_matches(':')
.to_ascii_lowercase()
.as_str()
{
"from" | "to" => Some(LookupKind::Account),
"from-commodity" | "to-commodity" => Some(LookupKind::Commodity),
_ => None,
/// The lookups one list form makes: `(get-account "k")`, `(get-commodity "k")`
/// or the `:from` / `:to` / `:from-commodity` / `:to-commodity` keys of a
/// logical row.
fn form_lookups(items: &[Expr]) -> Vec<Lookup> {
let head = match items {
[Expr::Symbol(_), Expr::String(key), ..] if is_head(items, &["get-account"]) => {
Some((LookupKind::Account, key, false))
[Expr::Symbol(_), Expr::String(key), ..] if is_head(items, &["get-commodity"]) => {
Some((LookupKind::Commodity, key, false))
};
let keyed = items.windows(2).filter_map(|pair| match pair {
[Expr::Keyword(name), Expr::String(key)] => Some((keyed_kind(name)?, key, true)),
});
head.into_iter()
.chain(keyed)
.map(|(kind, key, row_key)| Lookup {
kind,
key: key.clone(),
row_key,
})
.collect()
fn lookups(source: &str) -> Result<Vec<Lookup>, String> {
let program = Reader::parse(source).map_err(|err| format!("does not parse: {err}"))?;
let mut found: Vec<Lookup> = Vec::new();
let mut pending: Vec<&Expr> = program.exprs.iter().collect();
while let Some(expr) = pending.pop() {
match expr {
Expr::List(items) => {
found.extend(form_lookups(items));
pending.extend(items);
Expr::Cons(car, cdr) => pending.extend([&**car, &**cdr]),
Expr::Quote(inner)
| Expr::Quasiquote(inner)
| Expr::Unquote(inner)
| Expr::UnquoteSplicing(inner)
| Expr::Lambda(_, inner) => pending.push(inner),
Ok(found)
fn load_file(path: &Path) -> Result<Option<Source>, String> {
let extension = path.extension().and_then(|e| e.to_str());
if !matches!(extension, Some("org" | "nms" | "lisp")) {
return Ok(None);
let text = std::fs::read_to_string(path).map_err(|err| format!("cannot read: {err}"))?;
let code = match extension {
Some("org") => lisp_blocks(&text),
_ => text,
Ok(Some(Source {
name: path.display().to_string(),
lookups: lookups(&code)?,
}))
fn unreadable(path: &Path, reason: String) -> Finding {
Finding {
user: None,
subject: Subject::Source(path.display().to_string()),
reason,
/// The sources of `dir` in name order, and a finding for each that cannot be
/// read, or for the directory itself.
pub fn load(dir: &Path) -> (Vec<Source>, Vec<Finding>) {
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(err) => {
return (
Vec::new(),
vec![unreadable(dir, format!("cannot list: {err}"))],
);
let mut paths: Vec<_> = entries
.filter_map(|entry| Some(entry.ok()?.path()))
.collect();
paths.sort();
let mut sources = Vec::new();
let mut findings = Vec::new();
let mirrors = |path: &std::path::PathBuf| {
path.extension().is_some_and(|e| e == "nms") && path.with_extension("org").is_file()
for path in paths.iter().filter(|path| path.is_file() && !mirrors(path)) {
match load_file(path) {
Ok(source) => sources.extend(source),
Err(reason) => findings.push(unreadable(path, reason)),
(sources, findings)
pub(super) fn check(
user: Uuid,
directory: &Directory,
declared: &[Source],
report: &mut TenantReport,
) {
report.coverage.sources = declared.len();
for source in declared {
let subject = Subject::Source(source.name.clone());
judge(user, &subject, directory, source.lookups.clone(), report);
#[cfg(test)]
mod tests;