haz-cli 0.2.0

Command-line task runner: tracks task DAGs across a workspace of projects, executes them with caching.
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
449
//! `haz query` per `QRY-001`..`QRY-009`.
//!
//! Read-only enumeration of tasks under a boolean filter
//! language. The executor:
//!
//! 1. Loads the workspace and its validated task graph
//!    (`DISC-001..DISC-009`, `DAG-001..DAG-018`).
//! 2. Resolves the bearing project from cwd per `EXEC-022`.
//! 3. Parses each supplied filter expression through
//!    [`haz_query_lang::parser::parse`] and lifts every atom to
//!    its typed form (`TagName`, `ProjectName`, `TaskName`,
//!    `PathPattern`, or `RelationalAtom`) via the appropriate
//!    `haz_query::expr::*` helper.
//! 4. Assembles a [`QuerySpec`] and invokes
//!    [`haz_query::engine::execute`].
//! 5. Renders the matching task identities in canonical
//!    `(ProjectName, TaskName)` order per `QRY-007`. Plain output
//!    is one `<project>:<task>` line per match (`QRY-008`); JSON
//!    output is a single array of objects with `project`, `task`,
//!    and `tags` fields.

use std::io::{self, Write};

use haz_domain::task_id::TaskId;
use haz_domain::workspace::Workspace;
use haz_query::engine::execute as engine_execute;
use haz_query::engine::spec::QuerySpec;
use haz_query::expr::atom::AtomError;
use haz_query::expr::identifier::{parse_project_atom, parse_tag_atom, parse_task_atom};
use haz_query::expr::path::parse_path_pattern_atom;
use haz_query::expr::relational::parse_relational_atom;
use haz_query::expr::shortcut::BooleanShortcut;
use haz_query_lang::expr::{Expr, RawAtom};
use haz_query_lang::parser;
use miette::{IntoDiagnostic, Result, WrapErr, miette};

use crate::cli::{FieldPresence, OutputFormat, QueryArgs};
use crate::context::Context;

/// Execute `haz query` against `cwd`.
///
/// Returns `0` on a successful enumeration, regardless of how
/// many tasks the selection contains (including zero) per
/// `QRY-009`.
///
/// # Errors
///
/// Returns a [`miette::Report`] for workspace-load failures, for
/// any filter-expression parse error (malformed boolean grammar,
/// rejected atom value, unknown relational kind), and for
/// engine-side errors (canonicalisation regression, glob-glob
/// intersection failure). All map to the
/// internal-or-configuration-error exit class per `QRY-009`.
pub fn execute(args: &QueryArgs, ctx: &Context) -> Result<i32> {
    let bearing = ctx.bearing().cloned();

    let spec = build_query_spec(args)?;
    let selected = engine_execute(ctx.workspace(), ctx.graph(), bearing.as_ref(), &spec)
        .map_err(|e| miette!("query engine failed: {e}"))?;

    let mut out = io::stdout().lock();
    match args.format {
        OutputFormat::Plain => render_plain(&selected, &mut out),
        OutputFormat::Json => render_json(&selected, ctx.workspace(), &mut out),
    }
    .into_diagnostic()
    .wrap_err("failed to write query output")?;

    Ok(0)
}

/// Translate the CLI's [`QueryArgs`] into a typed [`QuerySpec`].
///
/// Each filter expression is parsed by the language parser and
/// then `try_map`ped to its typed-atom form. Any parse or lift
/// failure is surfaced as a `miette` diagnostic that names the
/// offending flag and the offending atom.
fn build_query_spec(args: &QueryArgs) -> Result<QuerySpec> {
    let tags = parse_typed_expr(args.tags.as_deref(), "--tags", parse_tag_atom)?;
    let projects = parse_typed_expr(args.projects.as_deref(), "--projects", parse_project_atom)?;
    let tasks = parse_typed_expr(args.tasks.as_deref(), "--tasks", parse_task_atom)?;
    let inputs = parse_typed_expr(args.inputs.as_deref(), "--inputs", parse_path_pattern_atom)?;
    let outputs = parse_typed_expr(
        args.outputs.as_deref(),
        "--outputs",
        parse_path_pattern_atom,
    )?;
    let child_of = parse_typed_expr(
        args.child_of.as_deref(),
        "--child-of",
        parse_relational_atom,
    )?;
    let parent_of = parse_typed_expr(
        args.parent_of.as_deref(),
        "--parent-of",
        parse_relational_atom,
    )?;
    let depends_on = parse_typed_expr(
        args.depends_on.as_deref(),
        "--depends-on",
        parse_relational_atom,
    )?;
    let ancestor_of = parse_typed_expr(
        args.ancestor_of.as_deref(),
        "--ancestor-of",
        parse_relational_atom,
    )?;

    let shortcuts = collect_shortcuts(args);

    Ok(QuerySpec {
        tags,
        projects,
        tasks,
        inputs,
        outputs,
        child_of,
        parent_of,
        depends_on,
        ancestor_of,
        shortcuts,
    })
}

/// Parse `raw` (when present) as a boolean expression and lift
/// every atom via `lift`.
///
/// The `flag` argument is the CLI flag name (e.g. `"--tags"`),
/// included verbatim in any diagnostic the function surfaces so
/// the user can locate the offending input.
fn parse_typed_expr<A, F>(raw: Option<&str>, flag: &str, lift: F) -> Result<Option<Expr<A>>>
where
    F: FnMut(RawAtom) -> Result<A, AtomError>,
{
    let Some(s) = raw else {
        return Ok(None);
    };
    let parsed =
        parser::parse(s).map_err(|e| miette!("{flag}: failed to parse expression `{s}`: {e}"))?;
    let typed = parsed
        .try_map(lift)
        .map_err(|e| miette!("{flag}: invalid atom in `{s}`: {e}"))?;
    Ok(Some(typed))
}

/// Map every supplied `QRY-005` shortcut to its
/// [`BooleanShortcut`] form. The CLI's tri-state
/// [`FieldPresence`] keeps the intra-pair mutex
/// (`--has-X` vs `--no-X`) impossible-to-represent, so this
/// function is a total mapping over the three policy fields plus
/// the `--mutex` switch.
fn collect_shortcuts(args: &QueryArgs) -> Vec<BooleanShortcut> {
    let mut shortcuts: Vec<BooleanShortcut> = Vec::new();
    match args.deps_presence {
        FieldPresence::Any => {}
        FieldPresence::NonEmpty => shortcuts.push(BooleanShortcut::HasDeps),
        FieldPresence::Empty => shortcuts.push(BooleanShortcut::NoDeps),
    }
    match args.inputs_presence {
        FieldPresence::Any => {}
        FieldPresence::NonEmpty => shortcuts.push(BooleanShortcut::HasInputs),
        FieldPresence::Empty => shortcuts.push(BooleanShortcut::NoInputs),
    }
    match args.outputs_presence {
        FieldPresence::Any => {}
        FieldPresence::NonEmpty => shortcuts.push(BooleanShortcut::HasOutputs),
        FieldPresence::Empty => shortcuts.push(BooleanShortcut::NoOutputs),
    }
    if args.mutex {
        shortcuts.push(BooleanShortcut::Mutex);
    }
    shortcuts
}

/// `QRY-008` plain-format output: one `<project>:<task>` line per
/// match, no header / footer / count. Zero matches produces zero
/// output lines.
fn render_plain(selected: &[TaskId], out: &mut impl Write) -> io::Result<()> {
    for id in selected {
        writeln!(out, "{id}")?;
    }
    Ok(())
}

/// `QRY-008` JSON-format output: a single JSON array of objects
/// each carrying `project`, `task`, and `tags` (an array of the
/// task's owning project's tag names, sorted via `BTreeSet`).
fn render_json(selected: &[TaskId], workspace: &Workspace, out: &mut impl Write) -> io::Result<()> {
    let array: Vec<serde_json::Value> = selected
        .iter()
        .map(|id| json_object_for(id, workspace))
        .collect();
    let serialised = serde_json::to_string(&serde_json::Value::Array(array))
        .expect("JSON serialisation of an array of identifier strings cannot fail");
    writeln!(out, "{serialised}")
}

fn json_object_for(id: &TaskId, workspace: &Workspace) -> serde_json::Value {
    let tags: Vec<String> = workspace
        .projects
        .get(&id.project)
        .map(|p| p.tags.iter().map(ToString::to_string).collect())
        .unwrap_or_default();
    serde_json::json!({
        "project": id.project.to_string(),
        "task": id.task.to_string(),
        "tags": tags,
    })
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::Path;
    use std::str::FromStr;

    use haz_domain::name::{ProjectName, TaskName};
    use haz_domain::task_id::TaskId;

    use super::{build_query_spec, execute, render_json, render_plain};
    use crate::cli::QueryArgs;
    use crate::context::Context;
    use miette::Result;

    fn write_file(path: &Path, contents: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, contents).unwrap();
    }

    /// Mimic the dispatch sequence for `haz query`: open the
    /// Context against `cwd`, then execute.
    fn run_query(args: &QueryArgs, cwd: &Path) -> Result<i32> {
        let ctx = Context::open(cwd)?;
        execute(args, &ctx)
    }

    /// Two-project workspace: `lib` has a `build` task and a
    /// `test` task that depends on `build`. `web` has `bundle`
    /// that depends on `lib:build`.
    fn two_project_workspace(root: &Path) {
        write_file(
            &root.join(".haz/workspace.yml"),
            "projects:\n  - /lib\n  - /web\n",
        );
        write_file(
            &root.join("lib/haz.yml"),
            "name: lib\ntags:\n  - backend\ntasks:\n  build:\n    command: [\"true\"]\n  test:\n    command: [\"true\"]\n    deps:\n      - ~:build\n",
        );
        write_file(
            &root.join("web/haz.yml"),
            "name: web\ntags:\n  - frontend\ntasks:\n  bundle:\n    command: [\"true\"]\n    deps:\n      - lib:build\n",
        );
    }

    // ---- build_query_spec ------------------------------------

    #[test]
    fn build_query_spec_returns_default_when_no_filters_set() {
        let args = QueryArgs::default();
        let spec = build_query_spec(&args).unwrap();
        assert!(spec.tags.is_none());
        assert!(spec.projects.is_none());
        assert!(spec.tasks.is_none());
        assert!(spec.inputs.is_none());
        assert!(spec.outputs.is_none());
        assert!(spec.child_of.is_none());
        assert!(spec.parent_of.is_none());
        assert!(spec.depends_on.is_none());
        assert!(spec.ancestor_of.is_none());
        assert!(spec.shortcuts.is_empty());
    }

    #[test]
    fn build_query_spec_lifts_tag_expression() {
        let args = QueryArgs {
            tags: Some("backend".to_owned()),
            ..QueryArgs::default()
        };
        let spec = build_query_spec(&args).unwrap();
        assert!(spec.tags.is_some());
    }

    #[test]
    fn build_query_spec_rejects_malformed_expression() {
        let args = QueryArgs {
            tags: Some("backend &".to_owned()),
            ..QueryArgs::default()
        };
        let err = build_query_spec(&args).unwrap_err();
        let rendered = format!("{err}");
        assert!(
            rendered.contains("--tags"),
            "diagnostic should name the flag: {rendered}",
        );
    }

    #[test]
    fn build_query_spec_rejects_invalid_atom_in_relational() {
        // `name:` lacks the value half of the kind:value shape.
        let args = QueryArgs {
            child_of: Some("name:".to_owned()),
            ..QueryArgs::default()
        };
        let err = build_query_spec(&args).unwrap_err();
        let rendered = format!("{err}");
        assert!(
            rendered.contains("--child-of"),
            "diagnostic should name the flag: {rendered}",
        );
    }

    #[test]
    fn build_query_spec_collects_every_supplied_shortcut() {
        use crate::cli::FieldPresence;
        let args = QueryArgs {
            deps_presence: FieldPresence::NonEmpty,
            inputs_presence: FieldPresence::Empty,
            mutex: true,
            ..QueryArgs::default()
        };
        let spec = build_query_spec(&args).unwrap();
        assert_eq!(spec.shortcuts.len(), 3);
    }

    // ---- render_plain ----------------------------------------

    #[test]
    fn render_plain_emits_one_line_per_task_id() {
        let ids = vec![
            TaskId {
                project: ProjectName::from_str("lib").unwrap(),
                task: TaskName::from_str("build").unwrap(),
            },
            TaskId {
                project: ProjectName::from_str("web").unwrap(),
                task: TaskName::from_str("bundle").unwrap(),
            },
        ];
        let mut out = Vec::<u8>::new();
        render_plain(&ids, &mut out).unwrap();
        assert_eq!(String::from_utf8(out).unwrap(), "lib:build\nweb:bundle\n",);
    }

    #[test]
    fn render_plain_emits_no_output_for_empty_selection() {
        let mut out = Vec::<u8>::new();
        render_plain(&[], &mut out).unwrap();
        assert!(out.is_empty(), "QRY-008 zero matches => zero lines");
    }

    // ---- render_json -----------------------------------------

    #[test]
    fn render_json_emits_array_with_required_fields() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        two_project_workspace(root);
        let (workspace, _graph) = crate::workspace_load::load_workspace(root).unwrap();

        let ids = vec![TaskId {
            project: ProjectName::from_str("lib").unwrap(),
            task: TaskName::from_str("build").unwrap(),
        }];
        let mut out = Vec::<u8>::new();
        render_json(&ids, &workspace, &mut out).unwrap();
        let rendered = String::from_utf8(out).unwrap();
        let value: serde_json::Value = serde_json::from_str(rendered.trim()).unwrap();
        let arr = value.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["project"], "lib");
        assert_eq!(arr[0]["task"], "build");
        assert_eq!(arr[0]["tags"], serde_json::json!(["backend"]));
    }

    #[test]
    fn render_json_emits_empty_array_for_empty_selection() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        two_project_workspace(root);
        let (workspace, _graph) = crate::workspace_load::load_workspace(root).unwrap();

        let mut out = Vec::<u8>::new();
        render_json(&[], &workspace, &mut out).unwrap();
        assert_eq!(out, b"[]\n");
    }

    // ---- execute (end-to-end) --------------------------------

    #[test]
    fn execute_with_empty_filters_lists_every_task_under_workspace() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        two_project_workspace(root);
        let args = QueryArgs::default();
        // cwd at workspace root: no bearing, full candidate set.
        let code = run_query(&args, root).unwrap();
        assert_eq!(code, 0);
    }

    #[test]
    fn execute_with_tags_filter_returns_zero_on_no_match() {
        // QRY-009: success regardless of how many tasks the
        // selection contains.
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        two_project_workspace(root);
        let args = QueryArgs {
            tags: Some("nonexistent".to_owned()),
            ..QueryArgs::default()
        };
        let code = run_query(&args, root).unwrap();
        assert_eq!(code, 0);
    }

    #[test]
    fn execute_rejects_malformed_filter_expression() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        two_project_workspace(root);
        let args = QueryArgs {
            projects: Some("(unclosed".to_owned()),
            ..QueryArgs::default()
        };
        let err = run_query(&args, root).unwrap_err();
        let rendered = format!("{err}");
        assert!(
            rendered.contains("--projects"),
            "diagnostic should name the offending flag: {rendered}",
        );
    }

    #[test]
    fn execute_with_relational_filter_uses_graph_edges() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        two_project_workspace(root);
        // child-of name:build => tasks whose deps directly name a
        // `build` task. In the fixture, `lib:test` depends on
        // `lib:build`, and `web:bundle` depends on `lib:build`.
        let args = QueryArgs {
            child_of: Some("name:build".to_owned()),
            ..QueryArgs::default()
        };
        let code = run_query(&args, root).unwrap();
        assert_eq!(code, 0);
    }
}