spreadsheet_to_json/
options.rs

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
use serde_json::{json, Error, Value};
use crate::headers::*;
use std::{path::Path, str::FromStr, sync::Arc};
/// default max number of rows without an override via ->max_row_count(max_row_count)
pub const DEFAULT_MAX_ROWS: usize = 10_000;

/// Row parsing options with nested column options
#[derive(Debug, Clone, Default)]
pub struct RowOptionSet {
  pub euro_number_format: bool, // always parse as euro number format
  pub date_only: bool,
  pub columns: Vec<Column>,
}

impl RowOptionSet {
  pub fn column(&self, index: usize) -> Option<&Column> {
    self.columns.get(index)
  }
}

/// Core options with nested row options
#[derive(Debug, Clone, Default)]
pub struct OptionSet {
  pub sheet: Option<String>, // Optional sheet name reference. Will default to index value if not matched
  pub index: u32, // worksheet index
  pub path: Option<String>, // path argument. If None, do not attempt to parse
  pub rows: RowOptionSet,
  pub jsonl: bool,
  pub max: Option<u32>,
  pub omit_header: bool,
  pub header_row: u8,
  pub read_mode: ReadMode,
}

impl OptionSet {
  /// Instantiates a new option set with a path string for file operations.
  pub fn new(path_str: &str) -> Self {
    OptionSet {
      sheet: None,
      index: 0,
      path: Some(path_str.to_string()),
      rows: RowOptionSet::default(),
      jsonl: false,
      max: None,
      omit_header: false,
      header_row: 0,
      read_mode: ReadMode::Sync,
    }
}


  /// Sets the sheet name for the operation.
  pub fn sheet_name(&mut self, name: String) -> &mut Self {
      self.sheet = Some(name);
      self
  }

  /// Sets the sheet index.
  pub fn sheet_index(&mut self, index: u32) -> &mut Self {
      self.index = index;
      self
  }
  /// Sets JSON Lines mode to true.
  pub fn json_lines(&mut self) -> &mut Self {
      self.jsonl = true;
      self
  }

  /// Omits the header when reading.
  pub fn omit_header(&mut self) -> &mut Self {
      self.omit_header = true;
      self
  }

  /// Sets the header row number.
  pub fn header_row(&mut self, row: u8) -> &mut Self {
      self.header_row = row;
      self
  }

  /// Sets the maximum number of rows to read.
  pub fn max_row_count(&mut self, max: u32) -> &mut Self {
      self.max = Some(max);
      self
  }

  /// Sets the read mode to asynchronous.
  pub fn read_mode_async(&mut self) -> &mut Self {
      self.read_mode = ReadMode::Async;
      self
  }

   pub fn to_json(&self) -> Value {
    json!({
      "sheet": {
        "key": self.sheet.clone().unwrap_or("".to_string()),
        "index": self.index,
      },
      "path": self.path.clone().unwrap_or("".to_string()),
      "euro_number_format": self.rows.euro_number_format,
      "date_only": self.rows.date_only,
      "columns": self.rows.columns.clone().into_iter().map(|c| c.to_json()).collect::<Vec<Value>>(),
      "max": self.max.unwrap_or(0),
      "header_row": self.header_row,
      "omit_header": self.omit_header,
      "jsonl": self.jsonl
    })
  }

  
  /// header row index as usize
  pub fn header_row_index(&self) -> usize {
    self.header_row as usize
  }

  /// set the maximum of rows to be output synchronously
  pub fn max_rows(&self) -> usize {
    if self.read_mode == ReadMode::PreviewAsync {
      return 20
    }
    if let Some(mr) = self.max {
      mr as usize
    } else {
      DEFAULT_MAX_ROWS
    }
  }

  /// future development with advanced column options
  #[allow(dead_code)]
  pub fn columns(&self) -> Vec<Column> {
    self.rows.columns.clone()
  }

  /// cloned read mode
  pub fn read_mode(&self) -> ReadMode {
    self.read_mode.clone()
  }

  /// Needs full data set to processed later
  pub fn is_async(&self) -> bool {
    self.read_mode.is_async()
  }

  // Should rows be captured synchronously
  pub fn capture_rows(&self) -> bool {
    match self.read_mode {
      ReadMode::Async => false,
      _ => true
    }
  }
}


/// Cell format overrides
#[derive(Debug, Clone)]
pub enum Format {
  Auto, // automatic interpretation
  Text, // text
  Integer, // integer only
  Decimal(u8), // decimal to stated precision
  Boolean, // Boolean or  cast to boolean from integers
  Date, // Interpret as date only
  DateTime, // Interpret as full datetime
  Truthy, // interpret common yes/no, y/n, true/false text strings as true/false
  #[allow(dead_code)]
  TruthyCustom(Arc<str>, Arc<str>) // define custom yes/no values
}

impl ToString for Format {
  fn to_string(&self) -> String {
    let result = match self {
      Self::Auto => "auto",
      Self::Text => "text",
      Self::Integer => "integer",
      Self::Decimal(n) => &format!("decimal({})", n),
      Self::Boolean => "boolean",
      Self::Date => "date",
      Self::DateTime => "datetime",
      Self::Truthy => "truthy",
      Self::TruthyCustom(yes, no) => &format!("truthy({},{})", yes, no),
    };
    result.to_string() 
  }
}

impl FromStr for Format {
  type Err = Error;
  fn from_str(key: &str) -> Result<Self, Self::Err> {
      let fmt = match key {
        "s" | "str" | "string" | "t" | "txt" | "text" => Self::Text,
        "i" | "int" | "integer" => Self::Integer,
        "d1" | "decimal_1" => Self::Decimal(1),
        "d2" | "decimal_2" => Self::Decimal(2),
        "d3" | "decimal_3" => Self::Decimal(3),
        "d4" | "decimal_4" => Self::Decimal(4),
        "d5" | "decimal_5" => Self::Decimal(5),
        "d6" | "decimal_6" => Self::Decimal(6),
        "b" | "bool" | "boolean" => Self::Boolean,
        "da" | "date" => Self::Date,
        "dt" | "datetime" => Self::DateTime,
        "tr" | "truthy" => Self::Truthy,
        _ => Self::Auto,
      };
      Ok(fmt)
  }
}

impl Format {
  #[allow(dead_code)]
  pub fn truthy_custom(yes: &str, no: &str) -> Self {
    Format::TruthyCustom(Arc::from(yes), Arc::from(no))
  }
}

#[derive(Debug, Clone)]
pub struct Column {
  pub key:  Arc<str>,
  pub format: Format,
  pub default: Option<Value>,
  pub date_only: bool, // date only in Format::Auto mode with datetime objects
  pub euro_number_format: bool, // parse as euro number format
}

impl Column {

  /// build from core options and sheet index only
  pub fn from_key_index(key_opt: Option<&str>, index: usize) -> Self {
    Self::from_key_ref_with_format(key_opt, index, Format::Auto, None, false, false)
  }

  // future development with column options
  #[allow(dead_code)]
  pub fn from_key_custom(key_opt: Option<&str>, index: usize, date_only: bool, euro_number_format: bool) -> Self {
    Self::from_key_ref_with_format(key_opt, index, Format::Auto, None, date_only, euro_number_format)
  }

  pub fn from_key_ref_with_format(key_opt: Option<&str>, index: usize, format: Format, default: Option<Value>, date_only: bool, euro_number_format: bool) -> Self {
    let key = key_opt.map(Arc::from).unwrap_or_else(|| Arc::from(to_head_key(index)));
    Column {
      key,
      format,
      default,
      date_only,
      euro_number_format
    }
  }

  pub fn to_json(&self) -> Value {
    json!({
      "key": self.key.to_string(),
      "format": self.format.to_string(),
      "date_only": self.date_only,
      "euro_number_format": self.euro_number_format,
      "default": self.default
    })
  }

}


/// Match on permitted file types identified by file extensions
/// Unmatched means do not process
#[derive(Debug, Clone, Copy)]
pub enum Extension {
  Unmatched,
  Ods,
  Xlsx,
  Xls,
  Csv,
  Tsv,
}

impl Extension {
  pub fn from_path(path:&Path) -> Extension {
    if let Some(ext) = path.extension() {
      if let Some(ext_str) = ext.to_str() {
        let ext_lc = ext_str.to_lowercase();
        return match  ext_lc.as_str() {
          "ods" => Extension::Ods,
          "xlsx" => Extension::Xlsx,
          "xls" => Extension::Xls,
          "csv" => Extension::Csv,
          "tsv" => Extension::Tsv,
          _ => Extension::Unmatched
        }
      }
    }
    Extension::Unmatched
  }

  /// use the Calamine library
  pub fn use_calamine(&self) -> bool {
    match self {
      Self::Ods | Self::Xlsx | Self::Xls => true,
      _ => false
    }
  }
  
  /// added for future development
  /// Process a simple CSV or TSV
  #[allow(dead_code)]
  pub fn use_csv(&self) -> bool {
    match self {
      Self::Csv | Self::Tsv => true,
      _ => false
    }
  }

}

impl ToString for Extension {
  fn to_string(&self) -> String {
    match self {
      Self::Ods => "ods",
      Self::Xlsx => "xlsx",
      Self::Xls => "xls",
      Self::Csv => "csv",
      Self::Tsv => "tsv",
      _ => ""
    }.to_string()
  }
}

pub struct PathData<'a> {
  path: &'a Path,
  ext: Extension
}

impl<'a> PathData<'a> {
  pub fn new(path: &'a Path) -> Self {
    PathData {
      path,
      ext: Extension::from_path(path)
    }
  }

  pub fn mode(&self) -> Extension {
    self.ext
  }

  pub fn extension(&self) -> String {
    self.ext.to_string()
  }

  pub fn ext(&self) -> Extension {
    self.ext
  }

  pub fn path(&self) -> &Path {
    self.path
  }

  pub fn is_valid(&self) -> bool {
    match self.ext {
      Extension::Unmatched => false,
      _ => true
    }
  }

  pub fn use_calamine(&self) -> bool {
    self.ext.use_calamine()
  }

  pub fn filename(&self) -> String {
    if let Some(file_ref) = self.path.file_name() {
        file_ref.to_string_lossy().to_string()
    } else {
        "".to_owned()
    }
  }
}



#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum ReadMode {
  #[default]
  Sync,
  PreviewAsync,
  Async
}

/// either Preview or Async mode
impl ReadMode {
  pub fn is_async(&self) -> bool {
    match self {
      Self::Sync => false,
      _ => true
    }
  }

  /// not preview or sync mode
  pub fn is_full_async(&self) -> bool {
    match self {
      Self::Async => true,
      _ => false
    }
  }
}

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

  #[test]
  fn test_format_mode() {
    let custom_boolean = Format::truthy_custom("si", "no");
    assert_eq!(custom_boolean.to_string(), "truthy(si,no)");
  }

}