elinvar 0.1.1

Find the holes in a design before you build it: a relational model finder, its command line, and an MCP server
Documentation
//! A migrations directory read as one schema, and the places in it
//! (SQL.md section 1.1).

use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};

/// For each directory read: its path, which names its joined text with or
/// without `.sql`, and each file's path with the line of the joined text
/// where the file's own first line is. The command line reads files and
/// prints results in one process, so the map lives as long as it does.
type Lines = Vec<(String, Vec<(usize, String)>)>;
static READ: Mutex<Lines> = Mutex::new(Vec::new());

/// The `.sql` files of `dir`, any case of the extension, sorted by name in
/// byte order and joined, each after a line `-- migration: NAME` and before
/// an empty line. An error is the message for `cli.input`.
pub fn read(dir: &Path) -> Result<String, String> {
    let disp = dir.to_string_lossy().into_owned();
    let entries =
        std::fs::read_dir(dir).map_err(|e| format!("cannot read directory `{disp}`: {e}"))?;
    let mut files: Vec<(String, PathBuf)> = Vec::new();
    for ent in entries {
        let ent = ent.map_err(|e| format!("cannot read entry in `{disp}`: {e}"))?;
        let p = ent.path();
        if p.is_file()
            && p.extension()
                .and_then(|s| s.to_str())
                .is_some_and(|ext| ext.eq_ignore_ascii_case("sql"))
        {
            files.push((ent.file_name().to_string_lossy().into_owned(), p));
        }
    }
    files.sort_by(|a, b| a.0.cmp(&b.0));
    if files.is_empty() {
        return Err(format!("directory `{disp}` contains no `.sql` files"));
    }
    let mut out = String::new();
    let mut starts = Vec::new();
    for (fname, fpath) in files {
        let body = std::fs::read_to_string(&fpath)
            .map_err(|e| format!("cannot read `{}`: {e}", fpath.display()))?;
        out.push_str(&format!("-- migration: {fname}\n"));
        starts.push((out.matches('\n').count() + 1, fpath.display().to_string()));
        out.push_str(&body);
        if !body.ends_with('\n') {
            out.push('\n');
        }
        out.push('\n');
    }
    READ.lock()
        .unwrap_or_else(PoisonError::into_inner)
        .push((disp.trim_end_matches('/').to_string(), starts));
    Ok(out)
}

/// The migration file and its own line for a line of a directory's joined
/// text, named as the directory or the directory with `.sql`.
fn place(joined: &str, line: usize) -> Option<(String, usize)> {
    let joined = joined.trim_end_matches('/');
    let read = READ.lock().unwrap_or_else(PoisonError::into_inner);
    let (_, starts) = read
        .iter()
        .find(|(dir, _)| joined == dir || joined.strip_suffix(".sql") == Some(dir))?;
    let (start, file) = starts.iter().rev().find(|(start, _)| *start <= line)?;
    Some((file.clone(), line - start + 1))
}

/// Every `{"file", "line"}` place in `v` that is in a directory read, and
/// every place in its strings, as `remap_text` maps them: a generated
/// model's comments and the reasons a rule is not read.
pub fn remap_json(v: &mut serde_json::Value) {
    match v {
        serde_json::Value::Object(map) => {
            let found = match (map.get("file"), map.get("line")) {
                (Some(serde_json::Value::String(f)), Some(serde_json::Value::Number(n))) => {
                    n.as_u64().and_then(|l| place(f, usize::try_from(l).ok()?))
                }
                _ => None,
            };
            if let Some((file, line)) = found {
                map.insert("file".into(), file.into());
                map.insert("line".into(), line.into());
            }
            map.values_mut().for_each(remap_json);
        }
        serde_json::Value::Array(items) => items.iter_mut().for_each(remap_json),
        serde_json::Value::String(s) => *s = remap_text(s),
        _ => {}
    }
}

/// Every `DIR.sql:LINE:` and `DIR:LINE:` in `text` for a directory read.
pub fn remap_text(text: &str) -> String {
    let names: Vec<String> = READ
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .iter()
        .flat_map(|(dir, _)| [format!("{dir}.sql:"), format!("{dir}:")])
        .collect();
    let mut out = text.to_string();
    for name in names {
        let mut rest = out.as_str();
        let mut next = String::new();
        while let Some(at) = rest.find(&name) {
            next.push_str(&rest[..at]);
            let after = &rest[at + name.len()..];
            let digits = after.chars().take_while(char::is_ascii_digit).count();
            let mapped = after[..digits]
                .parse::<usize>()
                .ok()
                .filter(|_| after[digits..].starts_with(':'))
                .and_then(|l| place(&name[..name.len() - 1], l));
            match mapped {
                Some((file, line)) => {
                    next.push_str(&format!("{file}:{line}"));
                    rest = &after[digits..];
                }
                None => {
                    next.push_str(&name);
                    rest = after;
                }
            }
        }
        next.push_str(rest);
        out = next;
    }
    out
}