1use std::fs;
2use std::path::PathBuf;
3
4use color_eyre::eyre::{Report, Result};
5use schemaui::precompile::tui as pre_tui;
6use schemaui::{DocumentFormat, SchemaUI};
7
8use crate::cli::{CommonArgs, TuiSnapshotCommand};
9use crate::session::{SessionBundle, prepare_session};
10
11pub fn run_cli(args: &CommonArgs) -> Result<()> {
12 let session = prepare_session(args)?;
13 execute_session(session)
14}
15
16pub(crate) fn execute_session(session: SessionBundle) -> Result<()> {
17 let SessionBundle {
18 schema,
19 defaults,
20 title,
21 output,
22 } = session;
23 let mut ui = SchemaUI::new(schema);
24 if let Some(title) = title {
25 ui = ui.with_title(title);
26 }
27 if let Some(ref defaults) = defaults {
28 ui = ui.with_default_data(defaults);
29 }
30 if let Some(options) = output {
31 ui = ui.with_output(options);
32 }
33 ui.run().map_err(Report::msg).map(|_| ())
34}
35
36pub fn run_snapshot_cli(cmd: TuiSnapshotCommand) -> Result<()> {
37 let schema_spec = cmd
39 .common
40 .schema
41 .as_deref()
42 .ok_or_else(|| Report::msg("tui-snapshot requires --schema <PATH>"))?;
43 if schema_spec == "-" {
44 return Err(Report::msg(
45 "tui-snapshot does not support --schema - (stdin); please pass a file path",
46 ));
47 }
48
49 let schema_path = PathBuf::from(schema_spec);
50 if !schema_path.exists() {
51 return Err(Report::msg(format!(
52 "schema path {:?} does not exist",
53 schema_path
54 )));
55 }
56
57 let config_spec = cmd.common.config.as_deref();
58 if config_spec == Some("-") {
59 return Err(Report::msg(
60 "tui-snapshot does not support --config - (stdin); please pass a file path",
61 ));
62 }
63
64 let defaults_path = config_spec.map(PathBuf::from);
65 if let Some(ref path) = defaults_path
66 && !path.exists()
67 {
68 return Err(Report::msg(format!(
69 "config path {:?} does not exist",
70 path
71 )));
72 }
73
74 let format = DocumentFormat::from_extension(&schema_path).unwrap_or(DocumentFormat::Json);
75
76 fs::create_dir_all(&cmd.out_dir)?;
77 let tui_module = cmd.out_dir.join("tui_artifacts.rs");
78 let form_module = cmd.out_dir.join("tui_form_schema.rs");
79 let layout_module = cmd.out_dir.join("tui_layout_nav.rs");
80
81 pre_tui::generate_tui_artifacts_module(
82 &schema_path,
83 format,
84 defaults_path.as_deref(),
85 &tui_module,
86 &cmd.tui_fn,
87 )
88 .map_err(Report::msg)?;
89 pre_tui::generate_tui_form_schema_module(
90 &schema_path,
91 format,
92 defaults_path.as_deref(),
93 &form_module,
94 &cmd.form_fn,
95 )
96 .map_err(Report::msg)?;
97 pre_tui::generate_tui_layout_nav_module(
98 &schema_path,
99 format,
100 defaults_path.as_deref(),
101 &layout_module,
102 &cmd.layout_fn,
103 )
104 .map_err(Report::msg)?;
105
106 eprintln!("Generated TUI artifact modules:");
107 eprintln!(" TuiArtifacts module: {:?}", tui_module);
108 eprintln!(" FormSchema module: {:?}", form_module);
109 eprintln!(" LayoutNavModel module: {:?}", layout_module);
110
111 Ok(())
112}