zacor 0.1.0

Package manager and dispatcher for zr — install, manage, and run modular CLI packages
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
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
use crate::error::*;
use crate::platform;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackageDefinition {
    pub name: String,
    pub version: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub binary: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub protocol: bool,
    pub commands: BTreeMap<String, CommandDefinition>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub config: BTreeMap<String, serde_yml::Value>,
    #[serde(default, skip_serializing_if = "DependsSection::is_empty")]
    pub depends: DependsSection,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service: Option<ServiceSection>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution: Option<ExecutionSection>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<BuildSection>,
    #[serde(
        rename = "project-data",
        default,
        skip_serializing_if = "std::ops::Not::not"
    )]
    pub project_data: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CommandDefinition {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub args: BTreeMap<String, ArgumentDefinition>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub invoke: Option<InvokeTemplate>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub commands: BTreeMap<String, CommandDefinition>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input: Option<InputType>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<OutputDeclaration>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputDeclaration {
    /// Legacy field — old `type: text|table|record` format.
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub output_type: Option<OutputType>,
    /// New field — how many results (one or many).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cardinality: Option<Cardinality>,
    /// New field — CLI rendering mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display: Option<DisplayType>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    #[serde(default)]
    pub stream: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<BTreeMap<String, String>>,
}

impl OutputDeclaration {
    /// Resolve cardinality from new or legacy fields.
    pub fn resolved_cardinality(&self) -> Cardinality {
        if let Some(c) = self.cardinality {
            return c;
        }
        match self.output_type {
            Some(OutputType::Table) => Cardinality::Many,
            _ => Cardinality::One,
        }
    }

    /// Resolve display type from new or legacy fields.
    pub fn resolved_display(&self) -> Option<DisplayType> {
        if let Some(d) = self.display {
            return Some(d);
        }
        self.output_type.map(|t| match t {
            OutputType::Text => DisplayType::Text,
            OutputType::Table => DisplayType::Table,
            OutputType::Record => DisplayType::Record,
        })
    }

    /// Backward compat — derive OutputType from new fields.
    pub fn resolved_output_type(&self) -> OutputType {
        if let Some(t) = self.output_type {
            return t;
        }
        match self.resolved_display() {
            Some(DisplayType::Text) => OutputType::Text,
            Some(DisplayType::Table) => OutputType::Table,
            Some(DisplayType::Record) => OutputType::Record,
            None => match self.resolved_cardinality() {
                Cardinality::One => OutputType::Record,
                Cardinality::Many => OutputType::Table,
            },
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum OutputType {
    Text,
    Table,
    Record,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Cardinality {
    One,
    Many,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DisplayType {
    Text,
    Table,
    Record,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum InputType {
    Text,
    Jsonl,
    Binary,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum InvokeTemplate {
    String(String),
    Array(Vec<String>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArgumentDefinition {
    #[serde(rename = "type")]
    pub arg_type: ArgType,
    #[serde(default)]
    pub required: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_yml::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flag: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub rest: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ArgType {
    String,
    Number,
    Integer,
    Bool,
    Path,
    Choice,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DependsSection {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub packages: Vec<PackageDep>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub binaries: Vec<BinaryDep>,
}

impl DependsSection {
    pub fn is_empty(&self) -> bool {
        self.packages.is_empty() && self.binaries.is_empty()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackageDep {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinaryDep {
    pub binary: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub check: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub install_hint: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceSection {
    pub start: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub startup: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildSection {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionSection {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
}

/// Parse a package.yaml from a file path.
pub fn parse_file(path: &Path) -> Result<PackageDefinition> {
    let contents = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read package definition at {}", path.display()))?;
    parse(&contents)
}

/// Parse a package.yaml from a YAML string.
pub fn parse(yaml: &str) -> Result<PackageDefinition> {
    let def: PackageDefinition =
        serde_yml::from_str(yaml).context("failed to parse package.yaml")?;
    validate(&def)?;
    Ok(def)
}

fn validate(def: &PackageDefinition) -> Result<()> {
    platform::validate_package_name(&def.name).context("package.yaml: invalid package name")?;

    if def.version.is_empty() {
        bail!("package.yaml: version is required");
    }

    if def.commands.is_empty() {
        bail!("package.yaml: at least one command is required");
    }

    for key in def.config.keys() {
        platform::validate_config_key(key)
            .with_context(|| format!("package.yaml: invalid config key '{}'", key))?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_valid_binary_package() {
        let yaml = r#"
name: ripgrep
version: "14.1.0"
binary: rg
description: Fast line-oriented search tool
commands:
  default:
    description: Search for a pattern
    args:
      pattern:
        type: string
        required: true
      path:
        type: path
"#;
        let def = parse(yaml).unwrap();
        assert_eq!(def.name, "ripgrep");
        assert_eq!(def.version, "14.1.0");
        assert_eq!(def.binary.as_deref(), Some("rg"));
        assert_eq!(
            def.description.as_deref(),
            Some("Fast line-oriented search tool")
        );
        assert!(def.commands.contains_key("default"));
        let cmd = &def.commands["default"];
        assert!(cmd.args["pattern"].required);
        assert!(!cmd.args["path"].required);
        assert_eq!(cmd.args["pattern"].arg_type, ArgType::String);
        assert_eq!(cmd.args["path"].arg_type, ArgType::Path);
    }

    #[test]
    fn test_definition_only_string_invoke() {
        let yaml = r#"
name: ffmpeg-convert
version: "1.0.0"
commands:
  convert:
    description: Convert media files
    args:
      input:
        type: path
        required: true
      format:
        type: choice
        values: [mp3, wav, flac]
        default: mp3
      output:
        type: path
        required: true
    invoke: "ffmpeg -i {input} -f {format} {output}"
"#;
        let def = parse(yaml).unwrap();
        assert!(def.binary.is_none());
        let cmd = &def.commands["convert"];
        match cmd.invoke.as_ref().unwrap() {
            InvokeTemplate::String(s) => assert!(s.contains("ffmpeg")),
            _ => panic!("expected string invoke"),
        }
    }

    #[test]
    fn test_definition_only_array_invoke() {
        let yaml = r#"
name: ffmpeg-convert
version: "1.0.0"
commands:
  convert:
    args:
      input:
        type: path
        required: true
      output:
        type: path
        required: true
    invoke:
      - ffmpeg
      - "-i"
      - "{input}"
      - "{output}"
"#;
        let def = parse(yaml).unwrap();
        let cmd = &def.commands["convert"];
        match cmd.invoke.as_ref().unwrap() {
            InvokeTemplate::Array(arr) => {
                assert_eq!(arr[0], "ffmpeg");
                assert_eq!(arr.len(), 4);
            }
            _ => panic!("expected array invoke"),
        }
    }

    #[test]
    fn test_missing_name() {
        let yaml = r#"
version: "1.0.0"
commands:
  default:
    description: test
"#;
        assert!(parse(yaml).is_err());
    }

    #[test]
    fn test_missing_version() {
        let yaml = r#"
name: test
commands:
  default:
    description: test
"#;
        assert!(parse(yaml).is_err());
    }

    #[test]
    fn test_missing_commands() {
        let yaml = r#"
name: test
version: "1.0.0"
"#;
        assert!(parse(yaml).is_err());
    }

    #[test]
    fn test_empty_commands() {
        let yaml = r#"
name: test
version: "1.0.0"
commands: {}
"#;
        let err = parse(yaml).unwrap_err().to_string();
        assert!(err.contains("at least one command"), "got: {}", err);
    }

    #[test]
    fn test_config_section() {
        let yaml = r#"
name: my-pkg
version: "1.0.0"
binary: my-pkg
config:
  model: base
  language: auto
commands:
  default:
    description: Transcribe audio
"#;
        let def = parse(yaml).unwrap();
        assert_eq!(def.config.len(), 2);
        assert!(def.config.contains_key("model"));
        assert!(def.config.contains_key("language"));
    }

    #[test]
    fn test_invalid_config_key() {
        let yaml = r#"
name: my-pkg
version: "1.0.0"
binary: my-pkg
config:
  output_format: json
commands:
  default:
    description: test
"#;
        let err = parse(yaml).unwrap_err().to_string();
        assert!(err.contains("invalid"), "got: {}", err);
    }

    #[test]
    fn test_nested_commands() {
        let yaml = r#"
name: my-pkg
version: "1.0.0"
binary: my-pkg
commands:
  transcribe:
    description: Transcribe audio
    commands:
      batch:
        description: Batch transcribe
        args:
          files:
            type: string
            required: true
  translate:
    description: Translate audio
"#;
        let def = parse(yaml).unwrap();
        assert!(def.commands.contains_key("transcribe"));
        let transcribe = &def.commands["transcribe"];
        assert!(transcribe.commands.contains_key("batch"));
    }

    #[test]
    fn test_depends_section() {
        let yaml = r#"
name: my-tool
version: "1.0.0"
commands:
  default:
    description: Run tool
depends:
  packages:
    - name: my-pkg
    - name: other-tool
      version: ">=1.0"
      source: github.com/user/other-tool
  binaries:
    - binary: ffmpeg
      check: "ffmpeg -version"
      install_hint: "Install ffmpeg via your package manager"
"#;
        let def = parse(yaml).unwrap();
        assert_eq!(def.depends.packages.len(), 2);
        assert_eq!(def.depends.packages[0].name, "my-pkg");
        assert!(def.depends.packages[0].source.is_none());
        assert_eq!(
            def.depends.packages[1].source.as_deref(),
            Some("github.com/user/other-tool")
        );
        assert_eq!(def.depends.binaries.len(), 1);
        assert_eq!(def.depends.binaries[0].binary, "ffmpeg");
    }

    #[test]
    fn test_unknown_fields_ignored() {
        let yaml = r#"
name: test
version: "1.0.0"
future_field: some_value
another_unknown: 42
commands:
  default:
    description: test
    unknown_cmd_field: true
"#;
        let def = parse(yaml).unwrap();
        assert_eq!(def.name, "test");
    }

    #[test]
    fn test_description_absent() {
        let yaml = r#"
name: test
version: "1.0.0"
binary: test
commands:
  default:
    args:
      input:
        type: string
"#;
        let def = parse(yaml).unwrap();
        assert!(def.description.is_none());
    }

    #[test]
    fn test_service_section() {
        let yaml = r#"
name: my-server
version: "1.0.0"
binary: my-server
service:
  start: "my-server --port {port}"
  port: 8080
  health: /health
  startup: eager
execution:
  default: service
commands:
  default:
    description: Run server
"#;
        let def = parse(yaml).unwrap();
        let svc = def.service.as_ref().unwrap();
        assert_eq!(svc.port, Some(8080));
        assert_eq!(svc.health.as_deref(), Some("/health"));
        assert_eq!(svc.startup.as_deref(), Some("eager"));
        let exec = def.execution.as_ref().unwrap();
        assert_eq!(exec.default.as_deref(), Some("service"));
    }

    #[test]
    fn test_build_section() {
        let yaml = r#"
name: echo
version: "0.2.0"
binary: echo
build:
  command: "cargo build --release --bin echo"
  output: target/release
commands:
  default:
    description: Echo text
"#;
        let def = parse(yaml).unwrap();
        let build = def.build.as_ref().unwrap();
        assert_eq!(
            build.command.as_deref(),
            Some("cargo build --release --bin echo")
        );
        assert_eq!(build.output.as_deref(), Some("target/release"));
    }

    #[test]
    fn test_output_declaration_text() {
        let yaml = r#"
name: echo
version: "0.2.0"
binary: echo
commands:
  default:
    description: Echo text
    output:
      type: text
      field: text
      schema:
        text: string
"#;
        let def = parse(yaml).unwrap();
        let cmd = &def.commands["default"];
        let output = cmd.output.as_ref().unwrap();
        assert_eq!(output.resolved_output_type(), OutputType::Text);
        assert_eq!(output.field.as_deref(), Some("text"));
        assert!(!output.stream);
        let schema = output.schema.as_ref().unwrap();
        assert_eq!(schema["text"], "string");
    }

    #[test]
    fn test_output_declaration_table() {
        let yaml = r#"
name: ls
version: "0.2.0"
binary: ls
commands:
  default:
    description: List entries
    output:
      type: table
      schema:
        name: string
        size: filesize
        kind: string
"#;
        let def = parse(yaml).unwrap();
        let cmd = &def.commands["default"];
        let output = cmd.output.as_ref().unwrap();
        assert_eq!(output.resolved_output_type(), OutputType::Table);
        assert!(output.field.is_none());
        assert!(!output.stream);
        let schema = output.schema.as_ref().unwrap();
        assert_eq!(schema.len(), 3);
        assert_eq!(schema["size"], "filesize");
    }

    #[test]
    fn test_output_declaration_streaming_table() {
        let yaml = r#"
name: cat
version: "0.2.0"
binary: cat
commands:
  default:
    description: Cat file
    output:
      type: table
      stream: true
      schema:
        line: number
        content: string
"#;
        let def = parse(yaml).unwrap();
        let cmd = &def.commands["default"];
        let output = cmd.output.as_ref().unwrap();
        assert_eq!(output.resolved_output_type(), OutputType::Table);
        assert!(output.stream);
    }

    #[test]
    fn test_invalid_output_type_rejected() {
        let yaml = r#"
name: bad
version: "1.0.0"
commands:
  default:
    output:
      type: invalid
"#;
        assert!(parse(yaml).is_err());
    }

    #[test]
    fn test_no_output_section_backwards_compatible() {
        let yaml = r#"
name: test
version: "1.0.0"
commands:
  default:
    description: test
"#;
        let def = parse(yaml).unwrap();
        let cmd = &def.commands["default"];
        assert!(cmd.output.is_none());
    }

    #[test]
    fn test_project_data_true() {
        let yaml = r#"
name: bp
version: "1.0.0"
project-data: true
commands:
  default:
    description: Blueprint
"#;
        let def = parse(yaml).unwrap();
        assert!(def.project_data);
    }

    #[test]
    fn test_project_data_defaults_false() {
        let yaml = r#"
name: echo
version: "0.2.0"
commands:
  default:
    description: Echo text
"#;
        let def = parse(yaml).unwrap();
        assert!(!def.project_data);
    }

    #[test]
    fn test_existing_packages_still_parse_without_project_data() {
        let yaml = r#"
name: ripgrep
version: "14.1.0"
binary: rg
description: Fast search
commands:
  default:
    description: Search
    args:
      pattern:
        type: string
        required: true
"#;
        let def = parse(yaml).unwrap();
        assert!(!def.project_data);
        assert_eq!(def.name, "ripgrep");
    }

    #[test]
    fn test_no_build_section_backwards_compatible() {
        let yaml = r#"
name: test
version: "1.0.0"
commands:
  default:
    description: test
"#;
        let def = parse(yaml).unwrap();
        assert!(def.build.is_none());
    }
}