nu-explore 0.112.1

Nushell table pager
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
//! Conversion utilities between Nu values and JSON, and config documentation parsing.

use crate::explore_config::types::NuValueType;
use nu_protocol::engine::EngineState;
use nu_protocol::{ShellError, shell_error::generic::GenericError};
use nu_utils::ConfigFileKind;
use serde_json::Value;
use std::collections::HashMap;
use std::error::Error;

/// Convert a nu_protocol::Value to a serde_json::Value
/// This properly handles closures by converting them to their string representation
#[allow(clippy::only_used_in_recursion)]
pub fn nu_value_to_json(
    engine_state: &EngineState,
    value: &nu_protocol::Value,
    span: nu_protocol::Span,
) -> Result<Value, ShellError> {
    Ok(match value {
        nu_protocol::Value::Bool { val, .. } => Value::Bool(*val),
        nu_protocol::Value::Int { val, .. } => Value::Number((*val).into()),
        nu_protocol::Value::Float { val, .. } => serde_json::Number::from_f64(*val)
            .map(Value::Number)
            .unwrap_or(Value::Null),
        nu_protocol::Value::String { val, .. } => Value::String(val.clone()),
        nu_protocol::Value::Nothing { .. } => Value::Null,
        nu_protocol::Value::List { vals, .. } => {
            let json_vals: Result<Vec<_>, _> = vals
                .iter()
                .map(|v| nu_value_to_json(engine_state, v, span))
                .collect();
            Value::Array(json_vals?)
        }
        nu_protocol::Value::Record { val, .. } => {
            let mut map = serde_json::Map::new();
            for (k, v) in val.iter() {
                map.insert(k.clone(), nu_value_to_json(engine_state, v, span)?);
            }
            Value::Object(map)
        }
        nu_protocol::Value::Closure { val, .. } => {
            // Convert closure to its string representation instead of serializing internal structure
            let closure_string =
                val.coerce_into_string(engine_state, value.span())
                    .map_err(|e| {
                        ShellError::Generic(
                            GenericError::new(
                                "Failed to convert closure to string",
                                "",
                                value.span(),
                            )
                            .with_inner([e]),
                        )
                    })?;
            Value::String(closure_string.to_string())
        }
        nu_protocol::Value::Filesize { val, .. } => Value::Number(val.get().into()),
        nu_protocol::Value::Duration { val, .. } => Value::Number((*val).into()),
        nu_protocol::Value::Date { val, .. } => Value::String(val.to_string()),
        nu_protocol::Value::Glob { val, .. } => Value::String(val.to_string()),
        nu_protocol::Value::CellPath { val, .. } => {
            let parts: Vec<Value> = val
                .members
                .iter()
                .map(|m| match m {
                    nu_protocol::ast::PathMember::String { val, .. } => Value::String(val.clone()),
                    nu_protocol::ast::PathMember::Int { val, .. } => {
                        Value::Number((*val as i64).into())
                    }
                })
                .collect();
            Value::Array(parts)
        }
        nu_protocol::Value::Binary { val, .. } => Value::Array(
            val.iter()
                .map(|b| Value::Number((*b as i64).into()))
                .collect(),
        ),
        nu_protocol::Value::Range { .. } => Value::Null,
        nu_protocol::Value::Error { error, .. } => {
            return Err(*error.clone());
        }
        nu_protocol::Value::Custom { val, .. } => {
            let collected = val.to_base_value(value.span())?;
            nu_value_to_json(engine_state, &collected, span)?
        }
    })
}

/// Parse the doc_config.nu file to extract documentation for each config path
/// Returns a HashMap mapping config paths (e.g., "history.file_format") to their documentation
pub fn parse_config_documentation() -> HashMap<String, String> {
    let doc_content = ConfigFileKind::Config.doc();
    let mut doc_map = HashMap::new();
    let mut current_comments: Vec<String> = Vec::new();

    for line in doc_content.lines() {
        let trimmed = line.trim();

        if trimmed.is_empty() {
            // Empty lines clear the comment buffer - this ensures section headings
            // (which are separated from actual documentation by blank lines)
            // don't get included in the documentation for settings
            current_comments.clear();
        } else if trimmed.starts_with('#') {
            // Collect comment lines (strip the leading # and space)
            let comment = trimmed.trim_start_matches('#').trim();
            if !comment.is_empty() {
                current_comments.push(comment.to_string());
            }
        } else if trimmed.starts_with("$env.config.") {
            // This is a config setting line
            // Extract the path (everything between "$env.config." and " =" or end of relevant part)
            if let Some(path) = extract_config_path(trimmed)
                && !current_comments.is_empty()
            {
                // Join all collected comments as the documentation
                let doc = current_comments.join("\n");
                doc_map.insert(path, doc);
            }
            // Clear comments after processing a setting
            current_comments.clear();
        } else {
            // Non-comment, non-config, non-empty line - might be code examples, clear comments
            current_comments.clear();
        }
    }

    doc_map
}

/// Extract the config path from a line like "$env.config.history.file_format = ..."
/// Returns the path without "$env.config." prefix (e.g., "history.file_format")
pub fn extract_config_path(line: &str) -> Option<String> {
    let line = line.trim();
    if !line.starts_with("$env.config.") {
        return None;
    }

    // Remove "$env.config." prefix
    let rest = &line["$env.config.".len()..];

    // Find where the path ends (at '=' or end of line for bare references)
    let path_end = rest.find(['=', ' ']).unwrap_or(rest.len());

    let path = rest[..path_end].trim();
    if path.is_empty() {
        None
    } else {
        Some(path.to_string())
    }
}

/// Build a map of path identifiers to NuValueType for tracking original nushell types
pub fn build_nu_type_map(
    value: &nu_protocol::Value,
    current_path: Vec<String>,
    type_map: &mut HashMap<String, NuValueType>,
) {
    let identifier = path_to_identifier(&current_path);

    if !identifier.is_empty() {
        type_map.insert(identifier.clone(), NuValueType::from_nu_value(value));
    }

    match value {
        nu_protocol::Value::Record { val, .. } => {
            for (k, v) in val.iter() {
                let mut path = current_path.clone();
                path.push(k.clone());
                build_nu_type_map(v, path, type_map);
            }
        }
        nu_protocol::Value::List { vals, .. } => {
            for (idx, v) in vals.iter().enumerate() {
                let mut path = current_path.clone();
                path.push(idx.to_string());
                build_nu_type_map(v, path, type_map);
            }
        }
        _ => {}
    }
}

/// Build a map of path identifiers to original Nu values for types that can't be roundtripped
/// (like Closures, Dates, Ranges, etc.)
pub fn build_original_value_map(
    value: &nu_protocol::Value,
    current_path: Vec<String>,
    value_map: &mut HashMap<String, nu_protocol::Value>,
) {
    let identifier = path_to_identifier(&current_path);

    // Store values that can't be roundtripped through JSON
    if !identifier.is_empty() {
        match value {
            nu_protocol::Value::Closure { .. }
            | nu_protocol::Value::Date { .. }
            | nu_protocol::Value::Range { .. } => {
                value_map.insert(identifier.clone(), value.clone());
            }
            _ => {}
        }
    }

    match value {
        nu_protocol::Value::Record { val, .. } => {
            for (k, v) in val.iter() {
                let mut path = current_path.clone();
                path.push(k.clone());
                build_original_value_map(v, path, value_map);
            }
        }
        nu_protocol::Value::List { vals, .. } => {
            for (idx, v) in vals.iter().enumerate() {
                let mut path = current_path.clone();
                path.push(idx.to_string());
                build_original_value_map(v, path, value_map);
            }
        }
        _ => {}
    }
}

/// Convert a path vector to an identifier string (e.g., ["history", "file_format"] -> "history.file_format")
fn path_to_identifier(path: &[String]) -> String {
    if path.is_empty() {
        String::new()
    } else {
        path.iter()
            .enumerate()
            .map(|(i, p)| {
                if p.parse::<usize>().is_ok() {
                    format!("[{}]", p)
                } else if i == 0 {
                    p.clone()
                } else {
                    format!(".{}", p)
                }
            })
            .collect::<String>()
    }
}

/// Convert a serde_json::Value to a nu_protocol::Value (simple version without type info)
#[allow(dead_code)]
pub fn json_to_nu_value(
    json: &Value,
    span: nu_protocol::Span,
) -> Result<nu_protocol::Value, Box<dyn Error>> {
    json_to_nu_value_with_types(json, span, &None, &None, Vec::new())
}

/// Convert a serde_json::Value to a nu_protocol::Value, using type information to preserve
/// original Nu types like Duration, Filesize, and Closure
pub fn json_to_nu_value_with_types(
    json: &Value,
    span: nu_protocol::Span,
    type_map: &Option<HashMap<String, NuValueType>>,
    original_values: &Option<HashMap<String, nu_protocol::Value>>,
    current_path: Vec<String>,
) -> Result<nu_protocol::Value, Box<dyn Error>> {
    let identifier = path_to_identifier(&current_path);
    let original_type = type_map.as_ref().and_then(|m| m.get(&identifier));

    Ok(match json {
        Value::Null => nu_protocol::Value::nothing(span),
        Value::Bool(b) => nu_protocol::Value::bool(*b, span),
        Value::Number(n) => {
            // Check if we need to convert to a special type based on original
            if let Some(orig_type) = original_type {
                match orig_type {
                    NuValueType::Duration => {
                        if let Some(i) = n.as_i64() {
                            return Ok(nu_protocol::Value::duration(i, span));
                        }
                    }
                    NuValueType::Filesize => {
                        if let Some(i) = n.as_i64() {
                            return Ok(nu_protocol::Value::filesize(i, span));
                        }
                    }
                    _ => {}
                }
            }
            // Default number handling
            if let Some(i) = n.as_i64() {
                nu_protocol::Value::int(i, span)
            } else if let Some(f) = n.as_f64() {
                nu_protocol::Value::float(f, span)
            } else {
                return Err(format!("Unsupported number: {}", n).into());
            }
        }
        Value::String(s) => {
            // Check if we need to restore an original value that can't be roundtripped
            if let Some(orig_type) = original_type {
                match orig_type {
                    NuValueType::Closure | NuValueType::Date | NuValueType::Range => {
                        // Try to get the original value - closures, dates, and ranges
                        // can't be reconstructed from their string representation
                        if let Some(original_values_map) = original_values
                            && let Some(original_value) = original_values_map.get(&identifier)
                        {
                            // Return the original value since we can't reconstruct these types
                            return Ok(original_value.clone());
                        }
                        // If no original value found, keep as string
                        // This will likely cause a config error, but that's the expected behavior
                        // since the user modified something that can't be properly converted
                    }
                    NuValueType::Glob => {
                        return Ok(nu_protocol::Value::glob(s.clone(), false, span));
                    }
                    _ => {}
                }
            }
            nu_protocol::Value::string(s.clone(), span)
        }
        Value::Array(arr) => {
            // Check if this was originally binary data
            if let Some(NuValueType::Binary) = original_type {
                let bytes: Result<Vec<u8>, _> = arr
                    .iter()
                    .map(|v| {
                        v.as_i64()
                            .and_then(|i| u8::try_from(i).ok())
                            .ok_or("Invalid byte value")
                    })
                    .collect();
                if let Ok(bytes) = bytes {
                    return Ok(nu_protocol::Value::binary(bytes, span));
                }
            }

            // Check if this was originally a CellPath
            if let Some(NuValueType::CellPath) = original_type {
                use nu_protocol::ast::PathMember;
                use nu_protocol::casing::Casing;
                let members: Result<Vec<PathMember>, _> = arr
                    .iter()
                    .map(|v| match v {
                        Value::String(s) => Ok(PathMember::String {
                            val: s.clone(),
                            span,
                            optional: false,
                            casing: Casing::Sensitive,
                        }),
                        Value::Number(n) => {
                            if let Some(i) = n.as_u64() {
                                Ok(PathMember::Int {
                                    val: i as usize,
                                    span,
                                    optional: false,
                                })
                            } else {
                                Err("Invalid cell path member")
                            }
                        }
                        _ => Err("Invalid cell path member"),
                    })
                    .collect();
                if let Ok(members) = members {
                    return Ok(nu_protocol::Value::cell_path(
                        nu_protocol::ast::CellPath { members },
                        span,
                    ));
                }
            }

            // Regular array/list
            let values: Result<Vec<_>, _> = arr
                .iter()
                .enumerate()
                .map(|(idx, v)| {
                    let mut path = current_path.clone();
                    path.push(idx.to_string());
                    json_to_nu_value_with_types(v, span, type_map, original_values, path)
                })
                .collect();
            nu_protocol::Value::list(values?, span)
        }
        Value::Object(obj) => {
            let mut record = nu_protocol::Record::new();
            for (k, v) in obj {
                let mut path = current_path.clone();
                path.push(k.clone());
                record.push(
                    k.clone(),
                    json_to_nu_value_with_types(v, span, type_map, original_values, path)?,
                );
            }
            nu_protocol::Value::record(record, span)
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use nu_protocol::Span;

    fn test_span() -> Span {
        Span::test_data()
    }

    #[test]
    fn test_duration_roundtrip() {
        // Create a type map with a duration type
        let mut type_map = HashMap::new();
        type_map.insert("timeout".to_string(), NuValueType::Duration);
        let type_map = Some(type_map);

        // Create JSON with a number that should be converted to duration
        let json = serde_json::json!({
            "timeout": 5000000000_i64  // 5 seconds in nanoseconds
        });

        let result =
            json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap();

        // Check that it's a record with a duration value
        if let nu_protocol::Value::Record { val, .. } = result {
            let timeout = val.get("timeout").expect("timeout field should exist");
            assert!(
                matches!(timeout, nu_protocol::Value::Duration { .. }),
                "Expected Duration, got {:?}",
                timeout
            );
            if let nu_protocol::Value::Duration { val, .. } = timeout {
                assert_eq!(*val, 5000000000);
            }
        } else {
            panic!("Expected Record, got {:?}", result);
        }
    }

    #[test]
    fn test_filesize_roundtrip() {
        let mut type_map = HashMap::new();
        type_map.insert("size".to_string(), NuValueType::Filesize);
        let type_map = Some(type_map);

        let json = serde_json::json!({
            "size": 1048576_i64  // 1 MiB in bytes
        });

        let result =
            json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap();

        if let nu_protocol::Value::Record { val, .. } = result {
            let size = val.get("size").expect("size field should exist");
            assert!(
                matches!(size, nu_protocol::Value::Filesize { .. }),
                "Expected Filesize, got {:?}",
                size
            );
        } else {
            panic!("Expected Record, got {:?}", result);
        }
    }

    #[test]
    fn test_nested_duration() {
        let mut type_map = HashMap::new();
        type_map.insert(
            "plugin_gc.default.stop_after".to_string(),
            NuValueType::Duration,
        );
        let type_map = Some(type_map);

        let json = serde_json::json!({
            "plugin_gc": {
                "default": {
                    "stop_after": 0_i64
                }
            }
        });

        let result =
            json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap();

        // Navigate to the nested value
        if let nu_protocol::Value::Record { val: outer, .. } = result {
            let plugin_gc = outer.get("plugin_gc").expect("plugin_gc should exist");
            if let nu_protocol::Value::Record { val: inner, .. } = plugin_gc {
                let default = inner.get("default").expect("default should exist");
                if let nu_protocol::Value::Record {
                    val: default_rec, ..
                } = default
                {
                    let stop_after = default_rec
                        .get("stop_after")
                        .expect("stop_after should exist");
                    assert!(
                        matches!(stop_after, nu_protocol::Value::Duration { .. }),
                        "Expected Duration, got {:?}",
                        stop_after
                    );
                } else {
                    panic!("Expected Record for default");
                }
            } else {
                panic!("Expected Record for plugin_gc");
            }
        } else {
            panic!("Expected Record");
        }
    }

    #[test]
    fn test_closure_restored_from_original() {
        // Create a type map marking this as a closure
        let mut type_map = HashMap::new();
        type_map.insert("hook".to_string(), NuValueType::Closure);
        let type_map = Some(type_map);

        // Create an original value map with the closure
        let mut original_values = HashMap::new();
        // We can't easily create a real closure in tests, so we'll test the path exists
        // In practice, the original closure value would be stored here

        let json = serde_json::json!({
            "hook": "{|| print 'hello'}"
        });

        // Without original value, it stays as string
        let result = json_to_nu_value_with_types(
            &json,
            test_span(),
            &type_map,
            &Some(original_values.clone()),
            Vec::new(),
        )
        .unwrap();

        if let nu_protocol::Value::Record { val, .. } = result {
            let hook = val.get("hook").expect("hook field should exist");
            // Without an original value stored, it remains a string
            assert!(
                matches!(hook, nu_protocol::Value::String { .. }),
                "Expected String when no original closure available, got {:?}",
                hook
            );
        } else {
            panic!("Expected Record");
        }

        // Now test with an original value stored (using a simple value as stand-in)
        // In real usage, this would be the actual Closure value
        original_values.insert(
            "hook".to_string(),
            nu_protocol::Value::string("original_closure_placeholder", test_span()),
        );

        let result = json_to_nu_value_with_types(
            &json,
            test_span(),
            &type_map,
            &Some(original_values),
            Vec::new(),
        )
        .unwrap();

        if let nu_protocol::Value::Record { val, .. } = result {
            let hook = val.get("hook").expect("hook field should exist");
            // With original value stored, it should return that value
            if let nu_protocol::Value::String { val: s, .. } = hook {
                assert_eq!(s, "original_closure_placeholder");
            } else {
                panic!("Expected the original value to be returned");
            }
        } else {
            panic!("Expected Record");
        }
    }

    #[test]
    fn test_glob_roundtrip() {
        let mut type_map = HashMap::new();
        type_map.insert("pattern".to_string(), NuValueType::Glob);
        let type_map = Some(type_map);

        let json = serde_json::json!({
            "pattern": "*.txt"
        });

        let result =
            json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap();

        if let nu_protocol::Value::Record { val, .. } = result {
            let pattern = val.get("pattern").expect("pattern field should exist");
            assert!(
                matches!(pattern, nu_protocol::Value::Glob { .. }),
                "Expected Glob, got {:?}",
                pattern
            );
        } else {
            panic!("Expected Record");
        }
    }

    #[test]
    fn test_binary_roundtrip() {
        let mut type_map = HashMap::new();
        type_map.insert("data".to_string(), NuValueType::Binary);
        let type_map = Some(type_map);

        let json = serde_json::json!({
            "data": [0, 1, 2, 255]
        });

        let result =
            json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap();

        if let nu_protocol::Value::Record { val, .. } = result {
            let data = val.get("data").expect("data field should exist");
            assert!(
                matches!(data, nu_protocol::Value::Binary { .. }),
                "Expected Binary, got {:?}",
                data
            );
            if let nu_protocol::Value::Binary { val, .. } = data {
                assert_eq!(val, &vec![0u8, 1, 2, 255]);
            }
        } else {
            panic!("Expected Record");
        }
    }

    #[test]
    fn test_list_with_typed_elements() {
        let mut type_map = HashMap::new();
        type_map.insert("timeouts[0]".to_string(), NuValueType::Duration);
        type_map.insert("timeouts[1]".to_string(), NuValueType::Duration);
        let type_map = Some(type_map);

        let json = serde_json::json!({
            "timeouts": [1000000000_i64, 2000000000_i64]
        });

        let result =
            json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap();

        if let nu_protocol::Value::Record { val, .. } = result {
            let timeouts = val.get("timeouts").expect("timeouts field should exist");
            if let nu_protocol::Value::List { vals, .. } = timeouts {
                assert_eq!(vals.len(), 2);
                for (i, v) in vals.iter().enumerate() {
                    assert!(
                        matches!(v, nu_protocol::Value::Duration { .. }),
                        "Expected Duration at index {}, got {:?}",
                        i,
                        v
                    );
                }
            } else {
                panic!("Expected List");
            }
        } else {
            panic!("Expected Record");
        }
    }

    #[test]
    fn test_without_type_map_uses_defaults() {
        // Without a type map, numbers stay as numbers, strings as strings
        let json = serde_json::json!({
            "timeout": 5000000000_i64,
            "name": "test"
        });

        let result =
            json_to_nu_value_with_types(&json, test_span(), &None, &None, Vec::new()).unwrap();

        if let nu_protocol::Value::Record { val, .. } = result {
            let timeout = val.get("timeout").expect("timeout field should exist");
            assert!(
                matches!(timeout, nu_protocol::Value::Int { .. }),
                "Expected Int without type map, got {:?}",
                timeout
            );
            let name = val.get("name").expect("name field should exist");
            assert!(
                matches!(name, nu_protocol::Value::String { .. }),
                "Expected String, got {:?}",
                name
            );
        } else {
            panic!("Expected Record");
        }
    }

    #[test]
    fn test_path_to_identifier() {
        assert_eq!(path_to_identifier(&[]), "");
        assert_eq!(path_to_identifier(&["foo".to_string()]), "foo");
        assert_eq!(
            path_to_identifier(&["foo".to_string(), "bar".to_string()]),
            "foo.bar"
        );
        assert_eq!(
            path_to_identifier(&["foo".to_string(), "0".to_string()]),
            "foo[0]"
        );
        assert_eq!(
            path_to_identifier(&["foo".to_string(), "0".to_string(), "bar".to_string()]),
            "foo[0].bar"
        );
    }

    #[test]
    fn test_build_nu_type_map() {
        let span = test_span();

        // Create a nested Nu value structure
        let mut inner_record = nu_protocol::Record::new();
        inner_record.push(
            "stop_after".to_string(),
            nu_protocol::Value::duration(0, span),
        );

        let mut outer_record = nu_protocol::Record::new();
        outer_record.push(
            "default".to_string(),
            nu_protocol::Value::record(inner_record, span),
        );

        let mut root_record = nu_protocol::Record::new();
        root_record.push(
            "plugin_gc".to_string(),
            nu_protocol::Value::record(outer_record, span),
        );

        let root_value = nu_protocol::Value::record(root_record, span);

        let mut type_map = HashMap::new();
        build_nu_type_map(&root_value, Vec::new(), &mut type_map);

        assert_eq!(type_map.get("plugin_gc"), Some(&NuValueType::Record));
        assert_eq!(
            type_map.get("plugin_gc.default"),
            Some(&NuValueType::Record)
        );
        assert_eq!(
            type_map.get("plugin_gc.default.stop_after"),
            Some(&NuValueType::Duration)
        );
    }

    #[test]
    fn test_build_original_value_map() {
        let span = test_span();

        // Create a structure with a duration (which can be roundtripped) and simulate
        // what would happen with non-roundtrippable types
        let mut record = nu_protocol::Record::new();
        record.push(
            "duration".to_string(),
            nu_protocol::Value::duration(0, span),
        );
        record.push(
            "string".to_string(),
            nu_protocol::Value::string("test", span),
        );

        let root_value = nu_protocol::Value::record(record, span);

        let mut value_map = HashMap::new();
        build_original_value_map(&root_value, Vec::new(), &mut value_map);

        // Duration and String are roundtrippable, so they shouldn't be in the map
        assert!(!value_map.contains_key("duration"));
        assert!(!value_map.contains_key("string"));
    }
}