oxo-flow-cli 0.6.1

CLI for the oxo-flow bioinformatics pipeline engine
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
use anyhow::{Context, Result};
use colored::Colorize;
use oxo_flow_core::config::WorkflowConfig;
use oxo_flow_core::dag::WorkflowDag;
use std::path::{Path, PathBuf};

use crate::commands::print_banner;

pub fn validate_command(workflow: PathBuf, as_include: bool) -> Result<()> {
    let config_res = WorkflowConfig::from_file(&workflow);
    match config_res {
        Ok(cfg) => {
            if cfg.rules.is_empty() {
                eprintln!("{} {} — 0 rules", "".green().bold(), workflow.display());
                eprintln!(
                    "  {} Workflow has no rules. Add [[rules]] sections to define pipeline steps.",
                    "⚠ Warning:".yellow().bold()
                );
                return Ok(());
            }

            // Run semantic validation (E001-E008)
            let validation = oxo_flow_core::format::validate_format(&cfg);
            let mut error_count = 0usize;

            for d in &validation.diagnostics {
                if d.severity == oxo_flow_core::format::Severity::Error {
                    error_count += 1;
                    eprintln!("  {} [{}]: {}", "error".red().bold(), d.code, d.message);
                    if let Some(ref rule) = d.rule {
                        eprintln!("    rule: {}", rule);
                    }
                    if let Some(ref suggestion) = d.suggestion {
                        eprintln!("    hint: {}", suggestion);
                    }
                }
            }

            // Check for missing input files (skip for --as-include)
            let mut missing_inputs = Vec::new();
            if !as_include {
                for rule in &cfg.rules {
                    for input in &rule.input {
                        // Only check if it's not a wildcard path and doesn't exist
                        if !input.contains('{')
                            && !input.contains('}')
                            && !Path::new(input).exists()
                        {
                            // Also check if it's an output of another rule
                            let is_generated =
                                cfg.rules.iter().any(|r| r.output.to_vec().contains(input));

                            if !is_generated {
                                missing_inputs.push(input);
                            }
                        }
                    }
                }
            }

            // Validate DAG construction (skip for --as-include)
            if as_include {
                // For sub-workflow fragments, skip DAG validation
                if error_count == 0 {
                    eprintln!(
                        "{} {}{} rules (fragment validation)",
                        "".green().bold(),
                        workflow.display(),
                        cfg.rules.len()
                    );
                } else {
                    eprintln!(
                        "{} {}{} validation error(s)",
                        "".red().bold(),
                        workflow.display(),
                        error_count
                    );
                }
            } else {
                match WorkflowDag::from_rules(&cfg.rules) {
                    Ok(dag) => {
                        if error_count == 0 {
                            eprintln!(
                                "{} {}{} rules, {} dependencies",
                                "".green().bold(),
                                workflow.display(),
                                dag.node_count(),
                                dag.edge_count()
                            );
                        } else {
                            eprintln!(
                                "{} {}{} validation error(s)",
                                "".red().bold(),
                                workflow.display(),
                                error_count
                            );
                        }

                        if !missing_inputs.is_empty() {
                            eprintln!(
                                "\n  {} The following input files do not exist:",
                                "⚠ Warning:".yellow().bold()
                            );
                            for input in missing_inputs {
                                eprintln!("    - {}", input);
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!(
                            "{} {} — DAG error: {}",
                            "".red().bold(),
                            workflow.display(),
                            e
                        );
                        std::process::exit(1);
                    }
                }
            }

            // Exit with error if validation failed
            if error_count > 0 {
                std::process::exit(1);
            }
        }
        Err(e) => {
            eprintln!("{} {}{}", "".red().bold(), workflow.display(), e);
            std::process::exit(1);
        }
    }
    Ok(())
}

pub fn lint_command(workflow: PathBuf, strict: bool) -> Result<()> {
    print_banner();
    let config = WorkflowConfig::from_file(&workflow)
        .with_context(|| format!("failed to parse {}", workflow.display()))?;

    let validation = oxo_flow_core::format::validate_format(&config);
    let lint_diags = oxo_flow_core::format::lint_format(&config);

    // Read the raw file content for secret scanning
    let raw_content = std::fs::read_to_string(&workflow).ok();
    let secret_diags = if let Some(content) = raw_content {
        oxo_flow_core::format::scan_for_secrets(&content)
    } else {
        Vec::new()
    };

    let mut error_count = 0usize;
    let mut warning_count = 0usize;
    let mut info_count = 0usize;

    for d in validation
        .diagnostics
        .iter()
        .chain(lint_diags.iter())
        .chain(secret_diags.iter())
    {
        let prefix = match d.severity {
            oxo_flow_core::format::Severity::Error => {
                error_count += 1;
                "error".red().bold().to_string()
            }
            oxo_flow_core::format::Severity::Warning => {
                warning_count += 1;
                "warning".yellow().bold().to_string()
            }
            oxo_flow_core::format::Severity::Info => {
                info_count += 1;
                "info".blue().to_string()
            }
        };
        eprint!("  {} [{}]: {}", prefix, d.code, d.message);
        if let Some(ref rule) = d.rule {
            eprint!(" (rule: {})", rule);
        }
        eprintln!();
    }

    eprintln!(
        "\n{} {} error(s), {} warning(s), {} info",
        "Summary:".bold(),
        error_count,
        warning_count,
        info_count
    );

    if error_count > 0 || (strict && warning_count > 0) {
        std::process::exit(1);
    }
    Ok(())
}

pub fn format_command(workflow: PathBuf, output: Option<PathBuf>, check: bool) -> Result<()> {
    let config = WorkflowConfig::from_file(&workflow)
        .with_context(|| format!("failed to parse {}", workflow.display()))?;

    let formatted = oxo_flow_core::format::format_workflow(&config);

    if check {
        let original = std::fs::read_to_string(&workflow)?;
        if original.trim() == formatted.trim() {
            eprintln!(
                "{} {} is already formatted",
                "".green().bold(),
                workflow.display()
            );
        } else {
            eprintln!(
                "{} {} needs formatting",
                "".red().bold(),
                workflow.display()
            );
            std::process::exit(1);
        }
    } else {
        match output {
            Some(path) => {
                std::fs::write(&path, &formatted)?;
                eprintln!("Formatted workflow written to {}", path.display());
            }
            None => {
                print!("{formatted}");
            }
        }
    }
    Ok(())
}

pub fn touch_command(workflow: PathBuf, rules: Vec<String>) -> Result<()> {
    print_banner();
    let config = WorkflowConfig::from_file(&workflow)
        .with_context(|| format!("failed to parse {}", workflow.display()))?;

    let rules_to_touch: Vec<&oxo_flow_core::rule::Rule> = if rules.is_empty() {
        config.rules.iter().collect()
    } else {
        config
            .rules
            .iter()
            .filter(|r| rules.contains(&r.name))
            .collect()
    };

    let mut touched = 0usize;
    let mut skipped = 0usize;

    let base_dir = std::env::current_dir().unwrap_or_default();

    for rule in &rules_to_touch {
        for output in &rule.output {
            let has_wildcard = output.contains('{') && output.contains('}');
            if has_wildcard {
                skipped += 1;
                continue;
            }

            // Path safety: reject path traversal and absolute paths
            if output.contains("..") || output.starts_with('/') || output.starts_with('~') {
                eprintln!("  {} {} (rejected: unsafe path)", "".red().bold(), output);
                continue;
            }

            let path = base_dir.join(output);
            if path.exists() {
                // Update modification time
                match filetime::set_file_mtime(&path, filetime::FileTime::now()) {
                    Ok(()) => {
                        touched += 1;
                        eprintln!("  {} {}", "".green(), output);
                    }
                    Err(e) => {
                        eprintln!("  {} {} ({})", "".red(), output, e);
                    }
                }
            } else {
                // Create empty file to mark as "done"
                if let Some(parent) = path.parent()
                    && let Err(e) = std::fs::create_dir_all(parent)
                {
                    eprintln!(
                        "  {} {} (cannot create directory: {})",
                        "".red(),
                        output,
                        e
                    );
                    continue;
                }
                match std::fs::write(&path, "") {
                    Ok(()) => {
                        touched += 1;
                        eprintln!("  {} {} (created)", "".green(), output);
                    }
                    Err(e) => {
                        eprintln!("  {} {} (failed: {})", "".red(), output, e);
                    }
                }
            }
        }
    }

    eprintln!(
        "\n{} {} file(s) touched, {} wildcard patterns skipped",
        "Done:".bold(),
        touched,
        skipped
    );
    Ok(())
}

pub async fn watch_command(workflow: PathBuf, auto_run: bool, jobs: usize) -> Result<()> {
    print_banner();

    let workflow_path =
        std::path::absolute(&workflow).context("failed to resolve workflow path")?;

    if !workflow_path.exists() {
        eprintln!(
            "{} Workflow file not found: {}",
            "error:".bold().red(),
            workflow_path.display()
        );
        std::process::exit(1);
    }

    eprintln!(
        "{} {} for changes...",
        "Watching".bold().cyan(),
        workflow_path.display()
    );
    eprintln!("  Press Ctrl+C to stop.");

    let mut last_mtime = std::fs::metadata(&workflow_path)
        .and_then(|m| m.modified())
        .ok();

    loop {
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;

        let current_mtime = std::fs::metadata(&workflow_path)
            .and_then(|m| m.modified())
            .ok();

        let changed = match (last_mtime, current_mtime) {
            (Some(last), Some(current)) => current != last,
            _ => false,
        };

        if changed {
            eprintln!(
                "\n{} Change detected, re-validating...",
                "Change detected:".bold().green()
            );

            // Run validate + optional dry-run/run for quick feedback
            match validate_command(workflow_path.clone(), false) {
                Ok(()) => {
                    if auto_run {
                        eprintln!();
                        let _ = crate::commands::run::run_command(
                            Some(workflow_path.clone()),
                            jobs,
                            false,           // keep_going
                            None,            // workdir
                            vec![],          // target
                            0,               // retry
                            "0".to_string(), // timeout
                            false,           // resume_failed
                            None,            // profile
                            0,               // max_threads
                            0,               // max_memory
                            false,           // skip_env_setup
                            None,            // cache_dir
                            false,           // provenance
                        )
                        .await;
                    } else {
                        // Dry-run to show execution plan
                        eprintln!();
                        let _ = crate::commands::run::dry_run_command(
                            Some(workflow_path.clone()),
                            vec![],
                            false,
                        )
                        .await;
                    }
                    eprintln!();
                }
                Err(e) => {
                    eprintln!("  validation error: {}\n", e);
                }
            }

            // Run lint
            match lint_command(workflow_path.clone(), false) {
                Ok(()) => {
                    eprintln!();
                }
                Err(e) => {
                    eprintln!("  lint error: {}\n", e);
                }
            }

            eprintln!(
                "{} {} for changes...",
                "Watching".bold().cyan(),
                workflow_path.display()
            );
            last_mtime = current_mtime;
        }
    }
}

#[cfg(test)]
mod tests {
    use assert_cmd::Command;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_as_include_skips_dag_validation() {
        // Create a fragment with rules that reference undefined inputs
        let fragment = r#"
[workflow]
name = "qc-fragment"

[[rules]]
name = "fastqc"
input = ["{sample}.fastq"]
output = ["{sample}_fastqc.html"]
shell = "fastqc {input}"
"#;
        let mut file = NamedTempFile::with_suffix(".oxoflow").unwrap();
        file.write_all(fragment.as_bytes()).unwrap();

        // Should pass with --as-include (skips DAG validation)
        Command::cargo_bin("oxo-flow")
            .unwrap()
            .arg("validate")
            .arg("--as-include")
            .arg(file.path())
            .assert()
            .success();
    }

    #[test]
    fn test_as_include_validates_syntax() {
        // Create an invalid fragment (missing required 'name' field)
        let fragment = r#"
[workflow]
name = "bad-fragment"

[[rules]]
# Missing required 'name' field
input = ["test.txt"]
"#;
        let mut file = NamedTempFile::with_suffix(".oxoflow").unwrap();
        file.write_all(fragment.as_bytes()).unwrap();

        // Should fail even with --as-include (syntax errors)
        Command::cargo_bin("oxo-flow")
            .unwrap()
            .arg("validate")
            .arg("--as-include")
            .arg(file.path())
            .assert()
            .failure();
    }
}