workshop-rs-cli 0.1.12

Standalone CLI for the canonical Workshop core: parse, emit, convert, locales, and catalog identity.
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
//! Standalone command-line interface for the canonical Workshop core
//! (`workshop-rs`). Operates on raw Workshop text files: parse to WIR,
//! emit localized Workshop text, convert between locales, list declared
//! locales with coverage, and print the machine-readable catalog identity.
//!
//! Exit codes: `0` success, `1` parse/emit/conversion/catalog failure,
//! `2` usage error.

use std::path::{Path, PathBuf};

use workshop_rs::catalog::{Catalog, Locale};
use workshop_rs::census;
use workshop_rs::convert::{self, ConvertOptions};
use workshop_rs::detect;
use workshop_rs::emitter::{self, EmitOptions};
use workshop_rs::live_capture;
use workshop_rs::parser;

mod corpus;

/// The default locale override for parsing when the input locale is not
/// specified explicitly.
const USAGE: &str = "\
usage: workshop-rs-cli <command> [options]

commands:
  parse <file> [--locale LOCALE]
      Parse raw Workshop text into validated Workshop IR and print a
      deterministic WIR dump. Without --locale the locale is auto-detected.
  emit <file> [--locale LOCALE] [--fallback-locale LOCALE]
      Parse and emit localized Workshop text (fail-explicit on missing
      target-locale mappings; --fallback-locale opts into fallback, which is
      reported on stderr).
  convert <file> --from LOCALE --to LOCALE [--fallback-locale LOCALE]
      Convert raw Workshop text between locales (parse -> canonical
      semantics -> emit). Missing target-locale mappings fail explicitly
      unless --fallback-locale is given.
  locales
      List the declared locales with per-locale mapping coverage.
  version [--json]
      Print the machine-readable catalog identity: implementation version,
      catalog version and content digest, locale coverage, target evidence,
      and provenance.
  census [--json]
      Run the deterministic offline Workshop feature census. Unexpected
      regressions exit with status 1; known gaps remain visible.
  corpus <manifest> [--json]
      Run an offline provenance-linked real-project corpus manifest and print
      its #18 conformance report. Known gaps remain visible and do not count
      as matches; unexpected regressions return exit code 1.
  seasonal-diff <previous.json> <current.json> [--json]
      Validate two provenance-rich live-client capture documents and emit a
      structured offline drift report. This command never captures a client.
";

pub fn run(args: Vec<String>) -> i32 {
    let mut args = args.into_iter();
    let Some(command) = args.next() else {
        eprintln!("{USAGE}");
        return 2;
    };
    let rest: Vec<String> = args.collect();
    match command.as_str() {
        "parse" => parse_command(rest),
        "emit" => emit_command(rest),
        "convert" => convert_command(rest),
        "locales" => locales_command(rest),
        "version" => version_command(rest),
        "census" => census_command(rest),
        "corpus" => corpus_command(rest),
        "seasonal-diff" => seasonal_diff_command(rest),
        "help" | "--help" | "-h" => {
            print!("{USAGE}");
            0
        }
        other => {
            eprintln!("workshop-rs-cli: unknown command '{other}'");
            eprintln!("{USAGE}");
            2
        }
    }
}

/// `--locale LOCALE`, `--fallback-locale LOCALE`, `--from`/`--to LOCALE`,
/// `--json`, `--file PATH`, and the positional file argument.
struct ArgParser {
    args: Vec<String>,
    position: usize,
}

impl ArgParser {
    fn new(args: Vec<String>) -> Self {
        ArgParser { args, position: 0 }
    }

    fn next(&mut self) -> Option<&str> {
        let value = self.args.get(self.position).map(String::as_str);
        if value.is_some() {
            self.position += 1;
        }
        value
    }

    fn value_after(&mut self, flag: &str) -> Result<String, String> {
        self.next()
            .map(str::to_string)
            .ok_or_else(|| format!("missing value for {flag}"))
    }

    fn expect_end(&mut self) -> Result<(), String> {
        if let Some(extra) = self.next() {
            return Err(format!("unexpected argument '{extra}'"));
        }
        Ok(())
    }
}

fn catalog() -> Result<Catalog, String> {
    Catalog::builtin().map_err(|error| format!("catalog: {error}"))
}

fn read_file(path: &Path) -> Result<String, String> {
    std::fs::read_to_string(path)
        .map_err(|error| format!("cannot read {}: {error}", path.display()))
}

/// Resolve the parse locale: an explicit override always wins; otherwise
/// auto-detect with the documented confidence gate.
fn resolve_parse_locale(
    input: &str,
    catalog: &Catalog,
    explicit: Option<Locale>,
) -> Result<Locale, String> {
    detect::resolve_locale(input, catalog, explicit.as_ref()).map_err(|error| error.to_string())
}

fn parse_command(args: Vec<String>) -> i32 {
    let mut parser = ArgParser::new(args);
    let mut file: Option<PathBuf> = None;
    let mut locale: Option<Locale> = None;
    loop {
        match parser.next() {
            None => break,
            Some("--locale") => match parser.value_after("--locale") {
                Ok(value) => locale = Some(Locale::new(&value)),
                Err(error) => return usage_error(&error),
            },
            Some(value) if file.is_none() => file = Some(PathBuf::from(value)),
            Some(value) => return usage_error(&format!("unexpected argument '{value}'")),
        }
    }
    let Some(file) = file else {
        return usage_error("parse requires a file argument");
    };
    let (catalog, input) = match (catalog(), read_file(&file)) {
        (Ok(catalog), Ok(input)) => (catalog, input),
        (Err(error), _) | (_, Err(error)) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let locale = match resolve_parse_locale(&input, &catalog, locale) {
        Ok(locale) => locale,
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let program = match parser::parse_with_context(&input, &catalog, &locale, &catalog) {
        Ok(program) => program,
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    if let Err(error) = program.validate() {
        eprintln!("workshop-rs-cli: WIR validation failed: {error}");
        return 1;
    }
    print!("{}", program.dump());
    0
}

fn emit_command(args: Vec<String>) -> i32 {
    let mut parser = ArgParser::new(args);
    let mut file: Option<PathBuf> = None;
    let mut locale: Option<Locale> = None;
    let mut fallback: Option<Locale> = None;
    loop {
        match parser.next() {
            None => break,
            Some("--locale") => match parser.value_after("--locale") {
                Ok(value) => locale = Some(Locale::new(&value)),
                Err(error) => return usage_error(&error),
            },
            Some("--fallback-locale") => match parser.value_after("--fallback-locale") {
                Ok(value) => fallback = Some(Locale::new(&value)),
                Err(error) => return usage_error(&error),
            },
            Some(value) if file.is_none() => file = Some(PathBuf::from(value)),
            Some(value) => return usage_error(&format!("unexpected argument '{value}'")),
        }
    }
    let Some(file) = file else {
        return usage_error("emit requires a file argument");
    };
    let (catalog, input) = match (catalog(), read_file(&file)) {
        (Ok(catalog), Ok(input)) => (catalog, input),
        (Err(error), _) | (_, Err(error)) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let locale = match resolve_parse_locale(&input, &catalog, locale) {
        Ok(locale) => locale,
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let program = match parser::parse_with_context(&input, &catalog, &locale, &catalog) {
        Ok(program) => program,
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let options = EmitOptions {
        fallback_locale: fallback,
    };
    match emitter::emit_with_options(&program, &catalog, &locale, &options) {
        Ok(output) => {
            report_fallbacks(&output.fallback_ids);
            print!("{}", output.text);
            0
        }
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            1
        }
    }
}

fn convert_command(args: Vec<String>) -> i32 {
    let mut parser = ArgParser::new(args);
    let mut file: Option<PathBuf> = None;
    let mut from: Option<Locale> = None;
    let mut to: Option<Locale> = None;
    let mut fallback: Option<Locale> = None;
    loop {
        match parser.next() {
            None => break,
            Some("--from") => match parser.value_after("--from") {
                Ok(value) => from = Some(Locale::new(&value)),
                Err(error) => return usage_error(&error),
            },
            Some("--to") => match parser.value_after("--to") {
                Ok(value) => to = Some(Locale::new(&value)),
                Err(error) => return usage_error(&error),
            },
            Some("--fallback-locale") => match parser.value_after("--fallback-locale") {
                Ok(value) => fallback = Some(Locale::new(&value)),
                Err(error) => return usage_error(&error),
            },
            Some(value) if file.is_none() => file = Some(PathBuf::from(value)),
            Some(value) => return usage_error(&format!("unexpected argument '{value}'")),
        }
    }
    let Some(file) = file else {
        return usage_error("convert requires a file argument");
    };
    let (Some(from), Some(to)) = (from, to) else {
        return usage_error("convert requires --from and --to locales");
    };
    let (catalog, input) = match (catalog(), read_file(&file)) {
        (Ok(catalog), Ok(input)) => (catalog, input),
        (Err(error), _) | (_, Err(error)) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let options = ConvertOptions {
        fallback_locale: fallback,
    };
    match convert::convert(&input, &catalog, &from, &to, &options) {
        Ok(output) => {
            report_fallbacks(&output.fallback_ids);
            print!("{}", output.text);
            0
        }
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            1
        }
    }
}

/// Report opted-in fallback usage on stderr so the fallback choice is
/// visible in tooling output (ADR-0001 Decision 7).
fn report_fallbacks(fallback_ids: &[String]) {
    if fallback_ids.is_empty() {
        return;
    }
    eprintln!(
        "workshop-rs-cli: note: {} canonical id(s) emitted with a fallback-locale spelling: {}",
        fallback_ids.len(),
        fallback_ids.join(", ")
    );
}

fn locales_command(args: Vec<String>) -> i32 {
    let mut parser = ArgParser::new(args);
    if let Err(error) = parser.expect_end() {
        return usage_error(&error);
    }
    let catalog = match catalog() {
        Ok(catalog) => catalog,
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    for coverage in catalog.locale_coverage_all() {
        println!("{} {}/{}", coverage.locale, coverage.mapped, coverage.total);
    }
    0
}

fn version_command(args: Vec<String>) -> i32 {
    let mut parser = ArgParser::new(args);
    let mut json = false;
    loop {
        match parser.next() {
            None => break,
            Some("--json") => json = true,
            Some(value) => return usage_error(&format!("unexpected argument '{value}'")),
        }
    }
    let catalog = match catalog() {
        Ok(catalog) => catalog,
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let identity = catalog.identity();
    if json {
        match serde_json::to_string_pretty(&identity) {
            Ok(text) => println!("{text}"),
            Err(error) => {
                eprintln!("workshop-rs-cli: cannot serialize identity: {error}");
                return 1;
            }
        }
    } else {
        println!(
            "implementation version: {}",
            identity.implementation_version
        );
        println!("catalog version: {}", identity.catalog_version);
        println!(
            "catalog digest: {}",
            identity.catalog_digest.as_deref().unwrap_or("<none>")
        );
        for coverage in &identity.locale_coverage {
            println!(
                "locale {}: {}/{} mapped",
                coverage.locale, coverage.mapped, coverage.total
            );
        }
        println!(
            "target: {} ({})",
            identity.target.surface, identity.target.game
        );
    }
    0
}

fn census_command(args: Vec<String>) -> i32 {
    let json = match args.as_slice() {
        [] => false,
        [flag] if flag == "--json" => true,
        _ => return usage_error("census accepts only the optional --json flag"),
    };
    let catalog = match Catalog::builtin() {
        Ok(catalog) => catalog,
        Err(error) => return usage_error(&format!("cannot load catalog: {error}")),
    };
    let census = match census::Census::builtin(&catalog) {
        Ok(census) => census,
        Err(error) => return usage_error(&format!("cannot build census: {error}")),
    };
    let report = census.run(&catalog);
    if let Err(error) = report.validate_against(&catalog) {
        return usage_error(&format!("invalid census report: {error}"));
    }
    if json {
        match report.to_json() {
            Ok(text) => println!("{text}"),
            Err(error) => return usage_error(&format!("cannot serialize census: {error}")),
        }
    } else {
        println!(
            "census schema {} / conformance schema {}",
            report.schema_version, report.conformance_schema_version
        );
        for result in &report.results {
            println!("{}: {:?}", result.case_id, result.status);
        }
    }
    if report.results.iter().any(|result| {
        result.status == workshop_rs::conformance::ConformanceStatus::UnexpectedRegression
    }) {
        1
    } else {
        0
    }
}

fn corpus_command(args: Vec<String>) -> i32 {
    let mut parser = ArgParser::new(args);
    let mut manifest: Option<PathBuf> = None;
    let mut json = false;
    loop {
        match parser.next() {
            None => break,
            Some("--json") => json = true,
            Some(value) if manifest.is_none() => manifest = Some(PathBuf::from(value)),
            Some(value) => return usage_error(&format!("unexpected argument '{value}'")),
        }
    }
    let Some(manifest) = manifest else {
        return usage_error("corpus requires a manifest file");
    };
    match corpus::run(&manifest) {
        Ok(report) => {
            if json {
                match serde_json::to_string_pretty(&report) {
                    Ok(text) => println!("{text}"),
                    Err(error) => {
                        eprintln!("workshop-rs-cli: cannot serialize corpus report: {error}");
                        return 1;
                    }
                }
            } else {
                print!("{}", report.human_summary());
            }
            if report.has_unexpected_regression() {
                1
            } else {
                0
            }
        }
        Err(error) => {
            eprintln!("workshop-rs-cli: corpus: {error}");
            1
        }
    }
}

fn seasonal_diff_command(args: Vec<String>) -> i32 {
    let mut paths = Vec::new();
    let mut json = false;
    for argument in args {
        if argument == "--json" {
            json = true;
        } else if paths.len() < 2 {
            paths.push(PathBuf::from(argument));
        } else {
            return usage_error("seasonal-diff accepts two capture files and --json");
        }
    }
    if paths.len() != 2 {
        return usage_error("seasonal-diff requires previous and current capture files");
    }
    let previous = match read_file(&paths[0]) {
        Ok(text) => text,
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let current = match read_file(&paths[1]) {
        Ok(text) => text,
        Err(error) => {
            eprintln!("workshop-rs-cli: {error}");
            return 1;
        }
    };
    let previous = match live_capture::LiveCapture::from_json(&previous) {
        Ok(capture) => capture,
        Err(error) => {
            eprintln!("workshop-rs-cli: seasonal-diff: {error}");
            return 1;
        }
    };
    let current = match live_capture::LiveCapture::from_json(&current) {
        Ok(capture) => capture,
        Err(error) => {
            eprintln!("workshop-rs-cli: seasonal-diff: {error}");
            return 1;
        }
    };
    let diff = match previous.diff(&current) {
        Ok(diff) => diff,
        Err(error) => {
            eprintln!("workshop-rs-cli: seasonal-diff: {error}");
            return 1;
        }
    };
    if json {
        match diff.to_json() {
            Ok(text) => println!("{text}"),
            Err(error) => {
                eprintln!("workshop-rs-cli: cannot serialize seasonal diff: {error}");
                return 1;
            }
        }
    } else {
        print!("{}", diff.human_summary());
    }
    0
}

fn usage_error(message: &str) -> i32 {
    eprintln!("workshop-rs-cli: {message}");
    eprintln!("{USAGE}");
    2
}