use std::path::PathBuf;
use anyhow::{Context, Result};
use serde_json::{json, Map, Value};
use crate::meta::{self, ColumnFacts};
#[derive(Clone, Debug)]
pub struct FileEntry {
pub path: String,
pub label: String,
pub rows: i64,
pub size_bytes: u64,
pub row_groups: usize,
pub columns: Vec<ColumnFacts>,
}
#[derive(Clone, Debug)]
pub struct Finding {
pub rule: &'static str,
pub severity: &'static str,
pub file: Option<String>,
pub message: String,
}
impl Finding {
pub fn to_json(&self) -> Value {
let mut object = Map::new();
object.insert("rule".into(), Value::String(self.rule.into()));
object.insert("severity".into(), Value::String(self.severity.into()));
if let Some(file) = &self.file {
object.insert("file".into(), Value::String(file.clone()));
}
object.insert("message".into(), Value::String(self.message.clone()));
Value::Object(object)
}
}
#[derive(Clone, Debug)]
pub struct Comparison {
pub files: Vec<FileEntry>,
pub findings: Vec<Finding>,
}
impl Comparison {
pub fn to_json(&self) -> Value {
let files: Vec<Value> = self
.files
.iter()
.map(|file| {
json!({
"file": file.path,
"label": file.label,
"rows": file.rows,
"size_bytes": file.size_bytes,
"row_groups": file.row_groups,
"columns": file.columns.len(),
})
})
.collect();
json!({
"files": files,
"findings": self
.findings
.iter()
.map(|finding| finding.to_json())
.collect::<Vec<Value>>(),
})
}
}
pub struct Found {
pub path: PathBuf,
pub label: String,
}
pub fn collect(paths: &[PathBuf]) -> Result<Vec<Found>> {
let mut files = Vec::new();
for path in paths {
if path.is_dir() {
let mut inside = Vec::new();
walk(path, 0, &mut inside)?;
inside.sort();
for found in inside {
let label = found
.strip_prefix(path)
.unwrap_or(&found)
.to_string_lossy()
.to_string();
files.push(Found { path: found, label });
}
} else {
let label = path
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| path.display().to_string());
files.push(Found {
path: path.clone(),
label,
});
}
}
Ok(files)
}
fn walk(directory: &std::path::Path, depth: usize, files: &mut Vec<PathBuf>) -> Result<()> {
if depth > 4 {
return Ok(());
}
for entry in
std::fs::read_dir(directory).with_context(|| format!("read {}", directory.display()))?
{
let path = entry?.path();
if path.is_dir() {
walk(&path, depth + 1, files)?;
} else if path
.extension()
.and_then(|extension| extension.to_str())
.map(|extension| extension.eq_ignore_ascii_case("parquet"))
.unwrap_or(false)
{
files.push(path);
}
}
Ok(())
}
pub fn compare(paths: &[PathBuf]) -> Result<Comparison> {
let files = collect(paths)?;
if files.is_empty() {
anyhow::bail!("there is nothing to compare");
}
let mut entries = Vec::new();
for found in &files {
let facts = meta::file_facts(&found.path)?;
let columns = meta::column_facts(&found.path, false)?;
entries.push(FileEntry {
label: found.label.clone(),
path: facts.path,
rows: facts.rows,
size_bytes: facts.size_bytes,
row_groups: facts.row_groups,
columns,
});
}
let findings = differences(&entries);
Ok(Comparison {
files: entries,
findings,
})
}
fn differences(files: &[FileEntry]) -> Vec<Finding> {
let mut findings = Vec::new();
if files.len() < 2 {
return findings;
}
let mut shapes: Vec<(Vec<(String, String)>, usize)> = Vec::new();
for file in files {
let shape: Vec<(String, String)> = file
.columns
.iter()
.map(|column| (column.name.clone(), column.data_type.clone()))
.collect();
match shapes.iter_mut().find(|(other, _)| *other == shape) {
Some((_, count)) => *count += 1,
None => shapes.push((shape, 1)),
}
}
shapes.sort_by(|left, right| {
right
.1
.cmp(&left.1)
.then_with(|| right.0.len().cmp(&left.0.len()))
});
let reference_types = shapes[0].0.clone();
for file in files {
let types: Vec<(String, String)> = file
.columns
.iter()
.map(|column| (column.name.clone(), column.data_type.clone()))
.collect();
if types == reference_types {
continue;
}
for (name, data_type) in &types {
match reference_types.iter().find(|(other, _)| other == name) {
None => findings.push(Finding {
rule: "column-extra",
severity: "error",
file: Some(file.label.clone()),
message: format!("多了一个列「{name}」,别的文件没有"),
}),
Some((_, other_type)) if other_type != data_type => findings.push(Finding {
rule: "column-type-changed",
severity: "error",
file: Some(file.label.clone()),
message: format!("列「{name}」在这里是 {data_type},别的文件是 {other_type}"),
}),
Some(_) => {}
}
}
for (name, _) in &reference_types {
if !types.iter().any(|(other, _)| other == name) {
findings.push(Finding {
rule: "column-missing",
severity: "error",
file: Some(file.label.clone()),
message: format!("少了列「{name}」,别的文件有"),
});
}
}
}
let mut names: Vec<String> = Vec::new();
for file in files {
for column in &file.columns {
if !names.contains(&column.name) {
names.push(column.name.clone());
}
}
}
for name in names {
let sizes: Vec<i64> = files
.iter()
.map(|file| {
file.columns
.iter()
.find(|column| column.name == name)
.map(|column| column.compressed_size)
.unwrap_or(0)
})
.collect();
let largest = sizes.iter().copied().max().unwrap_or(0);
let smallest = sizes.iter().copied().min().unwrap_or(0);
if smallest > 0 && largest > smallest * 2 {
let file = files
.iter()
.zip(sizes.iter())
.max_by_key(|(_, size)| **size)
.map(|(file, _)| file.label.clone());
findings.push(Finding {
rule: "size-jump",
severity: "warning",
file,
message: format!(
"列「{name}」的字节从 {smallest} 涨到 {largest}({:.1} 倍)",
largest as f64 / smallest as f64
),
});
}
}
let sizes: Vec<u64> = files.iter().map(|file| file.size_bytes).collect();
let largest = sizes.iter().copied().max().unwrap_or(0);
let smallest = sizes.iter().copied().min().unwrap_or(0);
if smallest > 0 && largest > smallest * 2 {
findings.push(Finding {
rule: "file-size-jump",
severity: "warning",
file: None,
message: format!(
"文件的大小从 {smallest} 涨到 {largest}({:.1} 倍)",
largest as f64 / smallest as f64
),
});
}
findings
}
pub fn column_bytes(files: &[FileEntry]) -> Vec<(String, Vec<i64>)> {
let mut names: Vec<String> = Vec::new();
for file in files {
for column in &file.columns {
if !names.contains(&column.name) {
names.push(column.name.clone());
}
}
}
names
.into_iter()
.map(|name| {
let sizes = files
.iter()
.map(|file| {
file.columns
.iter()
.find(|column| column.name == name)
.map(|column| column.compressed_size)
.unwrap_or(0)
})
.collect();
(name, sizes)
})
.collect()
}