1use std::path::PathBuf;
8
9use anyhow::{Context, Result};
10use serde_json::{json, Map, Value};
11
12use crate::meta::{self, ColumnFacts};
13
14#[derive(Clone, Debug)]
16pub struct FileEntry {
17 pub path: String,
19 pub label: String,
21 pub rows: i64,
22 pub size_bytes: u64,
23 pub row_groups: usize,
24 pub columns: Vec<ColumnFacts>,
25}
26
27#[derive(Clone, Debug)]
29pub struct Finding {
30 pub rule: &'static str,
31 pub severity: &'static str,
32 pub file: Option<String>,
34 pub message: String,
35}
36
37impl Finding {
38 pub fn to_json(&self) -> Value {
39 let mut object = Map::new();
40 object.insert("rule".into(), Value::String(self.rule.into()));
41 object.insert("severity".into(), Value::String(self.severity.into()));
42 if let Some(file) = &self.file {
43 object.insert("file".into(), Value::String(file.clone()));
44 }
45 object.insert("message".into(), Value::String(self.message.clone()));
46 Value::Object(object)
47 }
48}
49
50#[derive(Clone, Debug)]
52pub struct Comparison {
53 pub files: Vec<FileEntry>,
54 pub findings: Vec<Finding>,
55}
56
57impl Comparison {
58 pub fn to_json(&self) -> Value {
59 let files: Vec<Value> = self
60 .files
61 .iter()
62 .map(|file| {
63 json!({
64 "file": file.path,
65 "label": file.label,
66 "rows": file.rows,
67 "size_bytes": file.size_bytes,
68 "row_groups": file.row_groups,
69 "columns": file.columns.len(),
70 })
71 })
72 .collect();
73 json!({
74 "files": files,
75 "findings": self
76 .findings
77 .iter()
78 .map(|finding| finding.to_json())
79 .collect::<Vec<Value>>(),
80 })
81 }
82}
83
84pub struct Found {
86 pub path: PathBuf,
87 pub label: String,
90}
91
92pub fn collect(paths: &[PathBuf]) -> Result<Vec<Found>> {
98 let mut files = Vec::new();
99 for path in paths {
100 if path.is_dir() {
101 let mut inside = Vec::new();
102 walk(path, 0, &mut inside)?;
103 inside.sort();
104 for found in inside {
105 let label = found
106 .strip_prefix(path)
107 .unwrap_or(&found)
108 .to_string_lossy()
109 .to_string();
110 files.push(Found { path: found, label });
111 }
112 } else {
113 let label = path
114 .file_name()
115 .map(|name| name.to_string_lossy().to_string())
116 .unwrap_or_else(|| path.display().to_string());
117 files.push(Found {
118 path: path.clone(),
119 label,
120 });
121 }
122 }
123 Ok(files)
124}
125
126fn walk(directory: &std::path::Path, depth: usize, files: &mut Vec<PathBuf>) -> Result<()> {
128 if depth > 4 {
129 return Ok(());
130 }
131 for entry in
132 std::fs::read_dir(directory).with_context(|| format!("read {}", directory.display()))?
133 {
134 let path = entry?.path();
135 if path.is_dir() {
136 walk(&path, depth + 1, files)?;
137 } else if path
138 .extension()
139 .and_then(|extension| extension.to_str())
140 .map(|extension| extension.eq_ignore_ascii_case("parquet"))
141 .unwrap_or(false)
142 {
143 files.push(path);
144 }
145 }
146 Ok(())
147}
148
149pub fn compare(paths: &[PathBuf]) -> Result<Comparison> {
151 let files = collect(paths)?;
152 if files.is_empty() {
153 anyhow::bail!("there is nothing to compare");
154 }
155
156 let mut entries = Vec::new();
157 for found in &files {
158 let facts = meta::file_facts(&found.path)?;
159 let columns = meta::column_facts(&found.path, false)?;
160 entries.push(FileEntry {
161 label: found.label.clone(),
162 path: facts.path,
163 rows: facts.rows,
164 size_bytes: facts.size_bytes,
165 row_groups: facts.row_groups,
166 columns,
167 });
168 }
169
170 let findings = differences(&entries);
171 Ok(Comparison {
172 files: entries,
173 findings,
174 })
175}
176
177fn differences(files: &[FileEntry]) -> Vec<Finding> {
179 let mut findings = Vec::new();
180 if files.len() < 2 {
181 return findings;
182 }
183
184 let mut shapes: Vec<(Vec<(String, String)>, usize)> = Vec::new();
187 for file in files {
188 let shape: Vec<(String, String)> = file
189 .columns
190 .iter()
191 .map(|column| (column.name.clone(), column.data_type.clone()))
192 .collect();
193 match shapes.iter_mut().find(|(other, _)| *other == shape) {
194 Some((_, count)) => *count += 1,
195 None => shapes.push((shape, 1)),
196 }
197 }
198 shapes.sort_by(|left, right| {
202 right
203 .1
204 .cmp(&left.1)
205 .then_with(|| right.0.len().cmp(&left.0.len()))
206 });
207 let reference_types = shapes[0].0.clone();
208
209 for file in files {
210 let types: Vec<(String, String)> = file
211 .columns
212 .iter()
213 .map(|column| (column.name.clone(), column.data_type.clone()))
214 .collect();
215
216 if types == reference_types {
217 continue;
218 }
219 for (name, data_type) in &types {
220 match reference_types.iter().find(|(other, _)| other == name) {
221 None => findings.push(Finding {
222 rule: "column-extra",
223 severity: "error",
224 file: Some(file.label.clone()),
225 message: format!("多了一个列「{name}」,别的文件没有"),
226 }),
227 Some((_, other_type)) if other_type != data_type => findings.push(Finding {
228 rule: "column-type-changed",
229 severity: "error",
230 file: Some(file.label.clone()),
231 message: format!("列「{name}」在这里是 {data_type},别的文件是 {other_type}"),
232 }),
233 Some(_) => {}
234 }
235 }
236 for (name, _) in &reference_types {
237 if !types.iter().any(|(other, _)| other == name) {
238 findings.push(Finding {
239 rule: "column-missing",
240 severity: "error",
241 file: Some(file.label.clone()),
242 message: format!("少了列「{name}」,别的文件有"),
243 });
244 }
245 }
246 }
247
248 let mut names: Vec<String> = Vec::new();
250 for file in files {
251 for column in &file.columns {
252 if !names.contains(&column.name) {
253 names.push(column.name.clone());
254 }
255 }
256 }
257 for name in names {
258 let sizes: Vec<i64> = files
259 .iter()
260 .map(|file| {
261 file.columns
262 .iter()
263 .find(|column| column.name == name)
264 .map(|column| column.compressed_size)
265 .unwrap_or(0)
266 })
267 .collect();
268 let largest = sizes.iter().copied().max().unwrap_or(0);
269 let smallest = sizes.iter().copied().min().unwrap_or(0);
270 if smallest > 0 && largest > smallest * 2 {
271 let file = files
272 .iter()
273 .zip(sizes.iter())
274 .max_by_key(|(_, size)| **size)
275 .map(|(file, _)| file.label.clone());
276 findings.push(Finding {
277 rule: "size-jump",
278 severity: "warning",
279 file,
280 message: format!(
281 "列「{name}」的字节从 {smallest} 涨到 {largest}({:.1} 倍)",
282 largest as f64 / smallest as f64
283 ),
284 });
285 }
286 }
287
288 let sizes: Vec<u64> = files.iter().map(|file| file.size_bytes).collect();
290 let largest = sizes.iter().copied().max().unwrap_or(0);
291 let smallest = sizes.iter().copied().min().unwrap_or(0);
292 if smallest > 0 && largest > smallest * 2 {
293 findings.push(Finding {
294 rule: "file-size-jump",
295 severity: "warning",
296 file: None,
297 message: format!(
298 "文件的大小从 {smallest} 涨到 {largest}({:.1} 倍)",
299 largest as f64 / smallest as f64
300 ),
301 });
302 }
303
304 findings
305}
306
307pub fn column_bytes(files: &[FileEntry]) -> Vec<(String, Vec<i64>)> {
309 let mut names: Vec<String> = Vec::new();
310 for file in files {
311 for column in &file.columns {
312 if !names.contains(&column.name) {
313 names.push(column.name.clone());
314 }
315 }
316 }
317 names
318 .into_iter()
319 .map(|name| {
320 let sizes = files
321 .iter()
322 .map(|file| {
323 file.columns
324 .iter()
325 .find(|column| column.name == name)
326 .map(|column| column.compressed_size)
327 .unwrap_or(0)
328 })
329 .collect();
330 (name, sizes)
331 })
332 .collect()
333}