use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::escape::unescape;
use crate::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpecOptions {
pub header: bool,
pub comment: bool,
pub min_cols: usize,
}
impl Default for SpecOptions {
fn default() -> Self {
SpecOptions {
header: true,
comment: true,
min_cols: 1,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Column {
Position(usize),
Name(String),
}
impl From<usize> for Column {
fn from(position: usize) -> Self {
Column::Position(position)
}
}
impl From<&str> for Column {
fn from(name: &str) -> Self {
Column::Name(name.to_string())
}
}
impl From<String> for Column {
fn from(name: String) -> Self {
Column::Name(name)
}
}
#[derive(Debug, Clone)]
pub struct Row {
pub file: String,
pub line: usize,
pub index: usize,
pub cols: Vec<String>,
pub header: Arc<Vec<String>>,
}
impl Row {
pub fn col(&self, i: usize) -> &str {
self.cols.get(i).map(String::as_str).unwrap_or("")
}
pub fn unesc(&self, i: usize) -> String {
unescape(self.col(i))
}
pub fn index_of(&self, name: &str) -> Option<usize> {
self.header.iter().position(|column| column == name)
}
pub fn named(&self, name: &str) -> &str {
self.index_of(name).map_or("", |i| self.col(i))
}
pub fn unesc_named(&self, name: &str) -> String {
unescape(self.named(name))
}
pub fn resolve(&self, selector: &Column) -> Result<usize> {
match selector {
Column::Position(i) => Ok(*i),
Column::Name(name) => self.index_of(name).ok_or_else(|| {
Error(format!(
"{}: no column named '{}' (header: {})",
self.file,
name,
self.header.join(", ")
))
}),
}
}
pub fn location(&self) -> String {
format!("{}:{}", self.file, self.line)
}
}
#[derive(Debug, Clone)]
pub struct SpecFile {
pub file: String,
pub path: PathBuf,
pub header: Arc<Vec<String>>,
pub rows: Vec<Row>,
}
pub fn parse_spec(file: &str, text: &str, options: &SpecOptions) -> Result<SpecFile> {
let text = text.strip_prefix('\u{FEFF}').unwrap_or(text);
let name = base_name(file);
let mut header: Arc<Vec<String>> = Arc::new(Vec::new());
let mut rows = Vec::new();
for (i, raw) in text.split('\n').enumerate() {
let line = raw.strip_suffix('\r').unwrap_or(raw);
let line_no = i + 1;
if options.header && i == 0 {
header = Arc::new(line.split('\t').map(str::to_string).collect());
continue;
}
if line.is_empty() {
continue;
}
if options.comment && line.starts_with('#') && !line.contains('\t') {
continue;
}
let cols: Vec<String> = line.split('\t').map(str::to_string).collect();
if cols.len() < options.min_cols {
return Err(Error(format!(
"{name}:{line_no}: expected at least {} tab-separated column(s), found {}",
options.min_cols,
cols.len()
)));
}
rows.push(Row {
file: name.clone(),
line: line_no,
index: rows.len(),
cols,
header: Arc::clone(&header),
});
}
Ok(SpecFile {
file: name,
path: PathBuf::new(),
header,
rows,
})
}
pub fn load_spec(path: impl AsRef<Path>, options: &SpecOptions) -> Result<SpecFile> {
let path = path.as_ref();
let text = fs::read_to_string(path)
.map_err(|error| Error(format!("spec file not found: {}: {error}", path.display())))?;
let mut spec = parse_spec(&path.to_string_lossy(), &text, options)?;
spec.path = path.to_path_buf();
Ok(spec)
}
pub fn load_spec_dir(dir: impl AsRef<Path>, options: &SpecOptions) -> Result<Vec<SpecFile>> {
let dir = dir.as_ref();
if !dir.is_dir() {
return Err(Error(format!(
"spec directory not found: {}",
dir.display()
)));
}
let entries = fs::read_dir(dir).map_err(|error| {
Error(format!(
"spec directory not found: {}: {error}",
dir.display()
))
})?;
let mut names = Vec::new();
for entry in entries {
let entry = entry.map_err(|error| Error(format!("{}: {error}", dir.display())))?;
let name = entry.file_name().to_string_lossy().into_owned();
if !name.ends_with(".tsv") {
continue;
}
let metadata = fs::metadata(dir.join(&name)).map_err(|error| {
Error(format!(
"spec fixture cannot be read: {}: {error}",
dir.join(&name).display()
))
})?;
if metadata.is_file() {
names.push(name);
}
}
names.sort();
if names.is_empty() {
return Err(Error(format!(
"no .tsv fixtures in spec directory: {}",
dir.display()
)));
}
names
.iter()
.map(|name| load_spec(dir.join(name), options))
.collect()
}
pub fn find_spec_dir(from: Option<&Path>) -> Result<PathBuf> {
let start = match from {
Some(path) => path.to_path_buf(),
None => std::env::current_dir()
.map_err(|error| Error(format!("cannot read the working directory: {error}")))?,
};
let start = start.canonicalize().unwrap_or(start);
let mut dir = start.clone();
loop {
let candidate = dir.join("test").join("spec");
if candidate.is_dir() {
return Ok(candidate);
}
match dir.parent() {
Some(parent) => dir = parent.to_path_buf(),
None => break, }
}
Err(Error(format!(
"no test/spec directory found at or above: {}",
start.display()
)))
}
fn base_name(file: &str) -> String {
Path::new(file)
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| file.to_string())
}