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
use nu_color_config::TextStyle;
use nu_engine::column::get_columns;
use nu_protocol::{ast::PathMember, Config, ShellError, Span, TableIndexMode, Value};

use crate::{
    clean_charset,
    common::{
        create_nu_table_config, get_empty_style, get_header_style, get_index_style,
        get_value_style, NuText, INDEX_COLUMN_NAME,
    },
    NuTable, NuTableCell, StringResult, TableOpts, TableOutput, TableResult,
};

pub struct JustTable;

impl JustTable {
    pub fn table(input: &[Value], opts: TableOpts<'_>) -> StringResult {
        create_table(input, opts)
    }

    pub fn kv_table(cols: &[String], vals: &[Value], opts: TableOpts<'_>) -> StringResult {
        kv_table(cols, vals, opts)
    }
}

fn create_table(input: &[Value], opts: TableOpts<'_>) -> Result<Option<String>, ShellError> {
    match table(input, opts.row_offset, opts.clone())? {
        Some(mut out) => {
            let left = opts.config.table_indent.left;
            let right = opts.config.table_indent.right;
            out.table.set_indent(left, right);

            let table_config =
                create_nu_table_config(opts.config, opts.style_computer, &out, false);
            Ok(out.table.draw(table_config, opts.width))
        }
        None => Ok(None),
    }
}

fn kv_table(cols: &[String], vals: &[Value], opts: TableOpts<'_>) -> StringResult {
    let mut data = vec![Vec::with_capacity(2); cols.len()];
    for ((column, value), row) in cols.iter().zip(vals.iter()).zip(data.iter_mut()) {
        if nu_utils::ctrl_c::was_pressed(&opts.ctrlc) {
            return Ok(None);
        }

        let is_string_value = matches!(value, Value::String { .. });
        let mut value = value.into_abbreviated_string(opts.config);
        if is_string_value {
            value = clean_charset(&value);
        }

        let key = NuTableCell::new(column.to_string());
        let value = NuTableCell::new(value);
        row.push(key);
        row.push(value);
    }

    let mut table = NuTable::from(data);
    table.set_index_style(TextStyle::default_field());

    let mut out = TableOutput::new(table, false, true);

    let left = opts.config.table_indent.left;
    let right = opts.config.table_indent.right;
    out.table.set_indent(left, right);

    let table_config = create_nu_table_config(opts.config, opts.style_computer, &out, false);
    let table = out.table.draw(table_config, opts.width);

    Ok(table)
}

fn table(input: &[Value], row_offset: usize, opts: TableOpts<'_>) -> TableResult {
    if input.is_empty() {
        return Ok(None);
    }

    let mut headers = get_columns(input);
    let with_index = match opts.config.table_index_mode {
        TableIndexMode::Always => true,
        TableIndexMode::Never => false,
        TableIndexMode::Auto => headers.iter().any(|header| header == INDEX_COLUMN_NAME),
    };

    let with_header = !headers.is_empty();
    if !with_header {
        let table = to_table_with_no_header(input, with_index, row_offset, opts)?;
        let table = table.map(|table| TableOutput::new(table, false, with_index));
        return Ok(table);
    }

    if with_header && with_index {
        headers.insert(0, "#".into());
    }

    // The header with the INDEX is removed from the table headers since
    // it is added to the natural table index
    let headers: Vec<_> = headers
        .into_iter()
        .filter(|header| header != INDEX_COLUMN_NAME)
        .collect();

    let table = to_table_with_header(input, headers, with_index, row_offset, opts)?;
    let table = table.map(|table| TableOutput::new(table, true, with_index));

    Ok(table)
}

fn to_table_with_header(
    input: &[Value],
    headers: Vec<String>,
    with_index: bool,
    row_offset: usize,
    opts: TableOpts<'_>,
) -> Result<Option<NuTable>, ShellError> {
    let count_rows = input.len() + 1;
    let count_columns = headers.len();
    let mut table = NuTable::new(count_rows, count_columns);
    table.set_header_style(get_header_style(opts.style_computer));
    table.set_index_style(get_index_style(opts.style_computer));

    for (i, text) in headers.iter().enumerate() {
        table.insert((0, i), text.to_owned());
    }

    for (row, item) in input.iter().enumerate() {
        if nu_utils::ctrl_c::was_pressed(&opts.ctrlc) {
            return Ok(None);
        }

        if let Value::Error { error } = item {
            return Err(*error.clone());
        }

        if with_index {
            let text = get_table_row_index(item, opts.config, row, row_offset);
            table.insert((row + 1, 0), text);
        }

        let skip_index = usize::from(with_index);
        for (col, header) in headers.iter().enumerate().skip(skip_index) {
            let (text, style) = get_string_value_with_header(item, header, &opts);

            table.insert((row + 1, col), text);
            table.insert_style((row + 1, col), style);
        }
    }

    Ok(Some(table))
}

fn to_table_with_no_header(
    input: &[Value],
    with_index: bool,
    row_offset: usize,
    opts: TableOpts<'_>,
) -> Result<Option<NuTable>, ShellError> {
    let mut table = NuTable::new(input.len(), with_index as usize + 1);
    table.set_index_style(get_index_style(opts.style_computer));

    for (row, item) in input.iter().enumerate() {
        if nu_utils::ctrl_c::was_pressed(&opts.ctrlc) {
            return Ok(None);
        }

        if let Value::Error { error } = item {
            return Err(*error.clone());
        }

        if with_index {
            let text = get_table_row_index(item, opts.config, row, row_offset);
            table.insert((row, 0), text);
        }

        let (text, style) = get_string_value(item, &opts);

        let pos = (row, with_index as usize);
        table.insert(pos, text);
        table.insert_style(pos, style);
    }

    Ok(Some(table))
}

fn get_string_value_with_header(item: &Value, header: &str, opts: &TableOpts) -> NuText {
    match item {
        Value::Record { .. } => {
            let path = PathMember::String {
                val: header.to_owned(),
                span: Span::unknown(),
                optional: false,
            };
            let value = item.clone().follow_cell_path(&[path], false);

            match value {
                Ok(value) => get_string_value(&value, opts),
                Err(_) => get_empty_style(opts.style_computer),
            }
        }
        value => get_string_value(value, opts),
    }
}

fn get_string_value(item: &Value, opts: &TableOpts) -> NuText {
    let (mut text, style) = get_value_style(item, opts.config, opts.style_computer);
    let is_string_value = matches!(item, Value::String { .. });
    if is_string_value {
        text = clean_charset(&text);
    }

    (text, style)
}

fn get_table_row_index(item: &Value, config: &Config, row: usize, offset: usize) -> String {
    match item {
        Value::Record { .. } => item
            .get_data_by_key(INDEX_COLUMN_NAME)
            .map(|value| value.into_string("", config))
            .unwrap_or_else(|| (row + offset).to_string()),
        _ => (row + offset).to_string(),
    }
}