csvmd 0.3.0

Convert from CSV to a Markdown table
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use std::io::Write;
use std::process::Command;
use tempfile::NamedTempFile;

#[test]
fn test_cli_with_file_input() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Age,City").unwrap();
    writeln!(temp_file, "John,25,NYC").unwrap();
    writeln!(temp_file, "Jane,30,LA").unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    let result = String::from_utf8(output.stdout).unwrap();
    insta::assert_snapshot!(result);
}

#[test]
fn test_cli_with_stdin() {
    let csv_data = "Product,Price\nLaptop,$999\nMouse,$25";

    let output = Command::new("cargo")
        .args(["run"])
        .arg("--")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    output
        .stdin
        .as_ref()
        .unwrap()
        .write_all(csv_data.as_bytes())
        .unwrap();
    let result = output.wait_with_output().unwrap();

    let stdout = String::from_utf8(result.stdout).unwrap();
    insta::assert_snapshot!(stdout);
}

#[test]
fn test_cli_with_complex_csv() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Description,Tags").unwrap();
    writeln!(
        temp_file,
        "John,\"A person with\nmultiple lines\",\"tag1,tag2\""
    )
    .unwrap();
    writeln!(temp_file, "Jane,\"Has | pipes\",simple").unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    let result = String::from_utf8(output.stdout).unwrap();
    insta::assert_snapshot!(result);
}

#[test]
fn test_cli_with_empty_file() {
    let temp_file = NamedTempFile::new().unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    let result = String::from_utf8(output.stdout).unwrap();
    insta::assert_snapshot!(result);
}

#[test]
fn test_cli_with_single_column() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Item").unwrap();
    writeln!(temp_file, "Apple").unwrap();
    writeln!(temp_file, "Banana").unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    let result = String::from_utf8(output.stdout).unwrap();
    insta::assert_snapshot!(result);
}

#[test]
fn test_cli_help_flag() {
    let output = Command::new("cargo")
        .args(["run", "--", "--help"])
        .output()
        .expect("Failed to execute command");

    let result = String::from_utf8(output.stdout).unwrap();
    // Normalize output for cross-platform compatibility (remove .exe extension on Windows)
    let normalized_result = result.replace("csvmd.exe", "csvmd");
    insta::assert_snapshot!(normalized_result);
}

#[test]
fn test_cli_nonexistent_file() {
    let output = Command::new("cargo")
        .args(["run", "--", "/nonexistent/file.csv"])
        .output()
        .expect("Failed to execute command");

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("No such file") || stderr.contains("cannot find"));
}

#[test]
fn test_cli_with_unicode() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Symbol,Name,Code").unwrap();
    writeln!(temp_file, "★,Star,U+2605").unwrap();
    writeln!(temp_file, "â™ ,Spade,U+2660").unwrap();
    writeln!(temp_file, "🚀,Rocket,U+1F680").unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    let result = String::from_utf8(output.stdout).unwrap();
    insta::assert_snapshot!(result);
}

#[test]
fn test_cli_with_mixed_quote_styles() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Quote").unwrap();
    writeln!(temp_file, "Shakespeare,\"To be or not to be\"").unwrap();
    writeln!(temp_file, "Einstein,\"E=mc²\"").unwrap();
    writeln!(temp_file, "Anonymous,No quotes here").unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    let result = String::from_utf8(output.stdout).unwrap();
    insta::assert_snapshot!(result);
}

#[test]
fn test_cli_stdin_with_piped_input_is_fast() {
    // Test that piped input doesn't have a 2-second delay
    let csv_data = "Product,Price\nLaptop,$999\nMouse,$25";

    let start = std::time::Instant::now();

    let mut child = Command::new("cargo")
        .args(["run"])
        .arg("--")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(csv_data.as_bytes())
        .unwrap();

    let result = child.wait_with_output().unwrap();
    let elapsed = start.elapsed();

    let stdout = String::from_utf8(result.stdout).unwrap();
    let expected = "| Product | Price |\n| --- | --- |\n| Laptop | $999 |\n| Mouse | $25 |\n";
    assert_eq!(stdout, expected);

    // Should complete quickly since input is piped (not interactive)
    assert!(
        elapsed.as_secs() < 2,
        "Piped input should not have 2-second delay, took {:?}",
        elapsed
    );
}

#[test]
fn test_cli_with_center_alignment() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Age").unwrap();
    writeln!(temp_file, "John,25").unwrap();
    writeln!(temp_file, "Jane,30").unwrap();

    let output = Command::new("cargo")
        .args([
            "run",
            "--",
            "--align",
            "center",
            temp_file.path().to_str().unwrap(),
        ])
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());
    let result = String::from_utf8(output.stdout).unwrap();
    let expected = "| Name | Age |\n| :---: | :---: |\n| John | 25 |\n| Jane | 30 |\n";
    assert_eq!(result, expected);
}

#[test]
fn test_cli_with_right_alignment() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Age").unwrap();
    writeln!(temp_file, "John,25").unwrap();

    let output = Command::new("cargo")
        .args([
            "run",
            "--",
            "--align",
            "right",
            temp_file.path().to_str().unwrap(),
        ])
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());
    let result = String::from_utf8(output.stdout).unwrap();
    let expected = "| Name | Age |\n| ---: | ---: |\n| John | 25 |\n";
    assert_eq!(result, expected);
}

#[test]
fn test_cli_with_left_alignment() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Age").unwrap();
    writeln!(temp_file, "John,25").unwrap();

    let output = Command::new("cargo")
        .args([
            "run",
            "--",
            "--align",
            "left",
            temp_file.path().to_str().unwrap(),
        ])
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());
    let result = String::from_utf8(output.stdout).unwrap();
    let expected = "| Name | Age |\n| --- | --- |\n| John | 25 |\n";
    assert_eq!(result, expected);
}

#[test]
fn test_cli_with_invalid_alignment() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Age").unwrap();
    writeln!(temp_file, "John,25").unwrap();

    let output = Command::new("cargo")
        .args([
            "run",
            "--",
            "--align",
            "invalid",
            temp_file.path().to_str().unwrap(),
        ])
        .output()
        .expect("Failed to execute command");

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("invalid value 'invalid' for '--align <ALIGN>'"));
}

#[test]
fn test_cli_with_streaming_and_alignment() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Age").unwrap();
    writeln!(temp_file, "John,25").unwrap();
    writeln!(temp_file, "Jane,30").unwrap();

    let output = Command::new("cargo")
        .args([
            "run",
            "--",
            "--stream",
            "--align",
            "center",
            temp_file.path().to_str().unwrap(),
        ])
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());
    let result = String::from_utf8(output.stdout).unwrap();
    let expected = "| Name | Age |\n| :---: | :---: |\n| John | 25 |\n| Jane | 30 |\n";
    assert_eq!(result, expected);
}

#[test]
fn test_cli_with_invalid_utf8_file() {
    let mut temp_file = NamedTempFile::new().unwrap();
    // Write valid CSV header, then invalid UTF-8 bytes
    write!(temp_file, "Name,Age\nJohn,25\n").unwrap();
    temp_file.write_all(&[0x80, 0x81, 0x82]).unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("Error: Csv"));
    assert!(stderr.contains("invalid utf-8"));
    assert!(stderr.contains("line 3, record 2"));
}

#[test]
fn test_cli_with_invalid_utf8_streaming_mode() {
    let mut temp_file = NamedTempFile::new().unwrap();
    // Write valid CSV header, then invalid UTF-8 bytes
    write!(temp_file, "Name,Age\nJohn,25\n").unwrap();
    temp_file.write_all(&[0x80, 0x81, 0x82]).unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", "--stream", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("Error: Csv"));
    assert!(stderr.contains("invalid utf-8"));
    assert!(stderr.contains("line 3, record 2"));
}

#[test]
fn test_cli_with_directory_instead_of_file() {
    let temp_dir = tempfile::tempdir().unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_dir.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    // On Linux, File::open() succeeds for directories but read() fails during CSV parsing (Error: Csv)
    // On Windows, File::open() fails immediately for directories (Error: Io)
    assert!(stderr.contains("Error: Csv") || stderr.contains("Error: Io"));
    // The key is that we get an error when trying to process a directory
}

#[test]
fn test_cli_with_binary_data_in_csv() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Data").unwrap();
    write!(temp_file, "Binary,").unwrap();
    // Write some binary data that will cause UTF-8 parsing issues
    temp_file.write_all(&[0xFF, 0xFE, 0xFD, 0xFC]).unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("Error: Csv"));
    assert!(stderr.contains("invalid utf-8"));
}

#[test]
fn test_cli_with_invalid_utf8_stdin() {
    let mut child = Command::new("cargo")
        .args(["run"])
        .arg("--")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    // Write valid CSV header, then invalid UTF-8 bytes
    let mut stdin_data = Vec::new();
    stdin_data.extend_from_slice(b"Name,Age\nJohn,25\n");
    stdin_data.extend_from_slice(&[0x80, 0x81, 0x82]);

    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(&stdin_data)
        .unwrap();

    let result = child.wait_with_output().unwrap();

    assert!(!result.status.success());
    let stderr = String::from_utf8(result.stderr).unwrap();
    assert!(stderr.contains("Error: Csv"));
    assert!(stderr.contains("invalid utf-8"));
}

#[test]
fn test_cli_with_permission_denied_file() {
    // This test only works on Unix-like systems where we can control file permissions
    #[cfg(unix)]
    {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        let temp_file = NamedTempFile::new().unwrap();

        // Try to make the file unreadable
        if let Ok(mut perms) = fs::metadata(temp_file.path()).map(|m| m.permissions()) {
            perms.set_mode(0o000);
            if fs::set_permissions(temp_file.path(), perms).is_ok() {
                let output = Command::new("cargo")
                    .args(["run", "--", temp_file.path().to_str().unwrap()])
                    .output()
                    .expect("Failed to execute command");

                assert!(!output.status.success());
                let stderr = String::from_utf8(output.stderr).unwrap();
                assert!(
                    stderr.contains("Permission denied") || stderr.contains("CSV parsing error")
                );
            }
        }
    }

    // On non-Unix systems (like Windows), we'll skip this test since permission
    // manipulation is platform-specific and complex
    #[cfg(not(unix))]
    {
        // Test passes by doing nothing - this ensures cross-platform compatibility
    }
}

#[test]
fn test_cli_with_large_field_causing_memory_error() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Data").unwrap();

    // Create a field that's extremely large to potentially cause issues
    // But not so large that it crashes the test runner
    let large_field = "x".repeat(100_000);
    writeln!(temp_file, "Test,\"{}\"", large_field).unwrap();

    // Add invalid UTF-8 at the end to guarantee an error
    temp_file.write_all(&[0x80, 0x81]).unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("Error: Csv") || stderr.contains("Error: Io"));
}

#[test]
fn test_cli_with_mixed_valid_and_invalid_utf8() {
    let mut temp_file = NamedTempFile::new().unwrap();
    writeln!(temp_file, "Name,Age,City").unwrap();
    writeln!(temp_file, "John,25,NYC").unwrap();
    writeln!(temp_file, "Jane,30,\"San Francisco\"").unwrap();

    // Add a line with invalid UTF-8 in the middle
    write!(temp_file, "Bob,35,").unwrap();
    temp_file.write_all(&[0xC0, 0xC1]).unwrap(); // Invalid UTF-8 sequence
    writeln!(temp_file).unwrap();

    let output = Command::new("cargo")
        .args(["run", "--", temp_file.path().to_str().unwrap()])
        .output()
        .expect("Failed to execute command");

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("Error: Csv"));
    assert!(stderr.contains("invalid utf-8"));
    // Should provide location information
    assert!(stderr.contains("line") || stderr.contains("record"));
}