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
//! Parser for the `haz query` subcommand.
//!
//! Owns [`QueryArgs`], the [`FieldPresence`] / [`OutputFormat`]
//! value types, the [`query_command`] parser builder, and the
//! [`presence_parser`] helper that lifts each `--has-X` / `--no-X`
//! flag pair to a tri-state [`FieldPresence`].

use bpaf::{Parser, construct, long};

/// Arguments parsed for the `haz query` subcommand.
///
/// Each filter slot stores the user's raw expression string; the
/// executor parses it through `haz_query_lang::parser` and lifts
/// each atom to its typed form via the appropriate
/// `haz_query::expr::*` helper. Storing strings here keeps the CLI
/// layer agnostic to the query language's typed-atom surface and
/// matches the convention already used for `targets` on
/// [`crate::cli::RunArgs`].
///
/// The boolean shortcuts each carry their own field; the parser
/// enforces the intra-pair mutex (`--has-X` vs `--no-X`) at parse
/// time so the executor sees at most one of each pair set.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct QueryArgs {
    /// `--tags <EXPR>` per `QRY-003`.
    pub tags: Option<String>,
    /// `--projects <EXPR>` per `QRY-003`.
    pub projects: Option<String>,
    /// `--tasks <EXPR>` per `QRY-003`.
    pub tasks: Option<String>,
    /// `--inputs <EXPR>` per `QRY-003`.
    pub inputs: Option<String>,
    /// `--outputs <EXPR>` per `QRY-003`.
    pub outputs: Option<String>,
    /// `--child-of <EXPR>` per `QRY-004`.
    pub child_of: Option<String>,
    /// `--parent-of <EXPR>` per `QRY-004`.
    pub parent_of: Option<String>,
    /// `--depends-on <EXPR>` per `QRY-004`.
    pub depends_on: Option<String>,
    /// `--ancestor-of <EXPR>` per `QRY-004`.
    pub ancestor_of: Option<String>,
    /// `--has-deps` / `--no-deps` per `QRY-005`.
    pub deps_presence: FieldPresence,
    /// `--has-inputs` / `--no-inputs` per `QRY-005`.
    pub inputs_presence: FieldPresence,
    /// `--has-outputs` / `--no-outputs` per `QRY-005`.
    pub outputs_presence: FieldPresence,
    /// `--mutex` per `QRY-005`.
    pub mutex: bool,
    /// `--format <FMT>` per `QRY-008`; defaults to `plain`.
    pub format: OutputFormat,
}

/// Per-field presence selector for the `--has-X` / `--no-X` flag
/// pairs of `QRY-005`. Encoding the pair as a single tri-state
/// value lifts the spec's intra-pair mutex (within a pair, the
/// two flags are mutually exclusive) into the type system, so the
/// invariant cannot be violated at any layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FieldPresence {
    /// Neither `--has-X` nor `--no-X` was supplied; the field
    /// contributes no constraint.
    #[default]
    Any,
    /// `--has-X`: the field MUST be non-empty.
    NonEmpty,
    /// `--no-X`: the field MUST be empty.
    Empty,
}

/// Output presentation for `haz query` per `QRY-008`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
    /// One line per task, formatted as `<project>:<task>`. The
    /// default per `QRY-001`.
    #[default]
    Plain,
    /// A single JSON array of objects with `project`, `task`, and
    /// `tags` fields per `QRY-008`.
    Json,
}

pub(super) fn query_command() -> impl Parser<QueryArgs> {
    let tags = long("tags")
        .help("Filter by owning-project tag expression (QRY-003)")
        .argument::<String>("EXPR")
        .optional();
    let projects = long("projects")
        .help("Filter by project-name expression (QRY-003)")
        .argument::<String>("EXPR")
        .optional();
    let tasks = long("tasks")
        .help("Filter by task-name expression (QRY-003)")
        .argument::<String>("EXPR")
        .optional();
    let inputs = long("inputs")
        .help("Filter by inputs path-pattern expression (QRY-003)")
        .argument::<String>("EXPR")
        .optional();
    let outputs = long("outputs")
        .help("Filter by outputs path-pattern expression (QRY-003)")
        .argument::<String>("EXPR")
        .optional();
    let child_of = long("child-of")
        .help("Direct hard-edge predecessor must satisfy EXPR (QRY-004)")
        .argument::<String>("EXPR")
        .optional();
    let parent_of = long("parent-of")
        .help("Direct hard-edge successor must satisfy EXPR (QRY-004)")
        .argument::<String>("EXPR")
        .optional();
    let depends_on = long("depends-on")
        .help("Transitive hard-edge predecessor must satisfy EXPR (QRY-004)")
        .argument::<String>("EXPR")
        .optional();
    let ancestor_of = long("ancestor-of")
        .help("Transitive hard-edge successor must satisfy EXPR (QRY-004)")
        .argument::<String>("EXPR")
        .optional();

    let deps_presence = presence_parser(
        "has-deps",
        "no-deps",
        "Select tasks whose `deps:` is non-empty (QRY-005)",
        "Select tasks whose `deps:` is empty (QRY-005)",
    );
    let inputs_presence = presence_parser(
        "has-inputs",
        "no-inputs",
        "Select tasks whose `inputs:` is non-empty (QRY-005)",
        "Select tasks whose `inputs:` is empty (QRY-005)",
    );
    let outputs_presence = presence_parser(
        "has-outputs",
        "no-outputs",
        "Select tasks whose `outputs:` is non-empty (QRY-005)",
        "Select tasks whose `outputs:` is empty (QRY-005)",
    );
    let mutex = long("mutex")
        .help("Select tasks that declare a `mutex:` field (QRY-005)")
        .switch();

    let format = long("format")
        .help("Output format (plain | json) per QRY-008")
        .argument::<String>("FMT")
        .parse(|s| match s.as_ref() {
            "plain" => Ok(OutputFormat::Plain),
            "json" => Ok(OutputFormat::Json),
            other => Err(format!(
                "unknown output format `{other}` (expected `plain` or `json`)"
            )),
        })
        .fallback(OutputFormat::Plain);

    construct!(QueryArgs {
        tags,
        projects,
        tasks,
        inputs,
        outputs,
        child_of,
        parent_of,
        depends_on,
        ancestor_of,
        deps_presence,
        inputs_presence,
        outputs_presence,
        mutex,
        format,
    })
}

/// Build the `--<has_flag>` / `--<no_flag>` pair parser. The
/// reduction to [`FieldPresence`] is the `QRY-005` intra-pair
/// mutex: two switches yield three valid states; the impossible
/// "both" state is rejected at parse time.
fn presence_parser(
    has_flag: &'static str,
    no_flag: &'static str,
    has_help: &'static str,
    no_help: &'static str,
) -> impl Parser<FieldPresence> {
    let has = long(has_flag).help(has_help).switch();
    let no = long(no_flag).help(no_help).switch();
    construct!(has, no).parse(move |(has, no)| match (has, no) {
        (false, false) => Ok(FieldPresence::Any),
        (true, false) => Ok(FieldPresence::NonEmpty),
        (false, true) => Ok(FieldPresence::Empty),
        (true, true) => Err(format!(
            "`--{has_flag}` and `--{no_flag}` are mutually exclusive"
        )),
    })
}

#[cfg(test)]
mod tests {
    use super::{FieldPresence, OutputFormat, QueryArgs};
    use crate::cli::{Cmd, parse};

    #[test]
    fn qry_001_query_with_no_flags_parses_to_default() {
        assert_eq!(parse(&["query"]).unwrap(), Cmd::Query(QueryArgs::default()),);
    }

    #[test]
    fn qry_003_tags_filter_captures_expression_verbatim() {
        assert_eq!(
            parse(&["query", "--tags", "backend & !legacy"]).unwrap(),
            Cmd::Query(QueryArgs {
                tags: Some("backend & !legacy".to_owned()),
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_003_projects_filter_captures_expression_verbatim() {
        assert_eq!(
            parse(&["query", "--projects", "lib | web"]).unwrap(),
            Cmd::Query(QueryArgs {
                projects: Some("lib | web".to_owned()),
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_003_tasks_filter_captures_expression_verbatim() {
        assert_eq!(
            parse(&["query", "--tasks", "build"]).unwrap(),
            Cmd::Query(QueryArgs {
                tasks: Some("build".to_owned()),
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_003_inputs_and_outputs_filters_capture_expressions_verbatim() {
        assert_eq!(
            parse(&[
                "query",
                "--inputs",
                "src/**/*.rs",
                "--outputs",
                "/lib/dist/*.so",
            ])
            .unwrap(),
            Cmd::Query(QueryArgs {
                inputs: Some("src/**/*.rs".to_owned()),
                outputs: Some("/lib/dist/*.so".to_owned()),
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_004_relational_filters_capture_expressions_verbatim() {
        assert_eq!(
            parse(&[
                "query",
                "--child-of",
                "name:build",
                "--parent-of",
                "tag:backend",
                "--depends-on",
                "project:lib",
                "--ancestor-of",
                "name:lint",
            ])
            .unwrap(),
            Cmd::Query(QueryArgs {
                child_of: Some("name:build".to_owned()),
                parent_of: Some("tag:backend".to_owned()),
                depends_on: Some("project:lib".to_owned()),
                ancestor_of: Some("name:lint".to_owned()),
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_005_individual_shortcut_flags_parse() {
        let parsed = parse(&[
            "query",
            "--has-deps",
            "--has-inputs",
            "--no-outputs",
            "--mutex",
        ])
        .unwrap();
        assert_eq!(
            parsed,
            Cmd::Query(QueryArgs {
                deps_presence: FieldPresence::NonEmpty,
                inputs_presence: FieldPresence::NonEmpty,
                outputs_presence: FieldPresence::Empty,
                mutex: true,
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_005_has_deps_plus_no_deps_rejects() {
        let err = parse(&["query", "--has-deps", "--no-deps"]).unwrap_err();
        assert!(
            err.contains("mutually exclusive"),
            "diagnostic should name the intra-pair mutex: {err}",
        );
    }

    #[test]
    fn qry_005_has_inputs_plus_no_inputs_rejects() {
        let err = parse(&["query", "--has-inputs", "--no-inputs"]).unwrap_err();
        assert!(
            err.contains("mutually exclusive"),
            "diagnostic should name the intra-pair mutex: {err}",
        );
    }

    #[test]
    fn qry_005_has_outputs_plus_no_outputs_rejects() {
        let err = parse(&["query", "--has-outputs", "--no-outputs"]).unwrap_err();
        assert!(
            err.contains("mutually exclusive"),
            "diagnostic should name the intra-pair mutex: {err}",
        );
    }

    #[test]
    fn qry_008_format_plain_parses() {
        assert_eq!(
            parse(&["query", "--format", "plain"]).unwrap(),
            Cmd::Query(QueryArgs {
                format: OutputFormat::Plain,
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_008_format_json_parses() {
        assert_eq!(
            parse(&["query", "--format", "json"]).unwrap(),
            Cmd::Query(QueryArgs {
                format: OutputFormat::Json,
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_008_format_default_is_plain() {
        let Cmd::Query(args) = parse(&["query"]).unwrap() else {
            panic!("expected Cmd::Query");
        };
        assert_eq!(args.format, OutputFormat::Plain);
    }

    #[test]
    fn qry_008_unknown_format_rejects() {
        let err = parse(&["query", "--format", "yaml"]).unwrap_err();
        assert!(
            err.contains("unknown output format"),
            "diagnostic should name the offending value: {err}",
        );
    }

    #[test]
    fn qry_006_multiple_filter_families_combine_into_one_args() {
        let parsed = parse(&[
            "query",
            "--tags",
            "backend",
            "--tasks",
            "test",
            "--has-deps",
            "--format",
            "json",
        ])
        .unwrap();
        assert_eq!(
            parsed,
            Cmd::Query(QueryArgs {
                tags: Some("backend".to_owned()),
                tasks: Some("test".to_owned()),
                deps_presence: FieldPresence::NonEmpty,
                format: OutputFormat::Json,
                ..QueryArgs::default()
            }),
        );
    }

    #[test]
    fn qry_001_query_rejects_positional_arguments() {
        let err = parse(&["query", "lib:build"]).unwrap_err();
        assert!(
            !err.is_empty(),
            "positional argument must produce a diagnostic: {err}",
        );
    }
}