razel 0.5.7

a command executor with caching for data processing pipelines
Documentation
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
use anyhow::bail;
use clap::{Args, Parser, Subcommand};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use url::Url;

use crate::executors::HttpRemoteExecConfig;
use crate::metadata::Tag;
use crate::razel_jsonl::parse_jsonl_file;
use crate::tasks::DownloadFileTask;
use crate::{parse_batch_file, parse_command, tasks, CommandBuilder, FileType, Razel};

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
#[clap(infer_subcommands = true)]
struct Cli {
    #[clap(subcommand)]
    command: CliCommands,
}

#[derive(Subcommand, Debug)]
enum CliCommands {
    /// Execute a custom command
    Command {
        #[clap(last = true, required = true)]
        command: Vec<String>,
    },
    /// Execute a single task
    #[clap(subcommand)]
    Task(CliTasks),
    /// Execute commands from a razel.jsonl or batch file
    #[clap(visible_alias = "build", visible_alias = "test")]
    Exec(Exec),
    /// List commands from a razel.jsonl or batch file
    #[clap(visible_alias = "ls", visible_alias = "show-only")]
    ListCommands {
        /// File with commands to list
        #[clap(short, long, default_value = "razel.jsonl")]
        file: String,
        #[clap(flatten)]
        filter_args: FilterArgs,
    },
    /// Import commands from files and create razel.jsonl
    Import {
        /// razel.jsonl file to create
        #[clap(short, long, default_value = "razel.jsonl")]
        output: PathBuf,
        /// Input files to parse commands from
        #[clap(required = true)]
        files: Vec<String>,
    },
    /// Subcommands for Razel system management
    #[clap(subcommand)]
    System(SystemCommand),
    // TODO add Debug subcommand
    // TODO add upgrade subcommand
}

#[derive(Args, Debug)]
struct Exec {
    /// File with commands to execute
    #[clap(short, long, default_value = "razel.jsonl")]
    file: String,
    #[clap(flatten)]
    run_args: RunArgs,
    #[clap(flatten)]
    filter_args: FilterArgs,
}

#[derive(Args, Debug)]
pub struct RunArgs {
    /// No execution, just show info about configuration, cache, ...
    #[clap(short, long)]
    pub info: bool,
    /// No execution, just list commands
    #[clap(short, long, visible_alias = "ls")]
    pub no_execution: bool,
    /// Do not stop on first failure
    #[clap(short, long, visible_alias = "keep-running")]
    pub keep_going: bool,
    /// Show verbose output
    #[clap(short, long)]
    pub verbose: bool,
    /// Prefix of tags to group the report
    #[clap(long, default_value = "group")]
    pub group_by_tag: String,
    /// Local cache directory (use --info to show default value)
    #[clap(long, env = "RAZEL_CACHE_DIR")]
    pub cache_dir: Option<PathBuf>,
    /// Comma seperated list of remote cache URLs
    #[clap(long, env = "RAZEL_REMOTE_CACHE", value_delimiter = ',')]
    pub remote_cache: Vec<String>,
    /// Only cache commands with: output size / exec time < threshold [kilobyte / s]
    #[clap(long, env = "RAZEL_REMOTE_CACHE_THRESHOLD")]
    pub remote_cache_threshold: Option<u32>,
    /// Http remote execution configuration
    #[clap(long, env = "RAZEL_HTTP_REMOTE_EXEC")]
    pub http_remote_exec: Option<HttpRemoteExecConfig>,
}

impl Default for RunArgs {
    fn default() -> Self {
        Self {
            info: false,
            no_execution: false,
            keep_going: false,
            verbose: true,
            group_by_tag: "group".to_string(),
            cache_dir: None,
            remote_cache: vec![],
            remote_cache_threshold: None,
            http_remote_exec: None,
        }
    }
}

#[derive(Args, Debug)]
#[group(multiple = false)]
pub struct FilterArgs {
    /// Filter commands by name or output file
    pub targets: Vec<String>,
    /// Filter commands by name or output file, include commands matching any pattern
    #[clap(short = 'r', long, num_args = 1..)]
    pub filter_regex: Vec<String>,
    /// Filter commands by name or output file, include commands matching all patterns
    #[clap(short = 'a', long, num_args = 1..)]
    pub filter_regex_all: Vec<String>,
    // TODO Filter commands by tags
    //#[clap(short = 't', long, num_args = 1..)]
    //pub filter_tags: Vec<String>,
}

#[derive(Subcommand, Debug)]
enum SystemCommand {
    /// Check remote cache availability
    CheckRemoteCache {
        /// Comma seperated list of remote cache URLs
        #[clap(env = "RAZEL_REMOTE_CACHE", value_delimiter = ',', required = true)]
        urls: Vec<String>,
    },
}

#[derive(Subcommand, Debug)]
enum CliTasks {
    /// Write a value captured with a regex to a file
    CaptureRegex(CaptureRegexTask),
    /// Concatenate multiple csv files - headers must match
    CsvConcat(CsvConcatTask),
    /// Filter a csv file - keeping only the specified cols
    CsvFilter(CsvFilterTask),
    /// Write a text file
    WriteFile(WriteFileTask),
    /// Download a file
    DownloadFile(DownloadFileTaskBuilder),
    /// Ensure that two files are equal
    EnsureEqual(EnsureEqualTask),
    /// Ensure that two files are not equal
    EnsureNotEqual(EnsureNotEqualTask),
    /// Post a HTTP multipart form for remote execution
    HttpRemoteExec(HttpRemoteExecTask),
}

impl CliTasks {
    pub fn build_command(
        self,
        razel: &mut Razel,
        name: String,
        args: Vec<String>,
        tags: Vec<Tag>,
    ) -> Result<(), anyhow::Error> {
        let mut builder = CommandBuilder::new(name, args, tags);
        match self {
            CliTasks::CaptureRegex(x) => x.build(&mut builder, razel),
            CliTasks::CsvConcat(x) => x.build(&mut builder, razel),
            CliTasks::CsvFilter(x) => x.build(&mut builder, razel),
            CliTasks::WriteFile(x) => x.build(&mut builder, razel),
            CliTasks::DownloadFile(x) => x.build(&mut builder, razel),
            CliTasks::EnsureEqual(x) => x.build(&mut builder, razel),
            CliTasks::EnsureNotEqual(x) => x.build(&mut builder, razel),
            CliTasks::HttpRemoteExec(x) => x.build(&mut builder, razel),
        }?;
        razel.push(builder)?;
        Ok(())
    }
}

trait TaskBuilder {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error>;
}

#[derive(Args, Debug)]
struct CaptureRegexTask {
    /// Input file to read
    input: String,
    /// File to write the captured value to
    output: String,
    /// Regex containing a single capturing group
    regex: String,
}

impl TaskBuilder for CaptureRegexTask {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error> {
        let input = builder.input(&self.input, razel)?;
        let output = builder.output(&self.output, FileType::OutputFile, razel)?;
        builder.blocking_task_executor(Arc::new(move || {
            tasks::capture_regex(input.clone(), output.clone(), self.regex.clone())
        }));
        Ok(())
    }
}

#[derive(Args, Debug)]
struct CsvConcatTask {
    /// Input csv files
    #[clap(required = true)]
    input: Vec<String>,
    /// Concatenated file to create
    output: String,
}

impl TaskBuilder for CsvConcatTask {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error> {
        let inputs = builder.inputs(&self.input, razel)?;
        let output = builder.output(&self.output, FileType::OutputFile, razel)?;
        builder.blocking_task_executor(Arc::new(move || {
            tasks::csv_concat(inputs.clone(), output.clone())
        }));
        Ok(())
    }
}

#[derive(Args, Debug)]
struct CsvFilterTask {
    #[clap(short, long)]
    input: String,
    #[clap(short, long)]
    output: String,
    /// Col names to keep - all other cols are dropped
    #[clap(short, long = "col", num_args = 0..)]
    cols: Vec<String>,
}

impl TaskBuilder for CsvFilterTask {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error> {
        let input = builder.input(&self.input, razel)?;
        let output = builder.output(&self.output, FileType::OutputFile, razel)?;
        builder.blocking_task_executor(Arc::new(move || {
            tasks::csv_filter(input.clone(), output.clone(), self.cols.clone())
        }));
        Ok(())
    }
}

#[derive(Args, Debug)]
struct WriteFileTask {
    /// File to create
    file: String,
    /// Lines to write
    lines: Vec<String>,
}

impl TaskBuilder for WriteFileTask {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error> {
        let output = builder.output(&self.file, FileType::OutputFile, razel)?;
        builder.blocking_task_executor(Arc::new(move || {
            tasks::write_file(output.clone(), self.lines.clone())
        }));
        Ok(())
    }
}

#[derive(Args, Debug)]
struct DownloadFileTaskBuilder {
    #[clap(short, long)]
    url: String,
    #[clap(short, long)]
    output: String,
    #[clap(short, long)]
    executable: bool,
}

impl TaskBuilder for DownloadFileTaskBuilder {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error> {
        let file_type = if self.executable {
            FileType::ExecutableInWorkspace
        } else {
            FileType::OutputFile
        };
        let output = builder.output(&self.output, file_type, razel)?;
        builder.async_task_executor(DownloadFileTask {
            url: self.url,
            output,
            executable: self.executable,
        });
        Ok(())
    }
}

#[derive(Args, Debug)]
struct EnsureEqualTask {
    file1: String,
    file2: String,
}

impl TaskBuilder for EnsureEqualTask {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error> {
        let file1 = builder.input(&self.file1, razel)?;
        let file2 = builder.input(&self.file2, razel)?;
        builder.blocking_task_executor(Arc::new(move || {
            tasks::ensure_equal(file1.clone(), file2.clone())
        }));
        Ok(())
    }
}

#[derive(Args, Debug)]
struct EnsureNotEqualTask {
    file1: String,
    file2: String,
}

impl TaskBuilder for EnsureNotEqualTask {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error> {
        let file1 = builder.input(&self.file1, razel)?;
        let file2 = builder.input(&self.file2, razel)?;
        builder.blocking_task_executor(Arc::new(move || {
            tasks::ensure_not_equal(file1.clone(), file2.clone())
        }));
        Ok(())
    }
}

#[derive(Args, Debug)]
struct HttpRemoteExecTask {
    /// url for HTTP multipart form POST
    #[clap(short, long)]
    url: Url,
    /// files to attach to the form
    #[clap(short, long)]
    files: Vec<String>,
    /// file names to use in the form
    #[clap(short = 'n', long)]
    file_names: Vec<String>,
}

impl TaskBuilder for HttpRemoteExecTask {
    fn build(self, builder: &mut CommandBuilder, razel: &mut Razel) -> Result<(), anyhow::Error> {
        if self.file_names.len() != self.files.len() {
            bail!("number of file names and files must be equal");
        }
        let state = razel.http_remote_exec(&self.url);
        let mut files = Vec::with_capacity(self.files.len());
        for (i, name) in self.file_names.into_iter().enumerate() {
            let file = builder.input(&self.files[i], razel)?;
            files.push((name, file));
        }
        builder.http_remote_executor(state, self.url, files);
        Ok(())
    }
}

pub async fn parse_cli(
    args: Vec<String>,
    razel: &mut Razel,
) -> Result<Option<RunArgs>, anyhow::Error> {
    let cli = Cli::parse_from(args.iter());
    Ok(match cli.command {
        CliCommands::Command { command } => {
            parse_command(razel, command)?;
            Some(Default::default())
        }
        CliCommands::Task(task) => {
            task.build_command(razel, "task".to_string(), args, vec![])?;
            Some(Default::default())
        }
        CliCommands::Exec(exec) => {
            if let Some(x) = &exec.run_args.http_remote_exec {
                razel.set_http_remote_exec_config(x);
            }
            apply_file(razel, &exec.file)?;
            apply_filter(razel, &exec.filter_args)?;
            Some(exec.run_args)
        }
        CliCommands::ListCommands { file, filter_args } => {
            apply_file(razel, &file)?;
            apply_filter(razel, &filter_args)?;
            Some(RunArgs {
                no_execution: true,
                ..Default::default()
            })
        }
        CliCommands::Import { output, files } => {
            import(razel, &output, files)?;
            None
        }
        CliCommands::System(s) => {
            match s {
                SystemCommand::CheckRemoteCache { urls } => razel.check_remote_cache(urls).await?,
            }
            None
        }
    })
}

pub fn parse_cli_within_file(
    razel: &mut Razel,
    args: Vec<String>,
    name: &str,
    tags: Vec<Tag>,
) -> Result<(), anyhow::Error> {
    let cli = Cli::try_parse_from(args.iter())?;
    match cli.command {
        CliCommands::Command { command } => {
            parse_command(razel, command)?;
        }
        CliCommands::Task(task) => {
            task.build_command(razel, name.to_owned(), args, tags)?;
        }
        _ => bail!("Razel subcommand not allowed within files"),
    }
    Ok(())
}

fn apply_file(razel: &mut Razel, file: &String) -> Result<(), anyhow::Error> {
    match Path::new(file).extension().and_then(OsStr::to_str) {
        Some("jsonl") => parse_jsonl_file(razel, file),
        _ => parse_batch_file(razel, file),
    }
}

fn apply_filter(razel: &mut Razel, filter: &FilterArgs) -> Result<(), anyhow::Error> {
    if !filter.targets.is_empty() {
        razel.filter_targets(&filter.targets);
    } else if !filter.filter_regex.is_empty() {
        razel.filter_targets_regex(&filter.filter_regex)?;
    } else if !filter.filter_regex_all.is_empty() {
        razel.filter_targets_regex_all(&filter.filter_regex_all)?;
    }
    Ok(())
}

fn import(razel: &mut Razel, output: &Path, files: Vec<String>) -> Result<(), anyhow::Error> {
    for file in files {
        apply_file(razel, &file)?;
    }
    razel.write_jsonl(output)
}