This repository was archived by the owner on Jun 18, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.rs
More file actions
2107 lines (1826 loc) · 64.3 KB
/
Copy pathmain.rs
File metadata and controls
2107 lines (1826 loc) · 64.3 KB
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![doc = include_str!("../README.md")]
//! Styx CLI tool
//!
//! Disambiguation heuristic:
//! If arg contains '.' or '/' → file mode
//! If arg is '-' → stdin (file mode)
//! Otherwise → subcommand mode
//!
//! Examples:
//! styx config.styx - file mode (has '.')
//! styx ./config - file mode (has '/')
//! styx - - stdin
//! styx lsp - subcommand (bare word)
//! styx tree config.styx - subcommand with file arg
use std::io::{self, IsTerminal, Read};
use std::path::Path;
use facet::Facet;
use facet_styx::{SchemaFile, validate};
use figue as args;
use styx_format::{FormatOptions, format_source};
use styx_lsp::{TokenType, compute_highlight_spans};
use styx_parse::{Lexer, Parser};
use styx_tokenizer::Tokenizer;
use styx_tree::{Payload, Value};
// ============================================================================
// Exit codes
// ============================================================================
const EXIT_SUCCESS: i32 = 0;
const EXIT_SYNTAX_ERROR: i32 = 1;
const EXIT_VALIDATION_ERROR: i32 = 2;
const EXIT_IO_ERROR: i32 = 3;
// ============================================================================
// CLI argument structures
// ============================================================================
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// File mode arguments: `styx <file> [options]`
#[derive(Facet, Debug, Default)]
struct FileArgs {
/// Input file path (or "-" for stdin)
#[facet(args::positional)]
input: String,
/// Output to file (styx format)
#[facet(args::named, args::short = 'o', default)]
output: Option<String>,
/// Output as JSON to file (or "-" for stdout)
#[facet(args::named, default)]
json_out: Option<String>,
/// Modify input file in place
#[facet(args::named, default)]
in_place: bool,
/// Single-line/compact formatting
#[facet(args::named, default)]
compact: bool,
/// Force multiline formatting (expand all objects/sequences)
#[facet(args::named, default)]
multiline: bool,
/// Enable pretty printing (respect line length limits)
#[facet(args::named, default)]
pretty: bool,
/// Maximum line length for pretty printing (default: 80)
#[facet(args::named, default)]
line_length: Option<usize>,
/// Validate against declared schema (no output unless -o specified)
#[facet(args::named, default)]
validate: bool,
/// Use this schema instead of declared @schema
#[facet(args::named, default)]
schema: Option<String>,
}
/// Top-level CLI with optional subcommand
#[derive(Facet, Debug)]
struct Args {
/// Show version
#[facet(args::named, args::short = 'V', default)]
version: bool,
/// Subcommand to run
#[facet(args::subcommand, default)]
command: Option<Command>,
}
/// Available subcommands
#[derive(Facet, Debug)]
#[repr(u8)]
enum Command {
/// Start language server (stdio)
Lsp,
/// Show tokens from tokenizer
Tokens {
/// Input file
#[facet(args::positional)]
file: String,
},
/// Show lexemes from lexer
Lexemes {
/// Input file
#[facet(args::positional)]
file: String,
},
/// Show parser events
Events {
/// Input file
#[facet(args::positional)]
file: String,
},
/// Show parse tree
Tree {
/// Output format: sexp or debug
#[facet(args::named, default = "debug")]
format: String,
/// Input file
#[facet(args::positional)]
file: String,
},
/// Show CST structure
Cst {
/// Input file
#[facet(args::positional)]
file: String,
},
/// Extract embedded schemas from a binary
Extract {
/// Binary file to extract from
#[facet(args::positional)]
binary: String,
},
/// Compare schema against published version
Diff {
/// Schema file to compare
#[facet(args::positional)]
schema: String,
/// Crate name on staging.crates.io
#[facet(args::named, rename = "crate")]
crate_name: String,
/// Baseline version (default: latest)
#[facet(args::named, default)]
baseline: Option<String>,
},
/// Generate publishable crate from schema
Package {
/// Schema file
#[facet(args::positional)]
schema: String,
/// Crate name
#[facet(args::named)]
name: String,
/// Crate version
#[facet(args::named)]
version: String,
/// Output directory (default: `./<name>`)
#[facet(args::named, default)]
output: Option<String>,
},
/// Publish schema to staging.crates.io
Publish {
/// Schema file
#[facet(args::positional)]
schema: String,
/// Skip confirmation prompt
#[facet(args::named, args::short = 'y', default)]
yes: bool,
},
/// Cache management
Cache {
/// Open cache directory in file explorer
#[facet(args::named, default)]
open: bool,
/// Clear all cached schemas
#[facet(args::named, default)]
clear: bool,
},
/// Output Claude Code skill for AI assistance
Skill,
/// Generate shell completions
Completions {
/// Shell to generate completions for
#[facet(args::positional)]
shell: String,
},
/// Generate code from schema
Gen {
/// Target language
#[facet(args::positional)]
language: String,
/// Schema file
#[facet(args::positional)]
schema: String,
/// Output directory (default: current directory)
#[facet(args::named, default)]
output: Option<String>,
/// Package name (for Go: defaults to schema basename)
#[facet(args::named, default)]
package: Option<String>,
},
}
// ============================================================================
// Main entry point
// ============================================================================
/// Determines if an argument should be treated as a file path.
///
/// Returns true if the argument:
/// - Contains '.' (e.g., config.styx, file.json)
/// - Contains '/' (e.g., ./config, ../path, /absolute/path)
/// - Is exactly '-' (stdin)
fn is_file_arg(arg: &str) -> bool {
arg == "-" || arg.contains('.') || arg.contains('/')
}
fn main() {
let raw_args: Vec<String> = std::env::args().skip(1).collect();
// Handle empty args or help
if raw_args.is_empty() {
print_help();
std::process::exit(EXIT_SUCCESS);
}
// Handle --version / -V at top level
if raw_args[0] == "--version" || raw_args[0] == "-V" {
println!("styx {VERSION}");
std::process::exit(EXIT_SUCCESS);
}
// Handle --help / -h at top level
if raw_args[0] == "--help" || raw_args[0] == "-h" {
print_help();
std::process::exit(EXIT_SUCCESS);
}
// Disambiguation: is first arg a file or a subcommand?
let result = if is_file_arg(&raw_args[0]) {
// File mode: parse as FileArgs
run_file_mode(&raw_args)
} else {
// Subcommand mode: parse as Args with subcommand
run_subcommand_mode(&raw_args)
};
match result {
Ok(()) => std::process::exit(EXIT_SUCCESS),
Err(e) => {
match &e {
CliError::ParseDiagnostic {
error,
source,
filename,
} => {
if let Some(parse_error) = error.as_parse_error() {
parse_error.write_report(filename, source, std::io::stderr());
} else {
eprintln!("error: {e}");
}
}
_ => {
eprintln!("error: {e}");
}
}
std::process::exit(e.exit_code());
}
}
}
fn print_help() {
eprintln!("styx {VERSION} - command-line tool for Styx configuration files\n");
eprintln!("USAGE:");
eprintln!(" styx <file> [options] Process a Styx file");
eprintln!(" styx <command> [args] Run a subcommand\n");
eprintln!(" Files are detected by '.' or '/' in the name, or '-' for stdin.");
eprintln!(" Bare words (e.g., 'lsp', 'tree') are subcommands.\n");
eprintln!("FILE MODE OPTIONS:");
eprintln!(" -o, --output <FILE> Output to file (styx format)");
eprintln!(" --json-out <FILE> Output as JSON (use '-' for stdout)");
eprintln!(" --in-place Modify input file in place");
eprintln!(" --compact Single-line/compact formatting");
eprintln!(" --multiline Force multiline formatting (expand all)");
eprintln!(" --pretty Enable pretty printing (respect line limits)");
eprintln!(
" --line-length <N> Max line length for pretty printing (default: 80)"
);
eprintln!(" --validate Validate against declared schema");
eprintln!(" --schema <FILE> Use this schema instead of @schema\n");
eprintln!("SUBCOMMANDS:");
eprintln!(" lsp Start language server (stdio)");
eprintln!(" tree <file> Show parse tree");
eprintln!(" cst <file> Show CST structure");
eprintln!(" extract <binary> Extract embedded schemas");
eprintln!(" diff <schema> --crate <name> Compare against published version");
eprintln!(" package <schema> --name <n> --version <v>");
eprintln!(" Generate publishable crate");
eprintln!(" publish <schema> [-y] Publish to staging.crates.io");
eprintln!(" cache [--open|--clear] Cache management");
eprintln!(" skill Output Claude Code skill");
eprintln!(" completions <shell> Generate shell completions (bash, zsh, fish)");
eprintln!(" gen <lang> <schema> Generate code from schema (go)\n");
eprintln!("EXAMPLES:");
eprintln!(" styx config.styx Format and print to stdout");
eprintln!(" styx config.styx --in-place Format file in place");
eprintln!(" styx config.styx --validate Validate against schema");
eprintln!(" styx tree config.styx Show parse tree");
eprintln!(" styx completions bash Generate bash completions");
}
fn run_file_mode(args: &[String]) -> Result<(), CliError> {
let args_strs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
let opts: FileArgs = figue::from_slice(&args_strs).unwrap();
// Validate option combinations
if opts.in_place && opts.input == "-" {
return Err(CliError::Usage(
"--in-place cannot be used with stdin".into(),
));
}
if opts.schema.is_some() && !opts.validate {
return Err(CliError::Usage("--schema requires --validate".into()));
}
// Safety check: prevent -o pointing to same file as input
if let Some(ref output) = opts.output
&& opts.input != "-"
&& output != "-"
&& is_same_file(&opts.input, output)
{
return Err(CliError::Usage(
"input and output are the same file\nhint: use --in-place to modify in place".into(),
));
}
// Read input
let source = read_input(Some(&opts.input))?;
let filename = if opts.input == "-" {
"<stdin>".to_string()
} else {
opts.input.clone()
};
// Parse
let value = styx_tree::parse(&source).map_err(|e| CliError::ParseDiagnostic {
error: e,
source: source.clone(),
filename: filename.clone(),
})?;
// Validate if requested
if opts.validate {
run_validation(&value, &source, &filename, opts.schema.as_deref())?;
}
// If --validate with no explicit output, we're done (exit code only)
let has_explicit_output = opts.json_out.is_some() || opts.output.is_some() || opts.in_place;
if opts.validate && !has_explicit_output {
return Ok(());
}
// Determine output format and destination
if let Some(ref json_path) = opts.json_out {
// JSON output
let json = value_to_json(&value);
let output =
serde_json::to_string_pretty(&json).map_err(|e| CliError::Io(io::Error::other(e)))?;
write_output(json_path, &output)?;
} else {
// Validate mutually exclusive options
if opts.compact && opts.multiline {
return Err(CliError::Usage(
"--compact and --multiline are mutually exclusive".to_string(),
));
}
if opts.compact && opts.pretty {
return Err(CliError::Usage(
"--compact and --pretty are mutually exclusive".to_string(),
));
}
if opts.multiline && opts.pretty {
return Err(CliError::Usage(
"--multiline and --pretty are mutually exclusive".to_string(),
));
}
// Styx output - use CST formatter to preserve comments
let mut format_opts = if opts.multiline {
FormatOptions::default().multiline()
} else if opts.compact {
FormatOptions::default().inline()
} else {
FormatOptions::default()
};
// Apply pretty printing options if enabled
if opts.pretty {
format_opts = format_opts.pretty(opts.line_length.unwrap_or(80));
}
let output = format_source(&source, format_opts);
if opts.in_place {
std::fs::write(&opts.input, &output)?;
} else if let Some(ref out_path) = opts.output {
write_output(out_path, &output)?;
} else {
print_styx(&output);
}
}
Ok(())
}
fn run_subcommand_mode(args: &[String]) -> Result<(), CliError> {
let args_strs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
let parsed: Args = figue::from_slice(&args_strs).unwrap();
match parsed.command {
Some(Command::Lsp) => run_lsp(),
Some(Command::Tokens { file }) => run_tokens(&file),
Some(Command::Lexemes { file }) => run_lexemes(&file),
Some(Command::Events { file }) => run_events(&file),
Some(Command::Tree { format, file }) => run_tree(&format, &file),
Some(Command::Cst { file }) => run_cst(&file),
Some(Command::Extract { binary }) => run_extract(&binary),
Some(Command::Diff {
schema,
crate_name,
baseline,
}) => run_diff(&schema, &crate_name, baseline.as_deref()),
Some(Command::Package {
schema,
name,
version,
output,
}) => run_package(&schema, &name, &version, output.as_deref()),
Some(Command::Publish { schema, yes }) => run_publish(&schema, yes),
Some(Command::Cache { open, clear }) => run_cache(open, clear),
Some(Command::Skill) => run_skill(),
Some(Command::Completions { shell }) => run_completions(&shell),
Some(Command::Gen {
language,
schema,
output,
package,
}) => run_gen(&language, &schema, output.as_deref(), package.as_deref()),
None => {
print_help();
Ok(())
}
}
}
// ============================================================================
// Error handling
// ============================================================================
#[derive(Debug)]
#[allow(dead_code)]
enum CliError {
Io(io::Error),
Parse(String),
ParseDiagnostic {
error: styx_tree::BuildError,
source: String,
filename: String,
},
Validation(String),
Usage(String),
}
impl CliError {
fn exit_code(&self) -> i32 {
match self {
CliError::Io(_) => EXIT_IO_ERROR,
CliError::Parse(_) => EXIT_SYNTAX_ERROR,
CliError::ParseDiagnostic { .. } => EXIT_SYNTAX_ERROR,
CliError::Validation(_) => EXIT_VALIDATION_ERROR,
CliError::Usage(_) => EXIT_SYNTAX_ERROR,
}
}
}
impl std::fmt::Display for CliError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CliError::Io(e) => write!(f, "{e}"),
CliError::Parse(e) => write!(f, "{e}"),
CliError::ParseDiagnostic { error, .. } => write!(f, "{error}"),
CliError::Validation(e) => write!(f, "{e}"),
CliError::Usage(e) => write!(f, "{e}"),
}
}
}
impl From<io::Error> for CliError {
fn from(e: io::Error) -> Self {
CliError::Io(e)
}
}
impl From<styx_tree::BuildError> for CliError {
fn from(e: styx_tree::BuildError) -> Self {
CliError::Parse(e.to_string())
}
}
impl From<styx_gen_go::GenError> for CliError {
fn from(e: styx_gen_go::GenError) -> Self {
CliError::Io(io::Error::other(e.to_string()))
}
}
// ============================================================================
// Subcommand implementations
// ============================================================================
fn run_lsp() -> Result<(), CliError> {
let rt = tokio::runtime::Runtime::new().map_err(CliError::Io)?;
rt.block_on(async {
styx_lsp::run()
.await
.map_err(|e| CliError::Io(io::Error::other(e)))
})
}
fn run_tokens(file: &str) -> Result<(), CliError> {
let source = read_input(Some(file))?;
for token in Tokenizer::new(&source) {
println!("{:?}", token);
}
Ok(())
}
fn run_lexemes(file: &str) -> Result<(), CliError> {
let source = read_input(Some(file))?;
for lexeme in Lexer::new(&source) {
println!("{:?}", lexeme);
}
Ok(())
}
fn run_events(file: &str) -> Result<(), CliError> {
let source = read_input(Some(file))?;
let mut parser = Parser::new(&source);
while let Some(event) = parser.next_event() {
println!("{:?}", event);
}
Ok(())
}
fn run_tree(format: &str, file: &str) -> Result<(), CliError> {
let source = read_input(Some(file))?;
let filename = if file == "-" { "<stdin>" } else { file };
match format {
"sexp" => match styx_tree::parse(&source) {
Ok(value) => {
println!("; file: {}", filename);
print_sexp(&value, 0);
println!();
}
Err(e) => {
let (start, end) = match &e {
styx_tree::BuildError::Parse(_, span) => (span.start, span.end),
_ => (0, 0),
};
println!("; file: {}", filename);
println!("(error [{}, {}] {:?})", start, end, e.to_string());
}
},
"debug" => {
let value = styx_tree::parse(&source).map_err(|e| CliError::ParseDiagnostic {
error: e,
source: source.clone(),
filename: filename.to_string(),
})?;
print_tree(&value, 0);
}
_ => {
return Err(CliError::Usage(format!(
"unknown format '{}', expected 'sexp' or 'debug'",
format
)));
}
}
Ok(())
}
fn run_cst(file: &str) -> Result<(), CliError> {
let source = read_input(Some(file))?;
let parsed = styx_cst::parse(&source);
println!("{:#?}", parsed.syntax());
if !parsed.errors().is_empty() {
println!("\nParse errors:");
for err in parsed.errors() {
println!(" {:?}", err);
}
}
Ok(())
}
fn run_extract(binary: &str) -> Result<(), CliError> {
let schemas = styx_embed::extract_schemas_from_file(Path::new(binary))
.map_err(|e| CliError::Io(io::Error::other(format!("{binary}: {e}"))))?;
if schemas.is_empty() {
return Err(CliError::Usage(format!(
"no embedded schemas found in {binary}"
)));
}
for (i, schema) in schemas.iter().enumerate() {
if schemas.len() > 1 {
eprintln!("--- schema {} ---", i + 1);
}
print_styx(schema);
// Ensure newline after schema (print_styx doesn't add one)
if !schema.ends_with('\n') {
println!();
}
}
Ok(())
}
fn run_skill() -> Result<(), CliError> {
print!("{}", include_str!("../contrib/SKILL.md"));
Ok(())
}
fn run_completions(shell: &str) -> Result<(), CliError> {
let shell_enum = match shell.to_lowercase().as_str() {
"bash" => figue::Shell::Bash,
"zsh" => figue::Shell::Zsh,
"fish" => figue::Shell::Fish,
_ => {
return Err(CliError::Usage(format!(
"unknown shell '{}', expected: bash, zsh, fish",
shell
)));
}
};
let completions = figue::generate_completions_for_shape(Args::SHAPE, shell_enum, "styx");
print!("{completions}");
Ok(())
}
fn run_gen(
language: &str,
schema_file: &str,
output: Option<&str>,
package: Option<&str>,
) -> Result<(), CliError> {
match language.to_lowercase().as_str() {
"go" => {
// Load and parse schema
let schema_content = std::fs::read_to_string(schema_file).map_err(|e| {
CliError::Io(io::Error::new(
e.kind(),
format!("schema file '{}': {}", schema_file, e),
))
})?;
let schema: facet_styx::SchemaFile = facet_styx::from_str(&schema_content)
.map_err(|e| CliError::Parse(format!("failed to parse schema: {}", e)))?;
// Determine package name
let pkg_name = package.unwrap_or_else(|| {
Path::new(schema_file)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("config")
});
// Sanitize package name for Go (replace hyphens with underscores)
let sanitized_pkg_name = pkg_name.replace('-', "_");
// Determine output directory
let output_dir = output.unwrap_or(".");
// Generate Go code
styx_gen_go::generate(&schema, &sanitized_pkg_name, output_dir)?;
eprintln!("Generated Go code in {}/", output_dir);
Ok(())
}
_ => Err(CliError::Usage(format!(
"unknown language '{}', expected: go",
language
))),
}
}
fn run_cache(open: bool, clear: bool) -> Result<(), CliError> {
use styx_lsp::cache;
if clear {
match cache::clear_cache() {
Ok((count, size)) => {
println!("Cleared {} cached schemas ({} bytes)", count, size);
}
Err(e) => {
return Err(CliError::Io(e));
}
}
return Ok(());
}
let Some(cache_dir) = cache::cache_dir() else {
return Err(CliError::Usage(
"could not determine cache directory".into(),
));
};
if open {
#[cfg(target_os = "macos")]
{
std::process::Command::new("open")
.arg(&cache_dir)
.spawn()
.map_err(CliError::Io)?;
}
#[cfg(target_os = "linux")]
{
std::process::Command::new("xdg-open")
.arg(&cache_dir)
.spawn()
.map_err(CliError::Io)?;
}
#[cfg(target_os = "windows")]
{
std::process::Command::new("explorer")
.arg(&cache_dir)
.spawn()
.map_err(CliError::Io)?;
}
return Ok(());
}
println!("Cache directory: {}", cache_dir.display());
if let Some(stats) = cache::cache_stats() {
println!(
"Embedded schemas: {} ({} bytes)",
stats.embedded_count, stats.embedded_size
);
println!(
"Crate schemas: {} ({} bytes)",
stats.crate_count, stats.crate_size
);
} else {
println!("(cache directory does not exist)");
}
Ok(())
}
// ============================================================================
// Validation
// ============================================================================
fn run_validation(
value: &Value,
source: &str,
filename: &str,
override_schema: Option<&str>,
) -> Result<(), CliError> {
let schema_file = if let Some(schema_path) = override_schema {
load_schema_file(schema_path)?
} else {
let schema_ref = find_schema_declaration(value)?;
match schema_ref {
SchemaRef::External(path) => {
let resolved = resolve_schema_path(&path, Some(filename))?;
load_schema_file(&resolved)?
}
SchemaRef::Embedded { id, cli } => extract_embedded_schema(&cli, id.as_deref())?,
}
};
let value_for_validation = strip_schema_declaration(value);
let result = validate(&value_for_validation, &schema_file);
if !result.is_valid() {
result.write_report(filename, source, std::io::stderr());
return Err(CliError::Validation(format!(
"{} validation error(s)",
result.errors.len()
)));
}
if !result.warnings.is_empty() {
result.write_report(filename, source, std::io::stderr());
}
Ok(())
}
enum SchemaRef {
External(String),
Embedded { id: Option<String>, cli: String },
}
fn strip_schema_declaration(value: &Value) -> Value {
if let Some(obj) = value.as_object() {
let filtered_entries: Vec<_> = obj
.entries
.iter()
.filter(|e| !e.key.is_schema_tag())
.cloned()
.collect();
Value {
tag: value.tag.clone(),
payload: Some(Payload::Object(styx_tree::Object {
entries: filtered_entries,
span: obj.span,
})),
span: value.span,
}
} else {
value.clone()
}
}
fn find_schema_declaration(value: &Value) -> Result<SchemaRef, CliError> {
let obj = value.as_object().ok_or_else(|| {
CliError::Validation("document root must be an object for validation".into())
})?;
for entry in &obj.entries {
if entry.key.is_schema_tag() {
if let Some(path) = entry.value.as_str() {
return Ok(SchemaRef::External(path.to_string()));
}
if let Some(schema_obj) = entry.value.as_object() {
if let Some(cli_value) = schema_obj.get("cli")
&& let Some(cli_name) = cli_value.as_str()
{
// Also extract the optional schema ID
let id = schema_obj
.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
return Ok(SchemaRef::Embedded {
id,
cli: cli_name.to_string(),
});
}
return Err(CliError::Validation(
"@schema directive must have a 'cli' field with the binary name".into(),
));
}
return Err(CliError::Validation(
"@schema directive must be a path or an object with {id ..., cli ...}".into(),
));
}
}
Err(CliError::Validation(
"no schema declaration found (@schema key)\nhint: use --schema to specify a schema file"
.into(),
))
}
fn resolve_schema_path(schema_path: &str, input_path: Option<&str>) -> Result<String, CliError> {
if schema_path.starts_with("http://") || schema_path.starts_with("https://") {
return Err(CliError::Usage(
"URL schema references are not yet supported".into(),
));
}
let path = Path::new(schema_path);
if path.is_absolute() {
return Ok(schema_path.to_string());
}
if let Some(input) = input_path
&& input != "-"
&& let Some(parent) = Path::new(input).parent()
{
return Ok(parent.join(schema_path).to_string_lossy().to_string());
}
Ok(schema_path.to_string())
}
fn load_schema_file(path: &str) -> Result<SchemaFile, CliError> {
let source = std::fs::read_to_string(path).map_err(|e| {
CliError::Io(io::Error::new(
e.kind(),
format!("schema file '{}': {}", path, e),
))
})?;
facet_styx::from_str(&source)
.map_err(|e| CliError::Parse(format!("failed to parse schema '{}': {}", path, e)))
}
fn extract_embedded_schema(
cli_name: &str,
schema_id: Option<&str>,
) -> Result<SchemaFile, CliError> {
let binary_path = which::which(cli_name).map_err(|_| {
CliError::Validation(format!(
"binary '{}' not found in PATH\nhint: ensure the binary is installed and in your PATH",
cli_name
))
})?;
let schemas = styx_embed::extract_schemas_from_file(&binary_path).map_err(|e| {
CliError::Validation(format!(
"failed to extract schema from '{}': {}\nhint: the binary may not have embedded schemas",
binary_path.display(),
e
))
})?;
if schemas.is_empty() {
return Err(CliError::Validation(format!(
"no embedded schemas found in '{}'",
binary_path.display()
)));
}
// If a schema ID is specified, find the matching schema
let schema_source = if let Some(target_id) = schema_id {
schemas
.iter()
.find(|schema| {
// Parse the schema to check its meta.id
if let Ok(parsed) = styx_tree::parse(schema)
&& let Some(obj) = parsed.as_object()
&& let Some(meta) = obj.get("meta")
&& let Some(meta_obj) = meta.as_object()
&& let Some(id_value) = meta_obj.get("id")
&& let Some(id) = id_value.as_str()
{
return id == target_id;
}
false
})
.ok_or_else(|| {
let available_ids: Vec<_> = schemas
.iter()
.filter_map(|schema| {
styx_tree::parse(schema).ok().and_then(|parsed| {
parsed.as_object().and_then(|obj| {
obj.get("meta").and_then(|meta| {
meta.as_object()
.and_then(|m| m.get("id").and_then(|v| v.as_str()))
.map(|s| s.to_string())
})
})
})
})
.collect();