use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};
type Lines = Vec<(String, Vec<(usize, String)>)>;
static READ: Mutex<Lines> = Mutex::new(Vec::new());
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)
}
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))
}
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),
_ => {}
}
}
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
}