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
use super::helper::ReconstructVal;
use crate::{record, Config, ShellError, Span, Value};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default)]
pub enum TableMode {
    Basic,
    Thin,
    Light,
    Compact,
    WithLove,
    CompactDouble,
    #[default]
    Rounded,
    Reinforced,
    Heavy,
    None,
    Psql,
    Markdown,
    Dots,
    Restructured,
    AsciiRounded,
    BasicCompact,
}

impl FromStr for TableMode {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "basic" => Ok(Self::Basic),
            "thin" => Ok(Self::Thin),
            "light" => Ok(Self::Light),
            "compact" => Ok(Self::Compact),
            "with_love" => Ok(Self::WithLove),
            "compact_double" => Ok(Self::CompactDouble),
            "default" => Ok(TableMode::default()),
            "rounded" => Ok(Self::Rounded),
            "reinforced" => Ok(Self::Reinforced),
            "heavy" => Ok(Self::Heavy),
            "none" => Ok(Self::None),
            "psql" => Ok(Self::Psql),
            "markdown" => Ok(Self::Markdown),
            "dots" => Ok(Self::Dots),
            "restructured" => Ok(Self::Restructured),
            "ascii_rounded" => Ok(Self::AsciiRounded),
            "basic_compact" => Ok(Self::BasicCompact),
            _ => Err("expected either 'basic', 'thin', 'light', 'compact', 'with_love', 'compact_double', 'rounded', 'reinforced', 'heavy', 'none', 'psql', 'markdown', 'dots', 'restructured', 'ascii_rounded', or 'basic_compact'"),
        }
    }
}

impl ReconstructVal for TableMode {
    fn reconstruct_value(&self, span: Span) -> Value {
        Value::string(
            match self {
                TableMode::Basic => "basic",
                TableMode::Thin => "thin",
                TableMode::Light => "light",
                TableMode::Compact => "compact",
                TableMode::WithLove => "with_love",
                TableMode::CompactDouble => "compact_double",
                TableMode::Rounded => "rounded",
                TableMode::Reinforced => "reinforced",
                TableMode::Heavy => "heavy",
                TableMode::None => "none",
                TableMode::Psql => "psql",
                TableMode::Markdown => "markdown",
                TableMode::Dots => "dots",
                TableMode::Restructured => "restructured",
                TableMode::AsciiRounded => "ascii_rounded",
                TableMode::BasicCompact => "basic_compact",
            },
            span,
        )
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum FooterMode {
    /// Never show the footer
    Never,
    /// Always show the footer
    Always,
    /// Only show the footer if there are more than RowCount rows
    RowCount(u64),
    /// Calculate the screen height, calculate row count, if display will be bigger than screen, add the footer
    Auto,
}

impl FromStr for FooterMode {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "always" => Ok(FooterMode::Always),
            "never" => Ok(FooterMode::Never),
            "auto" => Ok(FooterMode::Auto),
            x => {
                if let Ok(count) = x.parse() {
                    Ok(FooterMode::RowCount(count))
                } else {
                    Err("expected either 'never', 'always', 'auto' or a row count")
                }
            }
        }
    }
}

impl ReconstructVal for FooterMode {
    fn reconstruct_value(&self, span: Span) -> Value {
        Value::string(
            match self {
                FooterMode::Always => "always".to_string(),
                FooterMode::Never => "never".to_string(),
                FooterMode::Auto => "auto".to_string(),
                FooterMode::RowCount(c) => c.to_string(),
            },
            span,
        )
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum TableIndexMode {
    /// Always show indexes
    Always,
    /// Never show indexes
    Never,
    /// Show indexes when a table has "index" column
    Auto,
}

impl FromStr for TableIndexMode {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "always" => Ok(TableIndexMode::Always),
            "never" => Ok(TableIndexMode::Never),
            "auto" => Ok(TableIndexMode::Auto),
            _ => Err("expected either 'never', 'always' or 'auto'"),
        }
    }
}

impl ReconstructVal for TableIndexMode {
    fn reconstruct_value(&self, span: Span) -> Value {
        Value::string(
            match self {
                TableIndexMode::Always => "always",
                TableIndexMode::Never => "never",
                TableIndexMode::Auto => "auto",
            },
            span,
        )
    }
}

/// A Table view configuration, for a situation where
/// we need to limit cell width in order to adjust for a terminal size.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum TrimStrategy {
    /// Wrapping strategy.
    ///
    /// It it's similar to original nu_table, strategy.
    Wrap {
        /// A flag which indicates whether is it necessary to try
        /// to keep word boundaries.
        try_to_keep_words: bool,
    },
    /// Truncating strategy, where we just cut the string.
    /// And append the suffix if applicable.
    Truncate {
        /// Suffix which can be appended to a truncated string after being cut.
        ///
        /// It will be applied only when there's enough room for it.
        /// For example in case where a cell width must be 12 chars, but
        /// the suffix takes 13 chars it won't be used.
        suffix: Option<String>,
    },
}

impl TrimStrategy {
    pub fn wrap(dont_split_words: bool) -> Self {
        Self::Wrap {
            try_to_keep_words: dont_split_words,
        }
    }

    pub fn truncate(suffix: Option<String>) -> Self {
        Self::Truncate { suffix }
    }
}

impl Default for TrimStrategy {
    fn default() -> Self {
        TrimStrategy::Wrap {
            try_to_keep_words: true,
        }
    }
}

pub(super) fn try_parse_trim_strategy(
    value: &Value,
    errors: &mut Vec<ShellError>,
) -> Result<TrimStrategy, ShellError> {
    let map = value.as_record().map_err(|e| ShellError::GenericError {
        error: "Error while applying config changes".into(),
        msg: "$env.config.table.trim is not a record".into(),
        span: Some(value.span()),
        help: Some("Please consult the documentation for configuring Nushell.".into()),
        inner: vec![e],
    })?;

    let mut methodology = match map.get("methodology") {
        Some(value) => match try_parse_trim_methodology(value) {
            Some(methodology) => methodology,
            None => return Ok(TrimStrategy::default()),
        },
        None => {
            errors.push(ShellError::GenericError {
                error: "Error while applying config changes".into(),
                msg: "$env.config.table.trim.methodology was not provided".into(),
                span: Some(value.span()),
                help: Some("Please consult the documentation for configuring Nushell.".into()),
                inner: vec![],
            });
            return Ok(TrimStrategy::default());
        }
    };

    match &mut methodology {
        TrimStrategy::Wrap { try_to_keep_words } => {
            if let Some(value) = map.get("wrapping_try_keep_words") {
                if let Ok(b) = value.as_bool() {
                    *try_to_keep_words = b;
                } else {
                    errors.push(ShellError::GenericError {
                        error: "Error while applying config changes".into(),
                        msg: "$env.config.table.trim.wrapping_try_keep_words is not a bool".into(),
                        span: Some(value.span()),
                        help: Some(
                            "Please consult the documentation for configuring Nushell.".into(),
                        ),
                        inner: vec![],
                    });
                }
            }
        }
        TrimStrategy::Truncate { suffix } => {
            if let Some(value) = map.get("truncating_suffix") {
                if let Ok(v) = value.coerce_string() {
                    *suffix = Some(v);
                } else {
                    errors.push(ShellError::GenericError {
                        error: "Error while applying config changes".into(),
                        msg: "$env.config.table.trim.truncating_suffix is not a string".into(),
                        span: Some(value.span()),
                        help: Some(
                            "Please consult the documentation for configuring Nushell.".into(),
                        ),
                        inner: vec![],
                    });
                }
            }
        }
    }

    Ok(methodology)
}

fn try_parse_trim_methodology(value: &Value) -> Option<TrimStrategy> {
    if let Ok(value) = value.coerce_str() {
        match value.to_lowercase().as_str() {
        "wrapping" => {
            return Some(TrimStrategy::Wrap {
                try_to_keep_words: false,
            });
        }
        "truncating" => return Some(TrimStrategy::Truncate { suffix: None }),
        _ => eprintln!("unrecognized $config.table.trim.methodology value; expected either 'truncating' or 'wrapping'"),
    }
    } else {
        eprintln!("$env.config.table.trim.methodology is not a string")
    }

    None
}

pub(super) fn reconstruct_trim_strategy(config: &Config, span: Span) -> Value {
    match &config.trim_strategy {
        TrimStrategy::Wrap { try_to_keep_words } => Value::record(
            record! {
                "methodology" => Value::string("wrapping", span),
                "wrapping_try_keep_words" => Value::bool(*try_to_keep_words, span),
            },
            span,
        ),
        TrimStrategy::Truncate { suffix } => Value::record(
            match suffix {
                Some(s) => record! {
                    "methodology" => Value::string("truncating", span),
                    "truncating_suffix" => Value::string(s.clone(), span),
                },
                None => record! {
                    "methodology" => Value::string("truncating", span),
                    "truncating_suffix" => Value::nothing(span),
                },
            },
            span,
        ),
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TableIndent {
    pub left: usize,
    pub right: usize,
}

pub(super) fn reconstruct_padding(config: &Config, span: Span) -> Value {
    // For better completions always reconstruct the record version even though unsigned int would
    // be supported, `as` conversion is sane as it came from an i64 original
    Value::record(
        record!(
            "left" => Value::int(config.table_indent.left as i64, span),
            "right" => Value::int(config.table_indent.right as i64, span),
        ),
        span,
    )
}