sheeter-engine 0.11.0

A CLI tool for converting data files between formats. v0.1.0 supports CSV <-> JSON.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use clap::{Parser, Subcommand, ValueEnum};
use sheeter_engine::{
    convert_workbook_with_options, detect_content, detect_extension, external_sort_delimited,
    inspect, stream_delimited, stream_delimited_to_ndjson, stream_ndjson_to_delimited,
    stream_ndjson_to_ndjson, CanonicalValue, Filter, Format, SortSpec, SqlDialect, Transforms,
};
use std::fs;
use std::io::{BufWriter, Read, Write};
use std::path::Path;

#[derive(Parser)]
#[command(
    name = "sheeter",
    version,
    about = "Convert data files between formats"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum Commands {
    /// Convert a data file from one format to another
    Convert {
        /// Source format; auto-detected when omitted
        #[arg(long, ignore_case = true)]
        from: Option<FormatArg>,
        #[arg(long, ignore_case = true)]
        to: FormatArg,
        #[arg(long)]
        sheet: Option<String>,
        #[arg(long, default_value = "generic")]
        dialect: String,
        /// Filter expression (e.g. "age > 30 and name == 'Bob'")
        #[arg(long)]
        filter: Option<String>,
        /// Columns to keep, comma-separated
        #[arg(long)]
        select: Option<String>,
        /// Rename columns (e.g. "a=x,b=y")
        #[arg(long)]
        rename: Option<String>,
        /// Maximum number of rows
        #[arg(long)]
        limit: Option<usize>,
        /// Sort by column(s), e.g. "age desc,name"
        #[arg(long)]
        sort: Option<String>,
        /// Drop duplicate rows (whole row)
        #[arg(long)]
        dedup: bool,
        /// Drop duplicates by column(s), e.g. "email"
        #[arg(long, value_name = "COLS")]
        dedup_by: Option<String>,
        /// Input file, or "-" for stdin
        input: String,
        /// Output file, or "-" for stdout
        output: String,
    },
    /// Print a structural summary of a data file
    Inspect {
        /// Format; auto-detected when omitted
        #[arg(long, ignore_case = true)]
        format: Option<FormatArg>,
        /// Input file, or "-" for stdin
        input: String,
    },
    /// Print the detected format of a file or stdin
    Detect {
        /// Input file, or "-" for stdin
        input: String,
    },
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum FormatArg {
    Csv,
    Tsv,
    Json,
    Yaml,
    Xml,
    Toml,
    Xlsx,
    Sql,
    Ndjson,
}

impl From<FormatArg> for Format {
    fn from(f: FormatArg) -> Self {
        match f {
            FormatArg::Csv => Self::Csv,
            FormatArg::Tsv => Self::Tsv,
            FormatArg::Json => Self::Json,
            FormatArg::Yaml => Self::Yaml,
            FormatArg::Xml => Self::Xml,
            FormatArg::Toml => Self::Toml,
            FormatArg::Xlsx => Self::Xlsx,
            FormatArg::Sql => Self::Sql,
            FormatArg::Ndjson => Self::Ndjson,
        }
    }
}

fn sanitize(name: &str) -> String {
    let cleaned: String = name
        .chars()
        .map(|c| match c {
            '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0' => '_',
            c if c.is_control() => '_',
            c => c,
        })
        .collect();
    if cleaned.is_empty() {
        "Sheet".to_string()
    } else {
        cleaned
    }
}

fn read_input(path: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    if path == "-" {
        let mut buf = Vec::new();
        std::io::stdin().read_to_end(&mut buf)?;
        Ok(buf)
    } else {
        Ok(fs::read(path)?)
    }
}

fn write_output(
    path: &str,
    content: &[u8],
    is_binary: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    if path == "-" {
        if is_binary {
            return Err("cannot write binary output to stdout; specify a file path".into());
        }
        std::io::stdout().write_all(content)?;
        std::io::stdout().flush()?;
    } else {
        fs::write(path, content)?;
    }
    Ok(())
}

fn resolve_from(
    explicit: Option<FormatArg>,
    input_path: &str,
    input_bytes: &[u8],
) -> Result<Format, Box<dyn std::error::Error>> {
    if let Some(f) = explicit {
        return Ok(f.into());
    }
    if input_path != "-" {
        if let Some(f) = detect_extension(Path::new(input_path)) {
            return Ok(f);
        }
    }
    detect_content(input_bytes)
}

fn build_transforms(
    filter: Option<String>,
    select: Option<String>,
    rename: Option<String>,
    limit: Option<usize>,
    dedup: bool,
    dedup_by: Option<String>,
) -> Result<Transforms, Box<dyn std::error::Error>> {
    let filter = match filter {
        Some(s) => Some(Filter::parse(&s)?),
        None => None,
    };
    let select = select.map(|s| {
        s.split(',')
            .map(|x| x.trim().to_string())
            .filter(|x| !x.is_empty())
            .collect::<Vec<_>>()
    });
    let rename = rename
        .map(|s| {
            s.split(',')
                .filter_map(|pair| {
                    let mut parts = pair.split('=');
                    let from = parts.next()?.trim().to_string();
                    let to = parts.next()?.trim().to_string();
                    if from.is_empty() || to.is_empty() {
                        None
                    } else {
                        Some((from, to))
                    }
                })
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    let dedup_spec = if dedup {
        Some(Vec::new())
    } else {
        dedup_by.map(|s| {
            s.split(',')
                .map(|x| x.trim().to_string())
                .filter(|x| !x.is_empty())
                .collect::<Vec<_>>()
        })
    };
    Ok(Transforms {
        filter,
        select,
        rename,
        limit,
        dedup: dedup_spec,
    })
}

fn is_binary_format(f: Format) -> bool {
    matches!(f, Format::Xlsx)
}

fn is_text_streamable(from: Format, to: Format) -> bool {
    let delimited = |f: Format| matches!(f, Format::Csv | Format::Tsv);
    let ndjson = |f: Format| matches!(f, Format::Ndjson);
    (delimited(from) && delimited(to))
        || (ndjson(from) && delimited(to))
        || (delimited(from) && ndjson(to))
        || (ndjson(from) && ndjson(to))
}

fn stream_convert(
    from: Format,
    to: Format,
    input: &mut dyn Read,
    output: &mut dyn Write,
    transforms: &Transforms,
    sort: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let from_delim = if matches!(from, Format::Tsv) {
        b'\t'
    } else {
        b','
    };
    let to_delim = if matches!(to, Format::Tsv) {
        b'\t'
    } else {
        b','
    };

    match (from, to) {
        (Format::Csv | Format::Tsv, Format::Csv | Format::Tsv) => {
            if let Some(spec) = sort {
                let sort_spec = SortSpec::parse(spec)?;
                external_sort_delimited(
                    input, from_delim, output, to_delim, transforms, &sort_spec, 50_000,
                )?;
            } else {
                stream_delimited(input, from_delim, output, to_delim, transforms)?;
            }
        }
        (Format::Ndjson, Format::Csv | Format::Tsv) => {
            if sort.is_some() {
                return Err("--sort is not yet supported with NDJSON input".into());
            }
            stream_ndjson_to_delimited(input, output, to_delim, transforms)?;
        }
        (Format::Csv | Format::Tsv, Format::Ndjson) => {
            if sort.is_some() {
                return Err("--sort is not yet supported with NDJSON output".into());
            }
            stream_delimited_to_ndjson(input, from_delim, output, transforms)?;
        }
        (Format::Ndjson, Format::Ndjson) => {
            if sort.is_some() {
                return Err("--sort is not yet supported with NDJSON".into());
            }
            stream_ndjson_to_ndjson(input, output, transforms)?;
        }
        _ => return Err("stream_convert called with non-streamable pair".into()),
    }
    Ok(())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();
    match cli.command {
        Commands::Convert {
            from,
            to,
            sheet,
            dialect,
            filter,
            select,
            rename,
            limit,
            sort,
            dedup,
            dedup_by,
            input,
            output,
        } => {
            let to_fmt: Format = to.into();
            let transforms = build_transforms(filter, select, rename, limit, dedup, dedup_by)?;

            if is_binary_format(to_fmt) && !transforms.is_empty() {
                return Err(format!(
                    "transforms cannot be applied when the output format is {to_fmt:?} because it cannot be parsed back. Convert to a text format first."
                )
                .into());
            }

            let input_bytes = read_input(&input)?;
            let from_fmt = resolve_from(from, &input, &input_bytes)?;

            if is_text_streamable(from_fmt, to_fmt) {
                let mut reader = std::io::Cursor::new(&input_bytes);
                if output == "-" {
                    let mut out = std::io::stdout();
                    stream_convert(
                        from_fmt,
                        to_fmt,
                        &mut reader,
                        &mut out,
                        &transforms,
                        sort.as_deref(),
                    )?;
                } else {
                    let file = fs::File::create(&output)?;
                    let mut out = BufWriter::new(file);
                    stream_convert(
                        from_fmt,
                        to_fmt,
                        &mut reader,
                        &mut out,
                        &transforms,
                        sort.as_deref(),
                    )?;
                }
                return Ok(());
            }

            let sql_dialect: SqlDialect = dialect
                .parse()
                .map_err(|e: String| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
            let table_name = if output == "-" {
                None
            } else {
                Path::new(&output).file_stem().and_then(|s| s.to_str())
            };
            let mut results = convert_workbook_with_options(
                from_fmt,
                to_fmt,
                &input_bytes,
                sql_dialect,
                table_name,
            )?;

            if !transforms.is_empty() {
                for (_, content) in results.iter_mut() {
                    let text = std::str::from_utf8(content)?;
                    let hub = match to_fmt {
                        Format::Json => CanonicalValue::from_json(text)?,
                        Format::Yaml => CanonicalValue::from_yaml(text)?,
                        Format::Xml => CanonicalValue::from_xml(text)?,
                        Format::Toml => CanonicalValue::from_toml(text)?,
                        Format::Csv => CanonicalValue::from_csv(text)?,
                        Format::Tsv => CanonicalValue::from_tsv(text)?,
                        Format::Ndjson => CanonicalValue::from_ndjson(text)?,
                        Format::Xlsx | Format::Sql => continue,
                    };
                    let filtered = transforms.apply_to_array(&hub);
                    let reserialized = match to_fmt {
                        Format::Json => filtered.to_json()?,
                        Format::Yaml => filtered.to_yaml()?,
                        Format::Xml => filtered.to_xml()?,
                        Format::Toml => filtered.to_toml()?,
                        Format::Csv => filtered.to_csv()?,
                        Format::Tsv => filtered.to_tsv()?,
                        Format::Ndjson => filtered.to_ndjson()?,
                        Format::Xlsx | Format::Sql => continue,
                    };
                    *content = reserialized.into_bytes();
                }
            }

            if let Some(want) = sheet {
                results.retain(|(name, _)| name == &want);
                if results.is_empty() {
                    return Err(format!("sheet {want:?} not found").into());
                }
            }

            if results.len() == 1 {
                write_output(&output, &results[0].1, is_binary_format(to_fmt))?;
                return Ok(());
            }

            let out_path = Path::new(&output);
            let stem = out_path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("output");
            let ext = out_path.extension().and_then(|s| s.to_str()).unwrap_or("");
            let parent = out_path.parent().unwrap_or_else(|| Path::new("."));
            let mut used: std::collections::HashSet<String> = std::collections::HashSet::new();
            for (raw_name, content) in &results {
                let mut base = sanitize(raw_name);
                let mut n = 2;
                while !used.insert(base.clone()) {
                    base = format!("{}_{}", sanitize(raw_name), n);
                    n += 1;
                }
                let filename = if ext.is_empty() {
                    format!("{}.{}", stem, base)
                } else {
                    format!("{}.{}.{}", stem, base, ext)
                };
                fs::write(parent.join(filename), content)?;
            }
            Ok(())
        }
        Commands::Inspect { format, input } => {
            let bytes = read_input(&input)?;
            let fmt = resolve_from(format, &input, &bytes)?;
            let report = inspect(&bytes, fmt)?;
            print!("{report}");
            Ok(())
        }
        Commands::Detect { input } => {
            let bytes = read_input(&input)?;
            let fmt = resolve_from(None, &input, &bytes)?;
            println!("{:?}", fmt);
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::sanitize;

    #[test]
    fn sanitize_replaces_forbidden_chars() {
        assert_eq!(sanitize("A/B"), "A_B");
        assert_eq!(sanitize("A:B*C?"), "A_B_C_");
        assert_eq!(sanitize("a\\b"), "a_b");
    }

    #[test]
    fn sanitize_preserves_valid_names() {
        assert_eq!(sanitize("Sheet1"), "Sheet1");
        assert_eq!(sanitize("Vendas 2024"), "Vendas 2024");
        assert_eq!(sanitize("A.B"), "A.B");
    }

    #[test]
    fn sanitize_falls_back_on_empty() {
        assert_eq!(sanitize(""), "Sheet");
    }
}