1pub mod audio;
7pub mod catalog;
8pub mod cli;
9pub mod commands;
10pub mod config;
11pub mod engine;
12pub mod error;
13pub mod gpu;
14pub mod i18n;
15pub mod media_helper;
16pub mod model;
17pub mod output;
18pub mod paths;
19pub mod schema;
20pub mod signal;
21pub mod surface;
22pub mod transcribe;
23pub mod verbs;
24
25use std::io::Write;
29use std::process::ExitCode;
30
31use clap::{CommandFactory, Parser};
32use tracing::level_filters::LevelFilter;
33
34use crate::cli::{Cli, Commands};
35use crate::commands::Ctx;
36use crate::error::Error;
37use crate::i18n::UiLang;
38use crate::paths::AppPaths;
39
40struct TempGuard;
53
54impl Drop for TempGuard {
55 fn drop(&mut self) {
56 signal::cleanup_temps();
57 }
58}
59
60pub fn run() -> ExitCode {
62 signal::reset_sigpipe();
63 signal::install_handlers();
64 let _temps = TempGuard;
66
67 let cli = match Cli::try_parse() {
68 Ok(c) => c,
69 Err(e) => {
70 let informational = matches!(
73 e.kind(),
74 clap::error::ErrorKind::DisplayHelp
75 | clap::error::ErrorKind::DisplayVersion
76 | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
77 );
78 let rendered = e.render().to_string();
79 let _ = std::io::stderr().write_all(rendered.as_bytes());
80 if informational {
81 return ExitCode::SUCCESS;
82 }
83 let summary = rendered
93 .lines()
94 .find(|l| !l.trim().is_empty())
95 .unwrap_or("invalid arguments")
96 .trim_start_matches("error: ")
97 .to_string();
98 let err = Error::Usage(summary);
99 let _ = output::write_error(
101 &err,
102 &commands::new_correlation_id(),
103 &surface::Surface::default(),
104 None,
105 );
106 return err.to_exit_code();
107 }
108 };
109
110 let correlation_id = commands::new_correlation_id();
111 let surface = cli.surface();
112
113 let ui = match UiLang::resolve(cli.lang.as_deref()) {
114 Ok(l) => l,
115 Err(err) => return fail(&err, &correlation_id, &surface, None),
116 };
117
118 if cli.print_schema {
119 let paths = match AppPaths::resolve(cli.config_dir.as_deref(), cli.cache_dir.as_deref()) {
120 Ok(p) => p,
121 Err(err) => return fail(&err, &correlation_id, &surface, None),
122 };
123 let store = match commands::load_store(&paths) {
124 Ok(s) => s,
125 Err(err) => return fail(&err, &correlation_id, &surface, None),
126 };
127 init_tracing(cli.quiet, cli.verbose, Some(&store));
128 let mut ctx = Ctx {
129 paths: &paths,
130 store,
131 surface: &surface,
132 correlation_id: &correlation_id,
133 ui,
134 no_input: cli.no_input,
135 offline: cli.offline,
136 timeout: cli.timeout,
137 error_reported: false,
138 };
139 return match commands::dispatch(Commands::Schema { name: None }, &mut ctx) {
140 Ok(()) => ExitCode::SUCCESS,
141 Err(err) => fail(&err, &correlation_id, &surface, None),
142 };
143 }
144
145 let Some(command) = cli.command else {
146 let mut buf = Vec::new();
147 let _ = Cli::command().write_help(&mut buf);
148 let _ = std::io::stderr().write_all(&buf);
149 return ExitCode::from(2);
150 };
151
152 if matches!(command, Commands::Completions { .. }) {
154 init_tracing(cli.quiet, cli.verbose, None);
155 return match commands::dispatch(
156 command,
157 &mut Ctx {
158 paths: &AppPaths {
159 config_dir: std::path::PathBuf::from("."),
160 cache_dir: std::path::PathBuf::from("."),
161 state_dir: std::path::PathBuf::from("."),
162 },
163 store: config::Store::default(),
164 surface: &surface,
165 correlation_id: &correlation_id,
166 ui,
167 no_input: cli.no_input,
168 offline: cli.offline,
169 timeout: cli.timeout,
170 error_reported: false,
171 },
172 ) {
173 Ok(()) => ExitCode::SUCCESS,
174 Err(err) => fail(&err, &correlation_id, &surface, None),
175 };
176 }
177
178 let designated = command.target();
183 let target = designated
184 .as_ref()
185 .map(|(resolved, source)| error::TargetRef { resolved, source });
186
187 let paths = match AppPaths::resolve(cli.config_dir.as_deref(), cli.cache_dir.as_deref()) {
188 Ok(p) => p,
189 Err(err) => return fail(&err, &correlation_id, &surface, target),
190 };
191 if let Err(err) = paths.ensure() {
192 return fail(&err, &correlation_id, &surface, target);
193 }
194 let store = match commands::load_store(&paths) {
195 Ok(s) => s,
196 Err(err) => return fail(&err, &correlation_id, &surface, target),
197 };
198 init_tracing(cli.quiet, cli.verbose, Some(&store));
199 surface::publish_content_keys(
202 store
203 .effective()
204 .content_keys
205 .or(config::Store::seeds().content_keys)
206 .unwrap_or_default(),
207 );
208 let ui = match UiLang::resolve(cli.lang.as_deref().or(store.locale.as_deref())) {
209 Ok(l) => l,
210 Err(err) => return fail(&err, &correlation_id, &surface, target),
211 };
212
213 let mut ctx = Ctx {
214 paths: &paths,
215 store,
216 surface: &surface,
217 correlation_id: &correlation_id,
218 ui,
219 no_input: cli.no_input,
220 offline: cli.offline,
221 timeout: cli.timeout,
222 error_reported: false,
223 };
224
225 match commands::dispatch(command, &mut ctx) {
226 Ok(()) => ExitCode::SUCCESS,
227 Err(err) if ctx.error_reported => {
231 if !cli.quiet {
232 if let Some(key) = err.i18n_key() {
233 eprintln!("{}", i18n::tr(ui, key));
234 }
235 }
236 err.to_exit_code()
237 }
238 Err(err) => fail_localised(&err, &correlation_id, &surface, ui, cli.quiet, target),
239 }
240}
241
242fn fail(
243 err: &Error,
244 correlation_id: &str,
245 surface: &surface::Surface,
246 target: Option<error::TargetRef<'_>>,
247) -> ExitCode {
248 let _ = output::write_error(err, correlation_id, surface, target);
249 err.to_exit_code()
250}
251
252fn fail_localised(
254 err: &Error,
255 correlation_id: &str,
256 surface: &surface::Surface,
257 ui: UiLang,
258 quiet: bool,
259 target: Option<error::TargetRef<'_>>,
260) -> ExitCode {
261 if !quiet {
262 if let Some(key) = err.i18n_key() {
263 eprintln!("{}", i18n::tr(ui, key));
264 }
265 }
266 fail(err, correlation_id, surface, target)
267}
268
269fn init_tracing(quiet: bool, verbose: u8, store: Option<&config::Store>) {
295 let configured = store
296 .map(config::Store::effective)
297 .and_then(|e| e.log_level.or(config::Store::seeds().log_level))
298 .and_then(|name| match name.as_str() {
299 "off" => Some(LevelFilter::OFF),
300 "error" => Some(LevelFilter::ERROR),
301 "warn" => Some(LevelFilter::WARN),
302 "info" => Some(LevelFilter::INFO),
303 "debug" => Some(LevelFilter::DEBUG),
304 "trace" => Some(LevelFilter::TRACE),
305 _ => None,
306 });
307 let level = if quiet {
308 LevelFilter::OFF
309 } else {
310 match verbose {
311 0 => configured.unwrap_or(LevelFilter::WARN),
312 1 => LevelFilter::INFO,
313 2 => LevelFilter::DEBUG,
314 _ => LevelFilter::TRACE,
315 }
316 };
317 let effective = store.map(config::Store::effective);
318 let seeds = config::Store::seeds();
319 let json = effective
320 .as_ref()
321 .and_then(|e| e.log_format.clone())
322 .or(seeds.log_format)
323 .is_some_and(|f| f == "json");
324 let timestamps = effective
325 .as_ref()
326 .and_then(|e| e.log_timestamps)
327 .or(seeds.log_timestamps)
328 .unwrap_or(false);
329
330 let _ = match (json, timestamps) {
334 (true, true) => tracing_subscriber::fmt()
335 .json()
336 .with_max_level(level)
337 .with_writer(std::io::stderr)
338 .with_ansi(false)
339 .try_init(),
340 (true, false) => tracing_subscriber::fmt()
341 .json()
342 .with_max_level(level)
343 .with_writer(std::io::stderr)
344 .with_ansi(false)
345 .without_time()
346 .try_init(),
347 (false, true) => tracing_subscriber::fmt()
348 .with_max_level(level)
349 .with_writer(std::io::stderr)
350 .with_ansi(false)
351 .try_init(),
352 (false, false) => tracing_subscriber::fmt()
353 .with_max_level(level)
354 .with_writer(std::io::stderr)
355 .with_ansi(false)
356 .without_time()
357 .try_init(),
358 };
359}