-
Notifications
You must be signed in to change notification settings - Fork 71
/
luau.rs
2142 lines (1875 loc) · 82.8 KB
/
luau.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
static USAGE: &str = r#"
Create multiple new computed columns, filter rows or compute aggregations by
executing a Luau 0.650 script for every row (SEQUENTIAL MODE) or for
specified rows (RANDOM ACCESS MODE) of a CSV file.
Luau is not just another qsv command. It is qsv's Domain-Specific Language (DSL)
for data-wrangling. 👑
The executed Luau has 3 ways to reference row columns (as strings):
1. Directly by using column name (e.g. Amount), can be disabled with -g
2. Indexing col variable by column name: col.Amount or col["Total Balance"]
3. Indexing col variable by column 1-based index: col[1], col[2], etc.
This is only available with the --colindex or --no-headers options.
Of course, if your input has no headers, then 3. will be the only available
option.
It has two subcommands:
map - Create new columns by mapping the result of a Luau script for each row.
filter - Filter rows by executing a Luau script for each row. Rows that return
true are kept, the rest are filtered out.
Some usage examples:
Sum numeric columns 'a' and 'b' and call new column 'c'
$ qsv luau map c "a + b"
$ qsv luau map c "col.a + col['b']"
$ qsv luau map c --colindex "col[1] + col[2]"
There is some magic in the previous example as 'a' and 'b' are passed in
as strings (not numbers), but Luau still manages to add them up.
A more explicit way of doing it, is by using tonumber
$ qsv luau map c "tonumber(a) + tonumber(b)"
Add running total column for Amount
$ qsv luau map Total "tot = (tot or 0) + Amount; return tot"
Or use the --begin and --end options to compute the running & grand totals
$ qsv luau map Total --begin "tot = 0; gtotal = 0" \
"tot = tot + Amount; gtotal = gtotal + tot; return tot" --end "return gtotal"
Add running total column for Amount when previous balance was 900
$ qsv luau map Total "tot = (tot or 900) + Amount; return tot"
Convert Amount to always-positive AbsAmount and Type (debit/credit) columns
$ qsv luau map Type \
"if tonumber(Amount) < 0 then return 'debit' else return 'credit' end" | \
qsv luau map AbsAmount "math.abs(tonumber(Amount))"
Map multiple new columns in one pass
$ qsv luau map newcol1,newcol2,newcol3 "{cola + 1, colb + 2, colc + 3}"
Filter some rows based on numerical filtering
$ qsv luau filter "tonumber(a) > 45"
$ qsv luau filter "tonumber(a) >= tonumber(b)"
Typing long scripts on the command line gets tiresome rather quickly. Use the
"file:" prefix or the ".lua/.luau" file extension to read non-trivial scripts
from the filesystem.
In the following example, both the BEGIN and END scripts have the lua/luau file
extension so they are read from the filesystem. With the debitcredit.script file,
we use the "file:" prefix to read it from the filesystem.
$ qsv luau map Type -B init.lua file:debitcredit.script -E end.luau
With "luau map", if the MAIN script is invalid for a row, "<ERROR>" followed by a
detailed error message is returned for that row.
With "luau filter", if the MAIN script is invalid for a row, that row is not filtered.
If any row has an invalid result, an exitcode of 1 is returned and an error count
is logged.
SPECIAL VARIABLES:
"_IDX" - a READ-only variable that is zero during the BEGIN script and
set to the current row number during the MAIN & END scripts.
It is primarily used in SEQUENTIAL MODE when the CSV has no index or you
wish to process the CSV sequentially.
"_INDEX" - a READ/WRITE variable that enables RANDOM ACCESS MODE when used in
a script. Using "_INDEX" in a script switches qsv to RANDOM ACCESS MODE
where setting it to a row number will change the current row to the
specified row number. It will only work, however, if the CSV has an index.
When using _INDEX, the MAIN script will keep looping and evaluate the row
specified by _INDEX until _INDEX is set to an invalid row number
(e.g. <= zero or to a value greater than _ROWCOUNT).
If the CSV has no index, qsv will abort with an error unless "qsv_autoindex()"
is called in the BEGIN script to create an index.
"_ROWCOUNT" - a READ-only variable which is zero during the BEGIN & MAIN scripts,
and set to the rowcount during the END script when the CSV has no index
(SEQUENTIAL MODE).
When using _INDEX and the CSV has an index, _ROWCOUNT will be set to the
rowcount of the CSV file, even from the BEGINning
(RANDOM ACCESS MODE).
"_LASTROW" - a READ-only variable that is set to the last row number of the CSV.
Like _INDEX, it will also trigger RANDOM ACCESS MODE if used in a script.
Similarly, if the CSV has no index, qsv will also abort with an error unless
"qsv_autoindex()" is called in the BEGIN script to create an index.
For security and safety reasons as a purpose-built embeddable interpreter,
Luau's standard library is relatively minimal (https://luau-lang.org/library).
That's why qsv bundles & preloads LuaDate v2.2.1 as date manipulation is a common task.
See https://tieske.github.io/date/ on how to use the LuaDate library.
Additional libraries can be loaded from the LUAU_PATH using luau's "require" function.
See https://github.com/LewisJEllis/awesome-lua for a list of other libraries.
With the judicious use of "require", the BEGIN script & special variables, one can
create variables, tables, arrays & functions that can be used for complex aggregation
operations in the END script.
SCRIPT DEVELOPMENT TIPS:
When developing Luau scripts, be sure to take advantage of the "qsv_log" function to
debug your script. It will log messages at the level (INFO, WARN, ERROR, DEBUG, TRACE)
specified by the QSV_LOG_LEVEL environment variable (see docs/Logging.md for details).
At the DEBUG level, the log messages will be more verbose to faciitate debugging.
It will also skip precompiling the MAIN script to bytecode so you can see more
detailed error messages with line numbers.
Bear in mind that qsv strips comments from Luau scripts before executing them.
This is done so qsv doesn't falsely trigger on special variables mentioned in comments.
When checking line numbers in DEBUG mode, be sure to refer to the comment-stripped
scripts in the log file, not the original commented scripts.
There are more Luau helper functions in addition to "qsv_log" - "qsv_break", "qsv_skip",
"qsv_insertrecord", "qsv_autoindex", "qsv_coalesce", "qsv_sleep", "qsv_writefile",
"qsv_cmd", "qsv_shellcmd", "qsv_setenv", "qsv_getenv" and last but not least -
the powerful "qsv_register_lookup" which allows you to "lookup" values against other
CSVs on the filesystem, a URL, datHere's lookup repo or CKAN instances.
Detailed descriptions of these helpers can be found in the "setup_helpers" section at
the bottom of this file.
For more detailed examples, see https://github.com/jqnatividad/qsv/blob/master/tests/test_luau.rs.
Usage:
qsv luau map [options] -n <main-script> [<input>]
qsv luau map [options] <new-columns> <main-script> [<input>]
qsv luau filter [options] <main-script> [<input>]
qsv luau map --help
qsv luau filter --help
qsv luau --help
Luau arguments:
All <script> arguments/options can either be the Luau code, or if it starts with
"file:" or ends with ".luau/.lua" - the filepath from which to load the script.
Instead of using the --begin and --end options, you can also embed BEGIN and END
scripts in the MAIN script by using the "BEGIN { ... }!" and "END { ... }!" syntax.
The BEGIN script is embedded in the MAIN script by adding a BEGIN block at the
top of the script. The BEGIN block must start at the beginning of the line.
It can contain multiple statements.
The MAIN script is the main Luau script to execute. It is executed for EACH ROW of
the input CSV. It can contain multiple statements and should end with a "return" stmt.
In map mode, the return value is/are the new value/s of the mapped column/s.
In filter mode, the return value is a boolean indicating if the row should be filtered.
The END script is embedded in the MAIN script by adding an END block at the bottom
of the script. The END block must start at the beginning of the line.
It can contain multiple statements.
<new-columns> is a comma-separated list of new computed columns to add to the CSV
when using "luau map". Note that the new columns are added to the CSV after the
existing columns.
Luau options:
-g, --no-globals Don't create Luau global variables for each column,
only `col`. Useful when some column names mask standard
Luau globals and a bit more performance.
Note: access to Luau globals thru _G remains even with -g.
--colindex Create a 1-based column index. Useful when some column names
mask standard Luau globals. Automatically enabled with--no-headers.
-r, --remap Only the listed new columns are written to the output CSV.
Only applies to "map" subcommand.
-B, --begin <script> Luau script/file to execute in the BEGINning, before
processing the CSV with the main-script.
Typically used to initialize global variables.
Takes precedence over an embedded BEGIN script.
If <script> begins with "file:" or ends with ".luau/.lua",
it's interpreted as a filepath from which to load the script.
-E, --end <script> Luau script/file to execute at the END, after processing the
CSV with the main-script.
Typically used for aggregations.
The output of the END script is sent to stderr.
Takes precedence over an embedded END script.
If <script> begins with "file:" or ends with ".luau/.lua",
it's interpreted as a filepath from which to load the script.
--luau-path <pattern> The LUAU_PATH pattern to use from which the scripts
can "require" lua/luau library files from.
See https://www.lua.org/pil/8.1.html
[default: ?;?.luau;?.lua]
--max-errors <count> The maximum number of errors to tolerate before aborting.
Set to zero to disable error limit.
[default: 100]
--timeout <seconds> Timeout for downloading lookup_tables using
the qsv_register_lookup() helper function.
[default: 30]
--ckan-api <url> The URL of the CKAN API to use for downloading lookup_table
resources using the qsv_register_lookup() helper function
with the "ckan://" scheme.
If the QSV_CKAN_API envvar is set, it will be used instead.
[default: https://data.dathere.com/api/3/action]
--ckan-token <token> The CKAN API token to use. Only required if downloading
private resources.
If the QSV_CKAN_TOKEN envvar is set, it will be used instead.
--cache-dir <dir> The directory to use for caching downloaded lookup_table
resources using the qsv_register_lookup() helper function.
If the directory does not exist, qsv will attempt to create it.
If the QSV_CACHE_DIR envvar is set, it will be used instead.
[default: ~/.qsv-cache]
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. Automatically enables --colindex option.
-d, --delimiter <arg> The field delimiter for reading CSV data.
Must be a single character. (default: ,)
-p, --progressbar Show progress bars. Not valid for stdin.
Ignored in qsvdp.
In SEQUENTIAL MODE, the progress bar will show the
number of rows processed.
In RANDOM ACCESS MODE, the progress bar will show
the position of the current row being processed.
Enabling this option will also suppress stderr output
from the END script.
"#;
use std::{
env, fs, io,
io::Write,
path::Path,
sync::atomic::{AtomicBool, AtomicI8, AtomicU16, Ordering},
};
use csv_index::RandomAccessSimple;
#[cfg(any(feature = "feature_capable", feature = "lite"))]
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
use log::{debug, info, log_enabled};
use mlua::{Lua, LuaSerdeExt, Value};
use serde::Deserialize;
// use simple_expand_tilde::expand_tilde;
use crate::{
config::{Config, Delimiter, DEFAULT_WTR_BUFFER_CAPACITY},
lookup, util, CliError, CliResult,
};
#[allow(dead_code)]
#[derive(Deserialize)]
struct Args {
cmd_map: bool,
cmd_filter: bool,
arg_new_columns: Option<String>,
arg_main_script: String,
arg_input: Option<String>,
flag_no_globals: bool,
flag_colindex: bool,
flag_remap: bool,
flag_begin: Option<String>,
flag_end: Option<String>,
flag_luau_path: String,
flag_output: Option<String>,
flag_no_headers: bool,
flag_delimiter: Option<Delimiter>,
flag_progressbar: bool,
flag_max_errors: usize,
flag_timeout: u16,
flag_ckan_api: String,
flag_ckan_token: Option<String>,
flag_cache_dir: String,
}
impl From<mlua::Error> for CliError {
fn from(err: mlua::Error) -> CliError {
CliError::Other(err.to_string())
}
}
static QSV_BREAK: AtomicBool = AtomicBool::new(false);
static QSV_SKIP: AtomicBool = AtomicBool::new(false);
// internal variables
static QSV_BREAK_MSG: &str = "_QSV_BRKMSG";
static QSV_INSERTRECORD_TBL: &str = "_QSV_IR_TBL";
static QSV_CACHE_DIR: &str = "_QSV_CACHE_DIR";
// special variables that can be used in scripts
static QSV_V_IDX: &str = "_IDX";
static QSV_V_ROWCOUNT: &str = "_ROWCOUNT";
static QSV_V_LASTROW: &str = "_LASTROW";
static QSV_V_INDEX: &str = "_INDEX";
// there are 3 stages: 1-BEGIN, 2-MAIN, 3-END
#[derive(Copy, Clone, Debug, PartialEq)]
enum Stage {
Begin = 0,
Main = 1,
End = 2,
}
impl TryFrom<i8> for Stage {
type Error = &'static str;
fn try_from(value: i8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Stage::Begin),
1 => Ok(Stage::Main),
2 => Ok(Stage::End),
_ => Err("Invalid stage value"),
}
}
}
impl Stage {
fn set_current(self) {
LUAU_STAGE.store(self as i8, Ordering::Relaxed);
}
fn current() -> Option<Self> {
Stage::try_from(LUAU_STAGE.load(Ordering::Relaxed)).ok()
}
const fn as_str(self) -> &'static str {
match self {
Stage::Begin => "BEGIN",
Stage::Main => "MAIN",
Stage::End => "END",
}
}
}
static LUAU_STAGE: AtomicI8 = AtomicI8::new(0);
static TIMEOUT_SECS: AtomicU16 = AtomicU16::new(30);
pub fn run(argv: &[&str]) -> CliResult<()> {
let args: Args = util::get_args(USAGE, argv)?;
// safety: its safe since flag_timeout is a u16
TIMEOUT_SECS.store(
util::timeout_secs(args.flag_timeout)?.try_into().unwrap(),
Ordering::Relaxed,
);
let rconfig = Config::new(args.arg_input.as_ref())
.delimiter(args.flag_delimiter)
.no_headers(args.flag_no_headers);
let mut luau_script = if let Some(script_filepath) = args.arg_main_script.strip_prefix("file:")
{
match fs::read_to_string(script_filepath) {
Ok(file_contents) => file_contents,
Err(e) => return fail_clierror!("Cannot load Luau file: {e}"),
}
} else if std::path::Path::new(&args.arg_main_script)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("luau"))
|| std::path::Path::new(&args.arg_main_script)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("lua"))
{
match fs::read_to_string(args.arg_main_script.clone()) {
Ok(file_contents) => file_contents,
Err(e) => return fail_clierror!("Cannot load .lua/.luau file: {e}"),
}
} else {
args.arg_main_script.clone()
};
// in Luau, comments begin with two consecutive hyphens
// let's remove them, so we don't falsely trigger on commented special variables
let comment_remover_re = regex::Regex::new(r"(?m)(^\s*?--.*?$)").unwrap();
luau_script = comment_remover_re.replace_all(&luau_script, "").to_string();
let mut index_file_used =
luau_script.contains(QSV_V_INDEX) || luau_script.contains(QSV_V_LASTROW);
// check if the main script has BEGIN and END blocks
// and if so, extract them and remove them from the main script
let begin_re = regex::Regex::new(r"(?ms)^BEGIN \{(?P<begin_block>.*?)\}!").unwrap();
let end_re = regex::Regex::new(r"(?ms)^END \{(?P<end_block>.*?)\}!").unwrap();
let mut embedded_begin_script = String::new();
let mut embedded_end_script = String::new();
let mut main_script = luau_script.clone();
if let Some(caps) = begin_re.captures(&luau_script) {
embedded_begin_script = caps["begin_block"].to_string();
let begin_block_replace = format!("BEGIN {{{embedded_begin_script}}}!");
debug!("begin_block_replace: {begin_block_replace:?}");
main_script = main_script.replace(&begin_block_replace, "");
}
if let Some(caps) = end_re.captures(&main_script) {
embedded_end_script = caps["end_block"].to_string();
let end_block_replace = format!("END {{{embedded_end_script}}}!");
main_script = main_script.replace(&end_block_replace, "");
}
luau_script = main_script;
// if the main script is a single expression, we need to prepend a return statement
let mut main_script = if luau_script.contains("return") {
String::new()
} else {
String::from("return ")
};
main_script.push_str(luau_script.trim());
debug!("MAIN script: {main_script:?}");
// check if a BEGIN script was specified
let begin_script = if let Some(ref begin) = args.flag_begin {
let discrete_begin = if let Some(begin_filepath) = begin.strip_prefix("file:") {
match fs::read_to_string(begin_filepath) {
Ok(begin) => begin,
Err(e) => return fail_clierror!("Cannot load Luau BEGIN script file: {e}"),
}
} else if std::path::Path::new(begin)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("luau"))
|| std::path::Path::new(begin)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("lua"))
{
match fs::read_to_string(begin.clone()) {
Ok(file_contents) => file_contents,
Err(e) => return fail_clierror!("Cannot load BEGIN .lua/luau file: {e}"),
}
} else {
begin.to_string()
};
comment_remover_re
.replace_all(&discrete_begin, "")
.to_string()
} else {
embedded_begin_script.trim().to_string()
};
// check if the BEGIN script uses _INDEX
index_file_used = index_file_used
|| begin_script.contains(QSV_V_INDEX)
|| begin_script.contains(QSV_V_LASTROW);
let qsv_register_lookup_used = begin_script.contains("qsv_register_lookup(");
debug!("BEGIN script: {begin_script:?}");
// check if an END script was specified
let end_script = if let Some(ref end) = args.flag_end {
let discrete_end = if let Some(end_filepath) = end.strip_prefix("file:") {
match fs::read_to_string(end_filepath) {
Ok(end) => end,
Err(e) => return fail_clierror!("Cannot load Luau END script file: {e}"),
}
} else if std::path::Path::new(end)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("luau"))
|| std::path::Path::new(end)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("lua"))
{
match fs::read_to_string(end.clone()) {
Ok(file_contents) => file_contents,
Err(e) => return fail_clierror!("Cannot load END .lua/.luau file: {e}"),
}
} else {
end.to_string()
};
comment_remover_re
.replace_all(&discrete_end, "")
.to_string()
} else {
embedded_end_script.trim().to_string()
};
// check if the END script uses _INDEX
index_file_used =
index_file_used || end_script.contains(QSV_V_INDEX) || end_script.contains(QSV_V_LASTROW);
debug!("END script: {end_script:?}");
// check if "require" was used in the scripts. If so, we need to setup LUAU_PATH;
// we check for '= require "' using a robust regex pattern.
// \u0022 is the unicode codepoint for a double quote.
let requires_re = regex::Regex::new(r"(?mi)=[[:blank:]]*require[[:blank:]]+\u0022").unwrap();
let require_used = requires_re.is_match(&main_script)
|| requires_re.is_match(&begin_script)
|| requires_re.is_match(&end_script);
// if require_used, create a temporary directory and copy date.lua there.
// we do this outside the "require_used" setup below as the tempdir
// needs to persist until the end of the program.
let temp_dir = if require_used {
match tempfile::tempdir() {
Ok(temp_dir) => {
let temp_dir_path = temp_dir.into_path();
Some(temp_dir_path)
},
Err(e) => {
return fail_clierror!(
"Cannot create temporary directory to copy luadate library to: {e}"
)
},
}
} else {
None
};
// "require " was used in the scripts, so we need to prepare luadate library and setup LUAU_PATH
if require_used {
// prepare luadate so users can just use 'date = require "date"' in their scripts
let luadate_library = include_bytes!("../../resources/luau/vendor/luadate/date.lua");
// safety: safe to unwrap as we just created the tempdir above
let tdir_path = temp_dir.clone().unwrap();
let luadate_path = tdir_path.join("date.lua");
fs::write(luadate_path.clone(), luadate_library)?;
// set LUAU_PATH to include the luadate library
let mut luau_path = args.flag_luau_path.clone();
luau_path.push_str(&format!(";{}", luadate_path.as_os_str().to_string_lossy()));
env::set_var("LUAU_PATH", luau_path.clone());
info!(r#"set LUAU_PATH to "{luau_path}""#);
}
// -------- setup Luau environment --------
let luau = Lua::new();
// see Compiler settings here: https://docs.rs/mlua/latest/mlua/struct.Compiler.html#
let luau_compiler = if log_enabled!(log::Level::Debug) || log_enabled!(log::Level::Trace) {
// debugging is on, set more debugging friendly compiler settings
// so we can see more error details in the logfile
mlua::Compiler::new()
.set_optimization_level(0)
.set_debug_level(2)
.set_coverage_level(2)
} else {
// use more performant compiler settings
mlua::Compiler::new()
.set_optimization_level(2)
.set_debug_level(1)
.set_coverage_level(0)
};
// set default Luau compiler
luau.set_compiler(luau_compiler.clone());
let globals = luau.globals();
// check the QSV_CKAN_API environment variable
let ckan_api = if let Ok(api) = std::env::var("QSV_CKAN_API") {
api
} else {
args.flag_ckan_api.clone()
};
// check the QSV_CKAN_TOKEN environment variable
let ckan_token = if let Ok(token) = std::env::var("QSV_CKAN_TOKEN") {
Some(token)
} else {
args.flag_ckan_token.clone()
};
setup_helpers(&luau, args.flag_delimiter, ckan_api, ckan_token)?;
// check if qsv_registerlookup_used is set, if it is, setup the qsv_cache directory
if qsv_register_lookup_used {
let qsv_cache_dir = lookup::set_qsv_cache_dir(&args.flag_cache_dir)?;
info!("Using cache directory: {qsv_cache_dir}");
globals.raw_set(QSV_CACHE_DIR, qsv_cache_dir)?;
}
debug!("Main processing");
if index_file_used {
info!("RANDOM ACCESS MODE (_INDEX or _LASTROW special variables used)");
random_access_mode(
&rconfig,
&args,
&luau,
&luau_compiler,
&globals,
&begin_script,
&main_script,
&end_script,
args.flag_max_errors,
)?;
} else {
info!("SEQUENTIAL MODE");
sequential_mode(
&rconfig,
&args,
&luau,
&luau_compiler,
&globals,
&begin_script,
&main_script,
&end_script,
args.flag_max_errors,
)?;
}
if let Some(temp_dir) = temp_dir {
// delete the tempdir
fs::remove_dir_all(temp_dir)?;
}
Ok(())
}
// ------------ SEQUENTIAL MODE ------------
// this mode is used when the user does not use _INDEX or _LASTROW in their script,
// so we just scan the CSV, processing the MAIN script in sequence.
fn sequential_mode(
rconfig: &Config,
args: &Args,
luau: &Lua,
luau_compiler: &mlua::Compiler,
globals: &mlua::Table,
begin_script: &str,
main_script: &str,
end_script: &str,
max_errors: usize,
) -> Result<(), CliError> {
globals.raw_set("cols", "{}")?;
let mut rdr = rconfig.reader()?;
let mut wtr = Config::new(args.flag_output.as_ref()).writer()?;
let mut headers = rdr.headers()?.clone();
let mut remap_headers = csv::StringRecord::new();
let mut new_column_count = 0_u8;
let mut headers_count = headers.len();
let debug_enabled = log_enabled!(log::Level::Debug);
if !rconfig.no_headers {
if !args.cmd_filter {
let new_columns = args
.arg_new_columns
.as_ref()
.ok_or("Specify new column names")?;
let new_columns_vec: Vec<&str> = new_columns.split(',').collect();
debug!("new_columns_vec: {new_columns_vec:?}");
for new_column in new_columns_vec {
new_column_count += 1;
let new_column = new_column.trim();
headers.push_field(new_column);
remap_headers.push_field(new_column);
}
}
if args.flag_remap {
wtr.write_record(&remap_headers)?;
headers_count = remap_headers.len();
} else {
wtr.write_record(&headers)?;
}
}
// we initialize the special vars _IDX and _ROWCOUNT
globals.raw_set(QSV_V_IDX, 0)?;
globals.raw_set(QSV_V_ROWCOUNT, 0)?;
if !begin_script.is_empty() {
info!("Compiling and executing BEGIN script. _IDX: 0 _ROWCOUNT: 0");
Stage::Begin.set_current();
if let Err(e) = luau.load(begin_script).exec() {
return fail_clierror!("BEGIN error: Failed to execute \"{begin_script}\".\n{e}");
}
info!("BEGIN executed.");
}
let mut insertrecord = csv::StringRecord::new();
// check if qsv_insertrecord() was called in the BEGIN script
beginend_insertrecord(luau, &mut insertrecord, headers_count, &mut wtr)?;
if QSV_BREAK.load(Ordering::Relaxed) {
let qsv_break_msg: String = globals.raw_get(QSV_BREAK_MSG)?;
winfo!("{qsv_break_msg}");
return Ok(());
}
// we clear the table so we don't falsely detect a call to qsv_insertrecord()
// in the MAIN/END scripts
luau.globals().raw_set(QSV_INSERTRECORD_TBL, Value::Nil)?;
#[cfg(feature = "datapusher_plus")]
let show_progress = false;
#[cfg(any(feature = "feature_capable", feature = "lite"))]
let show_progress =
(args.flag_progressbar || util::get_envvar_flag("QSV_PROGRESSBAR")) && !rconfig.is_stdin();
#[cfg(any(feature = "feature_capable", feature = "lite"))]
let progress = ProgressBar::with_draw_target(None, ProgressDrawTarget::stderr_with_hz(5));
#[cfg(any(feature = "feature_capable", feature = "lite"))]
if show_progress {
util::prep_progress(&progress, util::count_rows(rconfig)?);
} else {
progress.set_draw_target(ProgressDrawTarget::hidden());
}
// check if _IDX was used in the MAIN script
let idx_used = main_script.contains(QSV_V_IDX);
// only precompile main script to bytecode if debug is disabled
let main_bytecode = if debug_enabled {
Vec::new()
} else {
luau_compiler.compile(main_script)?
};
let mut record = csv::StringRecord::new();
let mut idx = 0_u64;
let mut error_count = 0_usize;
Stage::Main.set_current();
info!("Executing MAIN script.");
let mut computed_value;
let mut must_keep_row;
let col = luau.create_table_with_capacity(record.len(), 1)?;
let flag_no_globals = args.flag_no_globals;
let flag_remap = args.flag_remap;
let no_headers = rconfig.no_headers;
let flag_colindex = args.flag_colindex || no_headers;
let cmd_map = args.cmd_map;
let mut err_msg: String;
let mut computed_result;
// main loop
// without an index, we stream the CSV in sequential order
'main: while rdr.read_record(&mut record)? {
#[cfg(any(feature = "feature_capable", feature = "lite"))]
if show_progress {
progress.inc(1);
}
idx += 1;
if idx_used {
// for perf reasons, only update _IDX if it was used in the MAIN script
globals.raw_set(QSV_V_IDX, idx)?;
}
// Updating col
let _ = col.clear();
if flag_colindex {
for (i, v) in record.iter().enumerate() {
col.raw_set(i + 1, v)?;
}
}
if !no_headers {
for (h, v) in headers.iter().zip(record.iter()) {
col.raw_set(h, v)?;
}
}
globals.raw_set("col", col.clone())?;
// Updating global
if !flag_no_globals && !no_headers {
for (h, v) in headers.iter().zip(record.iter()) {
globals.raw_set(h, v)?;
}
}
// if debug is enabled, we eval the script as string instead of precompiled bytecode
// so we can get more detailed error messages with line numbers
computed_result = if debug_enabled {
luau.load(main_script).eval()
} else {
luau.load(&main_bytecode).eval()
};
computed_value = match computed_result {
Ok(computed) => computed,
Err(e) => {
error_count += 1;
err_msg = format!("<ERROR> _IDX: {idx} error({error_count}): {e:?}");
log::error!("{err_msg}");
mlua::IntoLua::into_lua(err_msg, luau)
.map_err(|e| format!("Failed to convert error message to Lua: {e}"))?
},
};
if QSV_BREAK.load(Ordering::Relaxed) {
let qsv_break_msg: String = globals.raw_get(QSV_BREAK_MSG)?;
winfo!("{qsv_break_msg}");
break 'main;
}
if max_errors > 0 && error_count > max_errors {
info!("Maximum number of errors ({max_errors}) reached. Aborting MAIN script.");
break 'main;
}
if cmd_map {
map_computedvalue(&computed_value, &mut record, flag_remap, new_column_count)?;
// check if the script is trying to insert a record with
// qsv_insertrecord(). We do this by checking if the global
// _QSV_IR_TBL exists and is not empty
match luau.globals().raw_get(QSV_INSERTRECORD_TBL) {
Ok(Value::Table(insertrecord_table)) => {
// _QSV_IR_TBL is populated, we have a record to insert
insertrecord.clear();
create_insertrecord(&insertrecord_table, &mut insertrecord, headers_count)?;
if QSV_SKIP.load(Ordering::Relaxed) {
if log_enabled!(log::Level::Debug) {
debug!("Skipping record {idx} because _QSV_SKIP is set to true");
}
QSV_SKIP.store(false, Ordering::Relaxed);
} else {
wtr.write_record(&record)?;
}
wtr.write_record(&insertrecord)?;
insertrecord_table.clear()?;
},
Ok(_) | Err(_) => {
if QSV_SKIP.load(Ordering::Relaxed) {
QSV_SKIP.store(false, Ordering::Relaxed);
} else {
wtr.write_record(&record)?;
}
},
}
} else {
// filter subcommand
must_keep_row = if error_count > 0 {
true
} else {
match computed_value {
Value::Boolean(boolean) => boolean,
Value::Nil => false,
Value::String(strval) => !strval.to_string_lossy().is_empty(),
Value::Integer(intval) => intval != 0,
// we compare to f64::EPSILON as float comparison to zero
// unlike int, where we can say intval != 0, we cannot do fltval !=0
// https://doc.rust-lang.org/std/primitive.f64.html#associatedconstant.EPSILON
Value::Number(fltval) => (fltval).abs() > f64::EPSILON,
_ => true,
}
};
if must_keep_row {
wtr.write_record(&record)?;
}
}
}
if !end_script.is_empty() {
// at the END, set a convenience variable named _ROWCOUNT;
// true, _ROWCOUNT is equal to _IDX at this point, but this
// should make for more readable END scripts.
// Also, _ROWCOUNT is zero during the main script, and only set
// to _IDX during the END script.
Stage::End.set_current();
globals.raw_set(QSV_V_ROWCOUNT, idx)?;
if !idx_used {
// for perf reasons, we only updated _IDX in the main
// hot loop if it was used in the main script
// so we set it here in the END script, if it was not used in the main script
globals.raw_set(QSV_V_IDX, idx)?;
}
info!("Compiling and executing END script. _ROWCOUNT: {idx}");
let end_value: Value = match luau.load(end_script).eval() {
Ok(computed) => computed,
Err(e) => {
let err_msg = format!("<ERROR> END error: Cannot evaluate \"{end_script}\".\n{e}");
log::error!("{err_msg}");
log::error!("END globals: {globals:?}");
mlua::IntoLua::into_lua(err_msg, luau)
.map_err(|e| format!("Failed to convert error message to Lua: {e}"))?
},
};
// check if qsv_insertrecord() was called in the END script
beginend_insertrecord(luau, &mut insertrecord, headers_count, &mut wtr)?;
let end_string = match end_value {
Value::String(string) => string.to_string_lossy(),
Value::Number(number) => ryu::Buffer::new().format_finite(number).to_owned(),
Value::Integer(number) => itoa::Buffer::new().format(number).to_owned(),
Value::Boolean(boolean) => (if boolean { "true" } else { "false" }).to_owned(),
Value::Nil => String::new(),
_ => {
return fail_clierror!(
"Unexpected END value type returned by provided Luau expression. {end_value:?}"
);
},
};
if !end_string.is_empty() && !show_progress {
winfo!("{end_string}");
}
}
wtr.flush()?;
#[cfg(any(feature = "feature_capable", feature = "lite"))]
if show_progress {
util::finish_progress(&progress);
}
info!("SEQUENTIAL MODE: Processed {idx} record/s.");
if error_count > 0 {
return fail_clierror!("Luau errors encountered: {error_count}");
};
Ok(())
}
// ------------ RANDOM ACCESS MODE ------------
// this function is largely similar to sequential_mode, and is triggered when
// we use the special variable _INDEX or _LASTROW in the Luau scripts.
// the primary difference being that we use an Indexed File rdr in the main loop.
// differences pointed out in comments below
fn random_access_mode(
rconfig: &Config,
args: &Args,
luau: &Lua,
luau_compiler: &mlua::Compiler,
globals: &mlua::Table,
begin_script: &str,
main_script: &str,
end_script: &str,
max_errors: usize,
) -> Result<(), CliError> {
// users can create an index file by calling qsv_autoindex() in their BEGIN script
if begin_script.contains("qsv_autoindex()") {
let result = create_index(args.arg_input.as_ref());
if result.is_err() {
return fail_clierror!("Unable to create/update index file");
}
}
// we abort RANDOM ACCESS mode if the index file is not found
let Some(mut idx_file) = rconfig.indexed()? else {
return fail!(
r#"Index required but no index file found. Use "qsv_autoindex()" in your BEGIN script."#
);
};
globals.raw_set("cols", "{}")?;
// with an index, we can fetch the row_count in advance
let mut row_count = util::count_rows(rconfig).unwrap_or_default();
if args.flag_no_headers {
row_count += 1;
}
let mut wtr = Config::new(args.flag_output.as_ref()).writer()?;
let mut headers = idx_file.headers()?.clone();
let mut remap_headers = csv::StringRecord::new();
let mut new_column_count = 0_u8;
let mut headers_count = headers.len();
let debug_enabled = log_enabled!(log::Level::Debug);
if !rconfig.no_headers {
if !args.cmd_filter {
let new_columns = args
.arg_new_columns
.as_ref()
.ok_or("Specify new column names")?;
let new_columns_vec: Vec<&str> = new_columns.split(',').collect();
for new_column in new_columns_vec {
new_column_count += 1;
let new_column = new_column.trim();
headers.push_field(new_column);
remap_headers.push_field(new_column);
}
}
if args.flag_remap {
wtr.write_record(&remap_headers)?;
headers_count = remap_headers.len();
} else {
wtr.write_record(&headers)?;
}
}
// unlike sequential_mode, we actually know the row_count at the BEGINning
globals.raw_set(QSV_V_IDX, 0)?;
globals.raw_set(QSV_V_INDEX, 0)?;
globals.raw_set(QSV_V_ROWCOUNT, row_count)?;
globals.raw_set(QSV_V_LASTROW, row_count - 1)?;
if !begin_script.is_empty() {
info!(
"Compiling and executing BEGIN script. _ROWCOUNT: {row_count} _LASTROW: {}",
row_count - 1
);
Stage::Begin.set_current();