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
use nu_errors::ShellError;
use nu_protocol::{SpannedTypeName, TaggedDictBuilder, UntaggedValue, Value};
use nu_source::Tag;

use crate::utils::group;

#[allow(clippy::type_complexity)]
pub fn split(
    value: &Value,
    splitter: &Option<Box<dyn Fn(usize, &Value) -> Result<String, ShellError> + Send>>,
    tag: impl Into<Tag>,
) -> Result<Value, ShellError> {
    let tag = tag.into();

    let mut splits = indexmap::IndexMap::new();
    let mut out = TaggedDictBuilder::new(&tag);

    if splitter.is_none() {
        out.insert_untagged("table", value.clone());
        return Ok(out.into_value());
    }

    for (column, value) in value.row_entries() {
        if !&value.is_table() {
            return Err(ShellError::type_error(
                "a table value",
                value.spanned_type_name(),
            ));
        }

        match group(&value, splitter, &tag) {
            Ok(grouped) => {
                for (split_label, subset) in grouped.row_entries() {
                    let s = splits
                        .entry(split_label.clone())
                        .or_insert(indexmap::IndexMap::new());

                    if !&subset.is_table() {
                        return Err(ShellError::type_error(
                            "a table value",
                            subset.spanned_type_name(),
                        ));
                    }

                    s.insert(column.clone(), subset.clone());
                }
            }
            Err(err) => return Err(err),
        }
    }

    let mut out = TaggedDictBuilder::new(&tag);

    for (k, v) in splits.into_iter() {
        out.insert_untagged(k, UntaggedValue::row(v));
    }

    Ok(out.into_value())
}