qsv 16.1.0

A Blazing-Fast Data-wrangling toolkit.
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
static USAGE: &str = r#"
Renders a template using CSV data with the MiniJinja template engine.
https://docs.rs/minijinja/latest/minijinja/

Each CSV row is used to populate the template, with column headers used as variable names.
Non-alphanumeric characters in column headers are replaced with an underscore ("_").
The template syntax follows the Jinja2 template language with additional custom filters
(see bottom of file).

Example data:
    name,balance,"loyalty points",active
    Alice,123.45,100,true
    Bob,678.90,200,false

Example template:
  Dear {{ name }},
    Your account balance is {{ balance|format_float(2) }} with {{ points|human_count }} loyalty_points!
    Status: {% if active|str_to_bool is true %}Active{% else %}Inactive{% endif %}

For examples, see https://github.com/jqnatividad/qsv/blob/master/tests/test_template.rs.
For a relatively complex MiniJinja template, see https://github.com/jqnatividad/qsv/blob/master/scripts/template.tpl

Usage:
    qsv template [options] [--template <str> | --template-file <file>] [<input>] [<outdir> | --output <file>]
    qsv template --help

template arguments:
    <input>                     The CSV file to read. If not given, input is read from STDIN.
    <outdir>                    The directory where the output files will be written.
                                If it does not exist, it will be created.
template options:
    --template <str>            Template string to use (alternative to --template-file)
    -t, --template-file <file>  Template file to use
    --outfilename <str>         Template string to use to create the filename of the output 
                                files to write to <outdir>. If set to just QSV_ROWNO, the filestem
                                is set to the current rowno of the record, padded with leading
                                zeroes, with the ".txt" extension (e.g. 001.txt, 002.txt, etc.)
                                The number of leading zeroes is determined by the width of the
                                rowcount (e.g. if rowcount is 1000, the rendered files will be
                                0001.txt, 0002.txt, etc.).
                                Note that the QSV_ROWNO variable is also available in the context
                                if you want to use it in the filename template.
                                [default: QSV_ROWNO]
    --customfilter-error <arg>  The value to return when a custom filter returns an error.
                                Use "<empty string>" to return an empty string.
                                [default: <FILTER_ERROR>]
    -j, --jobs <arg>            The number of jobs to run in parallel.
                                When not set, the number of jobs is set to the number of CPUs detected.
    -b, --batch <size>          The number of rows per batch to load into memory, before running in parallel.
                                Set to 0 to load all rows in one batch.
                                [default: 50000]

Common options:
    -h, --help                  Display this message
    -o, --output <file>         Write output to <file> instead of stdout
    -n, --no-headers            When set, the first row will not be interpreted
                                as headers. Templates must use numeric 1-based indices
                                with the "_c" prefix.(e.g. col1: {{_c1}} col2: {{_c2}})
    --delimiter <sep>           Field separator for reading CSV [default: ,]
"#;

use std::{
    fs,
    io::{BufWriter, Write},
    sync::OnceLock,
};

use minijinja::Environment;
use serde::Deserialize;

use crate::{
    config::{Config, Delimiter, DEFAULT_WTR_BUFFER_CAPACITY},
    util, CliError, CliResult,
};

const QSV_ROWNO: &str = "QSV_ROWNO";

#[derive(Deserialize)]
struct Args {
    arg_input:               Option<String>,
    arg_outdir:              Option<String>,
    flag_template:           Option<String>,
    flag_template_file:      Option<String>,
    flag_output:             Option<String>,
    flag_outfilename:        String,
    flag_customfilter_error: String,
    flag_jobs:               Option<usize>,
    flag_batch:              usize,
    flag_delimiter:          Option<Delimiter>,
    flag_no_headers:         bool,
}

static FILTER_ERROR: OnceLock<String> = OnceLock::new();

impl From<minijinja::Error> for CliError {
    fn from(err: minijinja::Error) -> CliError {
        CliError::Other(err.to_string())
    }
}

pub fn run(argv: &[&str]) -> CliResult<()> {
    let args: Args = util::get_args(USAGE, argv)?;

    // Get template content
    let template_content = match (args.flag_template_file, args.flag_template) {
        (Some(path), None) => fs::read_to_string(path)?,
        (None, Some(template)) => template,
        _ => return fail_clierror!("Must provide either --template or --template-string"),
    };

    // Initialize FILTER_ERROR from args.flag_customfilter_error
    if FILTER_ERROR
        .set(if args.flag_customfilter_error == "<empty string>" {
            String::new()
        } else {
            args.flag_customfilter_error
        })
        .is_err()
    {
        return fail!("Cannot initialize custom filter error message.");
    }

    // Set up minijinja environment
    let mut env = Environment::new();

    // Add custom filters
    env.add_filter("substr", substr);
    env.add_filter("format_float", format_float);
    env.add_filter("human_count", human_count);
    env.add_filter("human_float_count", human_float_count);
    env.add_filter("human_bytes", human_bytes);
    env.add_filter("round_num", round_num);
    env.add_filter("str_to_bool", str_to_bool);
    // TODO: Add lookup filter

    // Set up template
    env.add_template("template", &template_content)?;
    let template = env.get_template("template")?;

    // Set up CSV reader
    let rconfig = Config::new(args.arg_input.as_ref())
        .delimiter(args.flag_delimiter)
        .no_headers(args.flag_no_headers);

    let mut rdr = rconfig.reader()?;
    // Check if headers are present
    let headers = if args.flag_no_headers {
        // If no headers, create a new StringRecord
        csv::StringRecord::new()
    } else {
        // If headers are present, sanitize them
        let headers = rdr.headers()?.clone();
        let sanitized_headers: Vec<String> = headers
            .iter()
            .map(|h| {
                h.chars()
                    .map(|c| if c.is_alphanumeric() { c } else { '_' })
                    .collect()
            })
            .collect();
        sanitized_headers.push(QSV_ROWNO.to_string());
        // Create a new StringRecord from the sanitized headers
        csv::StringRecord::from(sanitized_headers)
    };

    // Set up output handling
    let output_to_dir = args.arg_outdir.is_some();
    let mut row_number = 0_u64;
    let mut rowcount = 0;

    // Create filename environment once if needed
    let filename_env = if output_to_dir && args.flag_outfilename != QSV_ROWNO {
        let mut env = Environment::new();
        env.add_template("filename", &args.flag_outfilename)?;
        Some(env)
    } else {
        rowcount = util::count_rows(&rconfig)?;
        None
    };
    // Get width of rowcount for padding leading zeroes
    let width = rowcount.to_string().len();

    if output_to_dir {
        fs::create_dir_all(args.arg_outdir.as_ref().unwrap())?;
    }

    let mut wtr = if output_to_dir {
        None
    } else {
        Some(match args.flag_output {
            Some(file) => Box::new(BufWriter::with_capacity(
                DEFAULT_WTR_BUFFER_CAPACITY,
                fs::File::create(file)?,
            )) as Box<dyn Write>,
            None => Box::new(BufWriter::with_capacity(
                DEFAULT_WTR_BUFFER_CAPACITY,
                std::io::stdout(),
            )) as Box<dyn Write>,
        })
    };

    let no_headers = args.flag_no_headers;

    // amortize memory allocation by reusing record
    #[allow(unused_assignments)]
    let mut batch_record = csv::StringRecord::new();

    // reuse batch buffers
    let batchsize: usize = if args.flag_batch == 0 {
        util::count_rows(&rconfig)? as usize
    } else {
        args.flag_batch
    };
    let mut batch = Vec::with_capacity(batchsize);
    let mut batch_results = Vec::with_capacity(batchsize);

    util::njobs(args.flag_jobs);

    // main loop to read CSV and construct batches for parallel processing.
    // each batch is processed via Rayon parallel iterator.
    // loop exits when batch is empty.
    'batch_loop: loop {
        for _ in 0..batchsize {
            row_number += 1;
            match rdr.read_record(&mut batch_record) {
                Ok(has_data) => {
                    if has_data {
                        batch_record.push_field(itoa::Buffer::new().format(row_number));
                        batch.push(std::mem::take(&mut batch_record));
                    } else {
                        // nothing else to add to batch
                        break;
                    }
                },
                Err(e) => {
                    return fail_clierror!("Error reading file: {e}");
                },
            }
        }

        if batch.is_empty() {
            // break out of infinite loop when at EOF
            break 'batch_loop;
        }

        batch.par_iter().for_each(|record| {
            if no_headers {
                // Use numeric, column 1-based indices (e.g. _c1, _c2, etc.)
                let record_len = record.len();
                for (i, field) in record.iter().enumerate() {
                    if i == record_len - 1 {
                        context.insert(
                            QSV_ROWNO.to_string(),
                            simd_json::OwnedValue::String(field.to_owned()),
                        );
                    } else {
                        context.insert(
                            format!("_c{}", i + 1),
                            simd_json::OwnedValue::String(field.to_owned()),
                        );
                    }
                }
            } else {
                // Use header names
                for (header, field) in headers.iter().zip(record.iter()) {
                    context.insert(
                        header.to_string(),
                        simd_json::OwnedValue::String(field.to_owned()),
                    );
                }
            }
            rendered = template.render(&context)?;

            if output_to_dir {
                outfilename = if args.flag_outfilename == QSV_ROWNO {
                    // Pad row number with required number of leading zeroes
                    format!("{row_number:0width$}.txt")
                } else {
                    filename_env
                        .as_ref()
                        .unwrap()
                        .get_template("filename")?
                        .render(&context)?
                };
                let outpath = std::path::Path::new(args.arg_outdir.as_ref().unwrap()).join(outfilename);
                let mut writer = BufWriter::new(fs::File::create(outpath)?);
                write!(writer, "{rendered}")?;
                writer.flush()?;
            } else if let Some(ref mut w) = wtr {
                w.write_all(rendered.as_bytes())?;
            }
        }).collect_into_vec(&mut batch_results);

        for result_record in &batch_results {
            wtr.write_record(result_record)?;
        }

        batch.clear();
    }

    // amortize allocations
    let mut curr_record = csv::StringRecord::new();
    #[allow(unused_assignments)]
    let mut rendered = String::new();
    #[allow(unused_assignments)]
    let mut outfilename = String::new();
    let mut context = simd_json::owned::Object::default();

    // Process each record
    for record in rdr.records() {
        row_number += 1;
        curr_record.clone_from(&record?);

        if args.flag_no_headers {
            // Use numeric, column 1-based indices (e.g. _c1, _c2, etc.)
            for (i, field) in curr_record.iter().enumerate() {
                context.insert(
                    format!("_c{}", i + 1),
                    simd_json::OwnedValue::String(field.to_owned()),
                );
            }
        } else {
            // Use header names
            for (header, field) in headers.iter().zip(curr_record.iter()) {
                context.insert(
                    header.to_string(),
                    simd_json::OwnedValue::String(field.to_owned()),
                );
            }
        }
        // Always add row number to context
        context.insert(
            QSV_ROWNO.to_string(),
            simd_json::OwnedValue::from(row_number),
        );

        // Render template with record data
        rendered = template.render(&context)?;

        if output_to_dir {
            outfilename = if args.flag_outfilename == QSV_ROWNO {
                // Pad row number with required number of leading zeroes
                format!("{row_number:0width$}.txt")
            } else {
                filename_env
                    .as_ref()
                    .unwrap()
                    .get_template("filename")?
                    .render(&context)?
            };
            let outpath = std::path::Path::new(args.arg_outdir.as_ref().unwrap()).join(outfilename);
            let mut writer = BufWriter::new(fs::File::create(outpath)?);
            write!(writer, "{rendered}")?;
            writer.flush()?;
        } else if let Some(ref mut w) = wtr {
            w.write_all(rendered.as_bytes())?;
        }
        context.clear();
    }

    if let Some(mut w) = wtr {
        w.flush()?;
    }

    Ok(())
}

// CUSTOM MINIJINJA FILTERS =========================================
// safety: for all FILTER_ERROR.gets, safe to unwrap as FILTER_ERROR
// is initialized on startup

/// Returns a substring of the input string from start index to end index (exclusive).
/// If end is not provided, returns substring from start to end of string.
/// Returns --customfilter-error (default: <FILTER_ERROR>) if indices are invalid.
fn substr(value: &str, start: u32, end: Option<u32>) -> String {
    let end = end.unwrap_or(value.len() as _);
    if let Some(s) = value.get(start as usize..end as usize) {
        s.into()
    } else {
        FILTER_ERROR.get().unwrap().clone()
    }
}

/// Formats a float number string with the specified decimal precision.
/// Returns --customfilter-error (default: <FILTER_ERROR>) if input cannot be parsed as float.
fn format_float(value: &str, precision: u32) -> String {
    value.parse::<f64>().map_or_else(
        |_| FILTER_ERROR.get().unwrap().clone(),
        |num| format!("{:.1$}", num, precision as usize),
    )
}

/// Formats an integer with thousands separators (e.g. "1,234,567").
/// Returns --customfilter-error (default: <FILTER_ERROR>) if input cannot be parsed as integer.
fn human_count(value: &str) -> String {
    atoi_simd::parse::<u64>(value.as_bytes()).map_or_else(
        |_| FILTER_ERROR.get().unwrap().clone(),
        |num| indicatif::HumanCount(num).to_string(),
    )
}

/// Formats a float number with thousands separators (e.g. "1,234,567.89").
/// Returns --customfilter-error (default: <FILTER_ERROR>) if input cannot be parsed as float.
fn human_float_count(value: &str) -> String {
    value.parse::<f64>().map_or_else(
        |_| FILTER_ERROR.get().unwrap().clone(),
        |num| indicatif::HumanFloatCount(num).to_string(),
    )
}

/// Formats bytes using binary prefixes (e.g. "1.5 GiB").
/// Returns --customfilter-error (default: <FILTER_ERROR>) if input cannot be parsed as integer.
fn human_bytes(value: &str) -> String {
    atoi_simd::parse::<u64>(value.as_bytes()).map_or_else(
        |_| FILTER_ERROR.get().unwrap().clone(),
        |num| indicatif::HumanBytes(num).to_string(),
    )
}

/// Rounds a float number to specified number of decimal places.
/// Returns --customfilter-error (default: <FILTER_ERROR>) if input cannot be parsed as float.
fn round_num(value: &str, places: u32) -> String {
    value.parse::<f64>().map_or_else(
        |_| FILTER_ERROR.get().unwrap().clone(),
        |num| util::round_num(num, places),
    )
}

/// Converts string to boolean.
/// Returns true for "true", "1", or "yes" (case insensitive).
/// Returns false for all other values.
fn str_to_bool(value: &str) -> bool {
    matches!(value.to_ascii_lowercase().as_str(), "true" | "1" | "yes")
}