coip-cli 0.2.0

CLI for converting, importing, exporting, diffing, inspecting, querying, verifying, and benchmarking COI (.coi) IP databases
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
641
//! Nushell-style rounded Unicode table renderer for `coip_format::Value`.
//!
//! Renders nested records, lists of records (multi-column tables with `#` index and
//! centered column headers), and indexed lists using Nushell's rounded box-drawing
//! style (`╭─┬─╮`, `│`, `├─┼─┤`, `╰─┴─╯`) and optional ANSI terminal colors.

use std::collections::HashSet;
use std::fmt::Write as _;
use std::io::IsTerminal;

use coip_format::Value;
use unicode_width::UnicodeWidthStr;

const ANSI_BOLD_GREEN: &str = "\x1b[1;32m";
const ANSI_LIGHT_CYAN: &str = "\x1b[96m";
const ANSI_BLUE: &str = "\x1b[34m";
const ANSI_RESET: &str = "\x1b[0m";

/// Formatting options for the Nushell-style table renderer.
#[derive(Debug, Clone, Copy, Default)]
pub struct TableOptions {
    /// Emit ANSI SGR color sequences matching Nushell's default theme.
    pub color: bool,
}

impl TableOptions {
    /// Detect color support from stdout TTY status and standard environment variables
    /// (`NO_COLOR`, `CLICOLOR_FORCE`, `TERM`).
    pub fn auto() -> Self {
        let no_color = std::env::var_os("NO_COLOR")
            .map(|v| !v.is_empty())
            .unwrap_or(false);
        let force = std::env::var_os("CLICOLOR_FORCE")
            .map(|v| !v.is_empty() && v != "0")
            .unwrap_or(false);
        let dumb_term = std::env::var_os("TERM")
            .map(|v| v == "dumb")
            .unwrap_or(false);
        let color = if no_color {
            false
        } else if force {
            true
        } else {
            !dumb_term && std::io::stdout().is_terminal()
        };
        Self { color }
    }

    /// Plain UTF-8 table output without ANSI escape sequences.
    #[cfg(test)]
    pub fn plain() -> Self {
        Self { color: false }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Align {
    Left,
    Right,
    Center,
}

#[derive(Debug, Clone)]
struct StyledLine {
    text: String,
    width: usize,
}

#[derive(Debug, Clone)]
struct CellBlock {
    lines: Vec<StyledLine>,
    max_width: usize,
    align: Align,
    is_table: bool,
}

impl CellBlock {
    fn from_lines(lines: Vec<StyledLine>, align: Align, is_table: bool) -> Self {
        let max_width = lines.iter().map(|l| l.width).max().unwrap_or(0);
        Self {
            lines,
            max_width,
            align,
            is_table,
        }
    }

    fn single(text: &str, style: Option<&str>, align: Align) -> Self {
        let lines = text_to_styled_lines(text, style);
        Self::from_lines(lines, align, false)
    }

    fn empty() -> Self {
        Self {
            lines: vec![StyledLine {
                text: String::new(),
                width: 0,
            }],
            max_width: 0,
            align: Align::Left,
            is_table: false,
        }
    }
}

/// Render a single `Value` as a Nushell-style rounded table.
pub fn render_value(val: &Value, opts: TableOptions) -> String {
    let block = match val {
        Value::Null => render_single_box("null", None),
        Value::Map(m) if m.is_empty() => render_single_box("empty record", None),
        Value::Map(m) => render_record_entries(m.iter().map(|(k, v)| (k.as_str(), v)), opts),
        Value::Array(a) if a.is_empty() => render_single_box("empty list", None),
        Value::Array(a) => render_array(a, opts),
        other => {
            let cell = render_cell(other, opts, false);
            render_grid(None, vec![vec![cell]], 1)
        }
    };
    join_block(&block)
}

/// Render an ordered sequence of `(key, value)` entries (e.g. multiple IP lookups)
/// as a 2-column Nushell-style record table preserving input order.
pub fn render_entries(entries: &[(String, Value)], opts: TableOptions) -> String {
    let block = if entries.is_empty() {
        render_single_box("empty record", None)
    } else {
        render_record_entries(entries.iter().map(|(k, v)| (k.as_str(), v)), opts)
    };
    join_block(&block)
}

fn join_block(block: &CellBlock) -> String {
    let mut out = String::new();
    for (i, line) in block.lines.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        out.push_str(&line.text);
    }
    out
}

fn render_single_box(text: &str, style: Option<&str>) -> CellBlock {
    render_grid(
        None,
        vec![vec![CellBlock::single(text, style, Align::Left)]],
        1,
    )
}

fn render_record_entries<'a>(
    entries: impl IntoIterator<Item = (&'a str, &'a Value)>,
    opts: TableOptions,
) -> CellBlock {
    let key_style = opts.color.then_some(ANSI_BOLD_GREEN);
    let mut rows = Vec::new();
    for (key, val) in entries {
        let val_cell = render_cell(val, opts, false);
        let mut key_lines = text_to_styled_lines(key, key_style);
        if val_cell.is_table {
            // Align key with the nested table's first content row, matching `nu | table -e`.
            key_lines.insert(
                0,
                StyledLine {
                    text: String::new(),
                    width: 0,
                },
            );
        }
        let key_cell = CellBlock::from_lines(key_lines, Align::Left, false);
        rows.push(vec![key_cell, val_cell]);
    }
    render_grid(None, rows, 2)
}

fn render_array(items: &[Value], opts: TableOptions) -> CellBlock {
    let header_style = opts.color.then_some(ANSI_BOLD_GREEN);

    // If every element is a Map and at least one map has keys, render a multi-column
    // table with `#` index column and centered column headers (matching Nushell).
    if items.iter().all(|v| matches!(v, Value::Map(_))) {
        let mut columns: Vec<&str> = Vec::new();
        let mut seen: HashSet<&str> = HashSet::new();
        for item in items {
            if let Value::Map(m) = item {
                for k in m.keys() {
                    if seen.insert(k.as_str()) {
                        columns.push(k.as_str());
                    }
                }
            }
        }

        if !columns.is_empty() {
            let missing_style = opts.color.then_some(ANSI_BLUE);
            let mut headers = Vec::with_capacity(columns.len() + 1);
            headers.push(CellBlock::single("#", header_style, Align::Center));
            for &col in &columns {
                headers.push(CellBlock::single(col, header_style, Align::Center));
            }

            let mut rows = Vec::with_capacity(items.len());
            for (idx, item) in items.iter().enumerate() {
                let mut row = Vec::with_capacity(columns.len() + 1);
                row.push(CellBlock::single(
                    &idx.to_string(),
                    header_style,
                    Align::Right,
                ));
                if let Value::Map(m) = item {
                    for &col in &columns {
                        match m.get(col) {
                            Some(v) => row.push(render_cell(v, opts, true)),
                            None => row.push(CellBlock::single("❎", missing_style, Align::Center)),
                        }
                    }
                }
                rows.push(row);
            }
            return render_grid(Some(headers), rows, columns.len() + 1);
        }
    }

    // Otherwise render a 2-column indexed list (no header row).
    let mut rows = Vec::with_capacity(items.len());
    for (idx, item) in items.iter().enumerate() {
        let idx_cell = CellBlock::single(&idx.to_string(), header_style, Align::Right);
        let val_cell = render_cell(item, opts, true);
        rows.push(vec![idx_cell, val_cell]);
    }
    render_grid(None, rows, 2)
}

fn render_cell(val: &Value, opts: TableOptions, align_numbers_right: bool) -> CellBlock {
    let num_align = if align_numbers_right {
        Align::Right
    } else {
        Align::Left
    };
    match val {
        Value::Null => CellBlock::empty(),
        Value::Bool(b) => {
            let style = opts.color.then_some(ANSI_LIGHT_CYAN);
            CellBlock::single(if *b { "true" } else { "false" }, style, Align::Left)
        }
        Value::U8(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::U16(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::U32(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::U64(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::U128(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::I32(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::I64(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::F32(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::F64(n) => CellBlock::single(&n.to_string(), None, num_align),
        Value::Utf8(s) => CellBlock::single(s, None, Align::Left),
        Value::Bytes(bytes) => CellBlock::single(&format_bytes_hex(bytes), None, Align::Left),
        Value::Array(a) if a.is_empty() => CellBlock::single("[list 0 items]", None, Align::Left),
        Value::Array(a) => render_array(a, opts),
        Value::Map(m) if m.is_empty() => CellBlock::single("{record 0 fields}", None, Align::Left),
        Value::Map(m) => render_record_entries(m.iter().map(|(k, v)| (k.as_str(), v)), opts),
    }
}

fn format_bytes_hex(bytes: &[u8]) -> String {
    if bytes.is_empty() {
        return String::from("0x[]");
    }
    let mut out = String::with_capacity(bytes.len() * 3 + 3);
    out.push_str("0x[");
    for (i, b) in bytes.iter().enumerate() {
        if i > 0 {
            out.push(' ');
        }
        let _ = write!(out, "{b:02x}");
    }
    out.push(']');
    out
}

fn text_to_styled_lines(text: &str, style: Option<&str>) -> Vec<StyledLine> {
    text.split('\n')
        .map(|raw| {
            let clean = sanitize_line(raw);
            let width = UnicodeWidthStr::width(clean.as_str());
            let styled = match style {
                Some(code) if !clean.is_empty() => format!("{code}{clean}{ANSI_RESET}"),
                _ => clean,
            };
            StyledLine {
                text: styled,
                width,
            }
        })
        .collect()
}

fn sanitize_line(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\t' => out.push_str("    "),
            '\r' => {}
            c if c.is_control() => {
                let _ = write!(out, "\\u{{{:04x}}}", c as u32);
            }
            c => out.push(c),
        }
    }
    out
}

fn render_grid(
    headers: Option<Vec<CellBlock>>,
    rows: Vec<Vec<CellBlock>>,
    num_cols: usize,
) -> CellBlock {
    debug_assert!(num_cols > 0);

    let mut col_widths = vec![0usize; num_cols];
    if let Some(ref hdrs) = headers {
        for (c, cell) in hdrs.iter().enumerate() {
            col_widths[c] = col_widths[c].max(cell.max_width);
        }
    }
    for row in &rows {
        for (c, cell) in row.iter().enumerate() {
            col_widths[c] = col_widths[c].max(cell.max_width);
        }
    }

    let total_width: usize = 1 + col_widths.iter().map(|&w| w + 3).sum::<usize>();
    let mut out_lines = Vec::new();

    out_lines.push(border_line('╭', '┬', '╮', &col_widths, total_width));

    if let Some(ref hdrs) = headers {
        push_row_lines(&mut out_lines, hdrs, &col_widths, total_width);
        out_lines.push(border_line('├', '┼', '┤', &col_widths, total_width));
    }

    for row in &rows {
        push_row_lines(&mut out_lines, row, &col_widths, total_width);
    }

    out_lines.push(border_line('╰', '┴', '╯', &col_widths, total_width));

    CellBlock::from_lines(out_lines, Align::Left, true)
}

fn border_line(
    left: char,
    mid: char,
    right: char,
    col_widths: &[usize],
    total_width: usize,
) -> StyledLine {
    let mut s = String::with_capacity(total_width * 3);
    s.push(left);
    for (i, &w) in col_widths.iter().enumerate() {
        if i > 0 {
            s.push(mid);
        }
        for _ in 0..(w + 2) {
            s.push('─');
        }
    }
    s.push(right);
    StyledLine {
        text: s,
        width: total_width,
    }
}

fn push_row_lines(
    out: &mut Vec<StyledLine>,
    row: &[CellBlock],
    col_widths: &[usize],
    total_width: usize,
) {
    let height = row.iter().map(|c| c.lines.len()).max().unwrap_or(1).max(1);
    for line_idx in 0..height {
        let mut s = String::with_capacity(total_width + 16);
        s.push('│');
        for (c, &col_w) in col_widths.iter().enumerate() {
            s.push(' ');
            if let Some(cell) = row.get(c)
                && let Some(line) = cell.lines.get(line_idx)
            {
                let pad = col_w.saturating_sub(line.width);
                match cell.align {
                    Align::Left => {
                        s.push_str(&line.text);
                        push_spaces(&mut s, pad);
                    }
                    Align::Right => {
                        push_spaces(&mut s, pad);
                        s.push_str(&line.text);
                    }
                    Align::Center => {
                        let left_pad = pad / 2;
                        let right_pad = pad - left_pad;
                        push_spaces(&mut s, left_pad);
                        s.push_str(&line.text);
                        push_spaces(&mut s, right_pad);
                    }
                }
            } else {
                push_spaces(&mut s, col_w);
            }
            s.push(' ');
            s.push('│');
        }
        out.push(StyledLine {
            text: s,
            width: total_width,
        });
    }
}

fn push_spaces(out: &mut String, count: usize) {
    for _ in 0..count {
        out.push(' ');
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::*;

    fn map(pairs: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
        let mut m = BTreeMap::new();
        for (k, v) in pairs {
            m.insert(k.to_owned(), v);
        }
        Value::Map(m)
    }

    #[test]
    fn test_nested_record_with_cjk_matches_nushell() {
        let rec = map([
            (
                "country",
                map([
                    ("geoname_id", Value::U32(6252001)),
                    ("is_in_european_union", Value::Bool(false)),
                    ("iso_code", Value::Utf8("US".into())),
                    (
                        "names",
                        map([
                            ("de", Value::Utf8("USA".into())),
                            ("en", Value::Utf8("United States".into())),
                            ("ja", Value::Utf8("アメリカ合衆国".into())),
                            ("zh-CN", Value::Utf8("美国".into())),
                        ]),
                    ),
                ]),
            ),
            (
                "location",
                map([
                    ("accuracy_radius", Value::U16(1000)),
                    ("latitude", Value::F64(37.7510123)),
                    ("longitude", Value::F64(-97.8220456)),
                    ("time_zone", Value::Utf8("America/Chicago".into())),
                ]),
            ),
            ("traits", map([("is_anycast", Value::Bool(false))])),
        ]);

        let expected = "\
╭──────────┬───────────────────────────────────────────────────────╮
│          │ ╭──────────────────────┬────────────────────────────╮ │
│ country  │ │ geoname_id           │ 6252001                    │ │
│          │ │ is_in_european_union │ false                      │ │
│          │ │ iso_code             │ US                         │ │
│          │ │                      │ ╭───────┬────────────────╮ │ │
│          │ │ names                │ │ de    │ USA            │ │ │
│          │ │                      │ │ en    │ United States  │ │ │
│          │ │                      │ │ ja    │ アメリカ合衆国 │ │ │
│          │ │                      │ │ zh-CN │ 美国           │ │ │
│          │ │                      │ ╰───────┴────────────────╯ │ │
│          │ ╰──────────────────────┴────────────────────────────╯ │
│          │ ╭─────────────────┬─────────────────╮                 │
│ location │ │ accuracy_radius │ 1000            │                 │
│          │ │ latitude        │ 37.7510123      │                 │
│          │ │ longitude       │ -97.8220456     │                 │
│          │ │ time_zone       │ America/Chicago │                 │
│          │ ╰─────────────────┴─────────────────╯                 │
│          │ ╭────────────┬───────╮                                │
│ traits   │ │ is_anycast │ false │                                │
│          │ ╰────────────┴───────╯                                │
╰──────────┴───────────────────────────────────────────────────────╯";

        assert_eq!(render_value(&rec, TableOptions::plain()), expected);
    }

    #[test]
    fn test_array_of_records_and_scalars_and_empty() {
        let rec = map([
            (
                "subdivisions",
                Value::Array(vec![
                    map([
                        ("iso_code", Value::Utf8("CA".into())),
                        (
                            "names",
                            map([
                                ("en", Value::Utf8("California".into())),
                                ("zh-CN", Value::Utf8("加利福尼亚".into())),
                            ]),
                        ),
                    ]),
                    map([
                        ("iso_code", Value::Utf8("SF".into())),
                        ("names", map([("en", Value::Utf8("San Francisco".into()))])),
                    ]),
                ]),
            ),
            (
                "tags",
                Value::Array(vec![
                    Value::Utf8("cdn".into()),
                    Value::Utf8("anycast".into()),
                ]),
            ),
            ("empty_arr", Value::Array(vec![])),
            ("empty_obj", Value::Map(BTreeMap::new())),
            ("nothing", Value::Null),
        ]);

        let expected = "\
╭──────────────┬───────────────────────────────────────────╮
│ empty_arr    │ [list 0 items]                            │
│ empty_obj    │ {record 0 fields}                         │
│ nothing      │                                           │
│              │ ╭───┬──────────┬────────────────────────╮ │
│ subdivisions │ │ # │ iso_code │         names          │ │
│              │ ├───┼──────────┼────────────────────────┤ │
│              │ │ 0 │ CA       │ ╭───────┬────────────╮ │ │
│              │ │   │          │ │ en    │ California │ │ │
│              │ │   │          │ │ zh-CN │ 加利福尼亚 │ │ │
│              │ │   │          │ ╰───────┴────────────╯ │ │
│              │ │ 1 │ SF       │ ╭────┬───────────────╮ │ │
│              │ │   │          │ │ en │ San Francisco │ │ │
│              │ │   │          │ ╰────┴───────────────╯ │ │
│              │ ╰───┴──────────┴────────────────────────╯ │
│              │ ╭───┬─────────╮                           │
│ tags         │ │ 0 │ cdn     │                           │
│              │ │ 1 │ anycast │                           │
│              │ ╰───┴─────────╯                           │
╰──────────────┴───────────────────────────────────────────╯";

        assert_eq!(render_value(&rec, TableOptions::plain()), expected);
    }

    #[test]
    fn test_sparse_table_missing_cells_and_alignment() {
        let arr = Value::Array(vec![
            map([("a", Value::U32(1)), ("b", Value::Utf8("x".into()))]),
            Value::Map(BTreeMap::new()),
            map([("a", Value::U32(2)), ("c", Value::Bool(true))]),
        ]);

        let expected = "\
╭───┬────┬────┬──────╮
│ # │ a  │ b  │  c   │
├───┼────┼────┼──────┤
│ 0 │  1 │ x  │  ❎  │
│ 1 │ ❎ │ ❎ │  ❎  │
│ 2 │  2 │ ❎ │ true │
╰───┴────┴────┴──────╯";

        assert_eq!(render_value(&arr, TableOptions::plain()), expected);
    }

    #[test]
    fn test_root_null_and_empty_containers() {
        assert_eq!(
            render_value(&Value::Null, TableOptions::plain()),
            "╭──────╮\n│ null │\n╰──────╯"
        );
        assert_eq!(
            render_value(&Value::Map(BTreeMap::new()), TableOptions::plain()),
            "╭──────────────╮\n│ empty record │\n╰──────────────╯"
        );
        assert_eq!(
            render_value(&Value::Array(vec![]), TableOptions::plain()),
            "╭────────────╮\n│ empty list │\n╰────────────╯"
        );
    }

    #[test]
    fn test_multiline_string_and_bytes() {
        let rec = map([
            ("bin", Value::Bytes(vec![0xde, 0xad, 0xbe, 0xef])),
            ("note", Value::Utf8("line1\nline2".into())),
        ]);

        let expected = "\
╭──────┬─────────────────╮
│ bin  │ 0x[de ad be ef] │
│ note │ line1           │
│      │ line2           │
╰──────┴─────────────────╯";
        assert_eq!(render_value(&rec, TableOptions::plain()), expected);
    }

    #[test]
    fn test_ansi_color_preserves_alignment() {
        let rec = map([
            ("flag", Value::Bool(true)),
            ("name", Value::Utf8("US".into())),
        ]);
        let colored = render_value(&rec, TableOptions { color: true });
        assert!(colored.contains(ANSI_BOLD_GREEN));
        assert!(colored.contains(ANSI_LIGHT_CYAN));
        // Stripping ANSI codes must produce the exact same plain table!
        let stripped = strip_ansi(&colored);
        assert_eq!(stripped, render_value(&rec, TableOptions::plain()));
    }

    fn strip_ansi(s: &str) -> String {
        let mut out = String::with_capacity(s.len());
        let mut chars = s.chars();
        while let Some(c) = chars.next() {
            if c == '\x1b' {
                for next in chars.by_ref() {
                    if next == 'm' {
                        break;
                    }
                }
            } else {
                out.push(c);
            }
        }
        out
    }
}