tokmd-format 1.10.0

Output formatting and serialization (Markdown, JSON, CSV) for tokmd.
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Deep tests for export formatting paths (JSONL, CSV, JSON, CycloneDX).
//!
//! Covers: field escaping, empty data for every format, newline-delimited
//! JSONL invariants, CycloneDX structural validity, redaction in CycloneDX,
//! and determinism of serialized output.

use std::path::PathBuf;

use tokmd_format::{
    write_export_csv_to, write_export_cyclonedx_to, write_export_cyclonedx_with_options,
    write_export_json_to, write_export_jsonl_to,
};
use tokmd_settings::{ChildIncludeMode, ScanOptions};
use tokmd_types::{ExportArgs, ExportData, ExportFormat, FileKind, FileRow, RedactMode};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn file_row(path: &str, module: &str, lang: &str, kind: FileKind, code: usize) -> FileRow {
    FileRow {
        path: path.to_string(),
        module: module.to_string(),
        lang: lang.to_string(),
        kind,
        code,
        comments: code / 5,
        blanks: code / 10,
        lines: code + code / 5 + code / 10,
        bytes: code * 10,
        tokens: code * 3,
    }
}

fn sample_rows() -> Vec<FileRow> {
    vec![
        file_row("src/lib.rs", "src", "Rust", FileKind::Parent, 200),
        file_row("tests/it.rs", "tests", "Rust", FileKind::Parent, 80),
        file_row("src/main.rs", "src", "Rust", FileKind::Parent, 50),
    ]
}

fn export_data(rows: Vec<FileRow>) -> ExportData {
    ExportData {
        rows,
        module_roots: vec!["src".into()],
        module_depth: 1,
        children: ChildIncludeMode::Separate,
    }
}

fn default_args(format: ExportFormat) -> ExportArgs {
    ExportArgs {
        paths: vec![PathBuf::from(".")],
        format,
        output: None,
        module_roots: vec![],
        module_depth: 1,
        children: ChildIncludeMode::Separate,
        min_code: 0,
        max_rows: 0,
        redact: RedactMode::None,
        meta: true,
        strip_prefix: None,
    }
}

fn default_scan() -> ScanOptions {
    ScanOptions::default()
}

// ===========================================================================
// 1. JSONL: each line is valid JSON, newline-delimited
// ===========================================================================

#[test]
fn jsonl_each_line_is_valid_json_with_meta() {
    let data = export_data(sample_rows());
    let args = default_args(ExportFormat::Jsonl);
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    for (i, line) in output.lines().enumerate() {
        assert!(
            serde_json::from_str::<serde_json::Value>(line).is_ok(),
            "line {i} is not valid JSON: {line}"
        );
    }
}

#[test]
fn jsonl_without_meta_has_only_data_rows() {
    let data = export_data(sample_rows());
    let mut args = default_args(ExportFormat::Jsonl);
    args.meta = false;
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let lines: Vec<&str> = output.lines().collect();

    // No meta line → all lines are data rows
    assert_eq!(lines.len(), 3);
    for line in &lines {
        let v: serde_json::Value = serde_json::from_str(line).expect("operation must succeed");
        assert_eq!(v["type"], "row");
    }
}

#[test]
fn jsonl_with_meta_first_line_is_meta() {
    let data = export_data(sample_rows());
    let args = default_args(ExportFormat::Jsonl);
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let first_line = output
        .lines()
        .next()
        .expect("output must have at least one line");
    let v: serde_json::Value = serde_json::from_str(first_line).expect("operation must succeed");

    assert_eq!(v["type"], "meta");
    assert!(v["schema_version"].is_number());
}

#[test]
fn jsonl_row_count_equals_data_rows() {
    let rows = sample_rows();
    let expected = rows.len();
    let data = export_data(rows);
    let mut args = default_args(ExportFormat::Jsonl);
    args.meta = false;
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    assert_eq!(output.lines().count(), expected);
}

#[test]
fn jsonl_ends_with_newline() {
    let data = export_data(sample_rows());
    let args = default_args(ExportFormat::Jsonl);
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    assert!(output.ends_with('\n'), "JSONL must end with newline");
}

// ===========================================================================
// 2. CSV: headers, field escaping, column consistency
// ===========================================================================

#[test]
fn csv_first_line_is_header() {
    let data = export_data(sample_rows());
    let args = default_args(ExportFormat::Csv);
    let mut buf = Vec::new();

    write_export_csv_to(&mut buf, &data, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let header = output
        .lines()
        .next()
        .expect("output must have at least one line");

    assert_eq!(
        header,
        "path,module,lang,kind,code,comments,blanks,lines,bytes,tokens"
    );
}

#[test]
fn csv_column_count_consistent_across_all_rows() {
    let data = export_data(sample_rows());
    let args = default_args(ExportFormat::Csv);
    let mut buf = Vec::new();

    write_export_csv_to(&mut buf, &data, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    let expected_cols = 10;
    for (i, line) in output.lines().enumerate() {
        // CSV parser handles quoting; a simple count works for non-quoted data
        let cols = line.split(',').count();
        assert_eq!(
            cols, expected_cols,
            "line {i} has {cols} columns, expected {expected_cols}"
        );
    }
}

#[test]
fn csv_escapes_commas_in_path() {
    let rows = vec![file_row("src/a,b.rs", "src", "Rust", FileKind::Parent, 100)];
    let data = export_data(rows);
    let args = default_args(ExportFormat::Csv);
    let mut buf = Vec::new();

    write_export_csv_to(&mut buf, &data, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    // CSV library should quote fields containing commas
    assert!(
        output.contains("\"src/a,b.rs\""),
        "comma in path must be quoted: {output}"
    );
}

#[test]
fn csv_escapes_quotes_in_path() {
    let rows = vec![file_row(
        "src/a\"b.rs",
        "src",
        "Rust",
        FileKind::Parent,
        100,
    )];
    let data = export_data(rows);
    let args = default_args(ExportFormat::Csv);
    let mut buf = Vec::new();

    write_export_csv_to(&mut buf, &data, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    // CSV escapes double-quotes by doubling them inside a quoted field
    assert!(
        output.contains("\"\""),
        "quote in path must be escaped: {output}"
    );
}

#[test]
fn csv_includes_child_file_kind() {
    let rows = vec![
        file_row("src/lib.rs", "src", "Rust", FileKind::Parent, 100),
        file_row("src/inline.html", "src", "HTML", FileKind::Child, 20),
    ];
    let data = export_data(rows);
    let args = default_args(ExportFormat::Csv);
    let mut buf = Vec::new();

    write_export_csv_to(&mut buf, &data, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    assert!(output.contains(",parent,"));
    assert!(output.contains(",child,"));
}

// ===========================================================================
// 3. CycloneDX: structural validity
// ===========================================================================

#[test]
fn cyclonedx_output_is_valid_json() {
    let data = export_data(sample_rows());
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::None).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");
    assert_eq!(v["bomFormat"], "CycloneDX");
    assert_eq!(v["specVersion"], "1.6");
}

#[test]
fn cyclonedx_component_count_matches_rows() {
    let rows = sample_rows();
    let expected = rows.len();
    let data = export_data(rows);
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::None).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    assert_eq!(
        v["components"]
            .as_array()
            .expect("must be a JSON array")
            .len(),
        expected
    );
}

#[test]
fn cyclonedx_components_have_required_properties() {
    let data = export_data(sample_rows());
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::None).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    for comp in v["components"].as_array().expect("must be a JSON array") {
        assert_eq!(comp["type"], "file");
        assert!(comp["name"].is_string());
        let props = comp["properties"].as_array().expect("must be a JSON array");
        let prop_names: Vec<&str> = props
            .iter()
            .map(|p| p["name"].as_str().expect("must be a JSON string"))
            .collect();
        assert!(prop_names.contains(&"tokmd:lang"));
        assert!(prop_names.contains(&"tokmd:code"));
        assert!(prop_names.contains(&"tokmd:lines"));
        assert!(prop_names.contains(&"tokmd:tokens"));
    }
}

#[test]
fn cyclonedx_child_kind_property_only_on_children() {
    let rows = vec![
        file_row("src/lib.rs", "src", "Rust", FileKind::Parent, 100),
        file_row("src/inline.html", "src", "HTML", FileKind::Child, 20),
    ];
    let data = export_data(rows);
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::None).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    let components = v["components"].as_array().expect("must be a JSON array");

    // Parent should NOT have tokmd:kind
    let parent_props: Vec<&str> = components[0]["properties"]
        .as_array()
        .expect("operation must succeed")
        .iter()
        .map(|p| p["name"].as_str().expect("must be a JSON string"))
        .collect();
    assert!(!parent_props.contains(&"tokmd:kind"));

    // Child should have tokmd:kind = "child"
    let child_props = components[1]["properties"]
        .as_array()
        .expect("must be a JSON array");
    let kind_prop = child_props
        .iter()
        .find(|p| p["name"] == "tokmd:kind")
        .expect("operation must succeed");
    assert_eq!(kind_prop["value"], "child");
}

#[test]
fn cyclonedx_with_fixed_serial_and_timestamp_is_deterministic() {
    let data = export_data(sample_rows());
    let serial = "urn:uuid:00000000-0000-0000-0000-000000000000".to_string();
    let ts = "2024-01-01T00:00:00Z".to_string();

    let mut buf1 = Vec::new();
    write_export_cyclonedx_with_options(
        &mut buf1,
        &data,
        RedactMode::None,
        Some(serial.clone()),
        Some(ts.clone()),
    )
    .expect("operation must succeed");

    let mut buf2 = Vec::new();
    write_export_cyclonedx_with_options(&mut buf2, &data, RedactMode::None, Some(serial), Some(ts))
        .expect("operation must succeed");

    assert_eq!(
        buf1, buf2,
        "CycloneDX must be deterministic with fixed params"
    );
}

#[test]
fn cyclonedx_redact_paths_hashes_component_names() {
    let data = export_data(sample_rows());
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::Paths).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    for comp in v["components"].as_array().expect("must be a JSON array") {
        let name = comp["name"].as_str().expect("must be a JSON string");
        // Redacted paths should NOT contain the original path segments
        assert!(
            !name.starts_with("src/"),
            "redacted path should not start with src/: {name}"
        );
    }
}

#[test]
fn cyclonedx_metadata_contains_tool_info() {
    let data = export_data(sample_rows());
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::None).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    let tools = v["metadata"]["tools"]
        .as_array()
        .expect("must be a JSON array");
    assert!(!tools.is_empty());
    assert_eq!(tools[0]["name"], "tokmd");
}

// ===========================================================================
// 4. Empty data handling for all formats
// ===========================================================================

#[test]
fn jsonl_empty_data_with_meta_produces_only_meta_line() {
    let data = export_data(vec![]);
    let args = default_args(ExportFormat::Jsonl);
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let lines: Vec<&str> = output.lines().collect();

    assert_eq!(lines.len(), 1, "empty data with meta = 1 line");
    let v: serde_json::Value = serde_json::from_str(lines[0]).expect("operation must succeed");
    assert_eq!(v["type"], "meta");
}

#[test]
fn jsonl_empty_data_without_meta_produces_no_output() {
    let data = export_data(vec![]);
    let mut args = default_args(ExportFormat::Jsonl);
    args.meta = false;
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    assert!(output.is_empty(), "empty data without meta = no output");
}

#[test]
fn csv_empty_data_produces_only_header() {
    let data = export_data(vec![]);
    let args = default_args(ExportFormat::Csv);
    let mut buf = Vec::new();

    write_export_csv_to(&mut buf, &data, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let lines: Vec<&str> = output.lines().collect();

    assert_eq!(lines.len(), 1, "empty data CSV = header only");
    assert!(lines[0].starts_with("path,"));
}

#[test]
fn json_empty_data_with_meta_produces_valid_envelope() {
    let data = export_data(vec![]);
    let args = default_args(ExportFormat::Json);
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_json_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    assert!(v["schema_version"].is_number());
    assert_eq!(v["rows"].as_array().expect("must be a JSON array").len(), 0);
}

#[test]
fn json_empty_data_without_meta_produces_empty_array() {
    let data = export_data(vec![]);
    let mut args = default_args(ExportFormat::Json);
    args.meta = false;
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_json_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    assert!(v.is_array());
    assert_eq!(v.as_array().expect("must be a JSON array").len(), 0);
}

#[test]
fn cyclonedx_empty_data_produces_valid_bom_with_no_components() {
    let data = export_data(vec![]);
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::None).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    assert_eq!(v["bomFormat"], "CycloneDX");
    assert_eq!(
        v["components"]
            .as_array()
            .expect("must be a JSON array")
            .len(),
        0
    );
}

// ===========================================================================
// 5. Determinism: same input → identical output
// ===========================================================================

#[test]
fn csv_output_is_deterministic() {
    let data = export_data(sample_rows());
    let args = default_args(ExportFormat::Csv);

    let mut buf1 = Vec::new();
    write_export_csv_to(&mut buf1, &data, &args).expect("operation must succeed");

    let mut buf2 = Vec::new();
    write_export_csv_to(&mut buf2, &data, &args).expect("operation must succeed");

    assert_eq!(buf1, buf2, "CSV output must be deterministic");
}

#[test]
fn jsonl_without_meta_is_deterministic() {
    let data = export_data(sample_rows());
    let mut args = default_args(ExportFormat::Jsonl);
    args.meta = false;
    let scan = default_scan();

    let mut buf1 = Vec::new();
    write_export_jsonl_to(&mut buf1, &data, &scan, &args).expect("operation must succeed");

    let mut buf2 = Vec::new();
    write_export_jsonl_to(&mut buf2, &data, &scan, &args).expect("operation must succeed");

    assert_eq!(buf1, buf2, "JSONL (no meta) output must be deterministic");
}

// ===========================================================================
// 6. JSONL row field integrity
// ===========================================================================

#[test]
fn jsonl_rows_contain_all_file_row_fields() {
    let data = export_data(sample_rows());
    let mut args = default_args(ExportFormat::Jsonl);
    args.meta = false;
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    let first: serde_json::Value = serde_json::from_str(
        output
            .lines()
            .next()
            .expect("output must have at least one line"),
    )
    .expect("operation must succeed");
    assert!(first["path"].is_string());
    assert!(first["module"].is_string());
    assert!(first["lang"].is_string());
    assert!(first["kind"].is_string());
    assert!(first["code"].is_number());
    assert!(first["comments"].is_number());
    assert!(first["blanks"].is_number());
    assert!(first["lines"].is_number());
    assert!(first["bytes"].is_number());
    assert!(first["tokens"].is_number());
}

#[test]
fn jsonl_row_values_match_input_data() {
    let rows = vec![file_row("src/lib.rs", "src", "Rust", FileKind::Parent, 100)];
    let data = export_data(rows);
    let mut args = default_args(ExportFormat::Jsonl);
    args.meta = false;
    let scan = default_scan();
    let mut buf = Vec::new();

    write_export_jsonl_to(&mut buf, &data, &scan, &args).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");

    let v: serde_json::Value = serde_json::from_str(
        output
            .lines()
            .next()
            .expect("output must have at least one line"),
    )
    .expect("operation must succeed");
    assert_eq!(v["path"], "src/lib.rs");
    assert_eq!(v["lang"], "Rust");
    assert_eq!(v["code"], 100);
    assert_eq!(v["kind"], "parent");
}

// ===========================================================================
// 7. CycloneDX: group field presence
// ===========================================================================

#[test]
fn cyclonedx_empty_module_omits_group_field() {
    let rows = vec![file_row("README.md", "", "Markdown", FileKind::Parent, 10)];
    let data = export_data(rows);
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::None).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    let comp = &v["components"][0];
    assert!(comp.get("group").is_none() || comp["group"].is_null());
}

#[test]
fn cyclonedx_nonempty_module_includes_group_field() {
    let rows = vec![file_row("src/lib.rs", "src", "Rust", FileKind::Parent, 100)];
    let data = export_data(rows);
    let mut buf = Vec::new();

    write_export_cyclonedx_to(&mut buf, &data, RedactMode::None).expect("operation must succeed");
    let output = String::from_utf8(buf).expect("output must be valid UTF-8");
    let v: serde_json::Value = serde_json::from_str(&output).expect("must parse valid JSON");

    let comp = &v["components"][0];
    assert_eq!(comp["group"], "src");
}