1use crate::cli::{BoardAction, BoardCommand, Cli, Commands};
2use crate::context::CliContext;
3use crate::handlers;
4use crate::output;
5use clap::{CommandFactory, FromArgMatches};
6use kanban_core::AppConfig;
7use kanban_persistence::{StoreFactory, StoreRegistry};
8use kanban_service::StoreManager;
9#[cfg(feature = "tui")]
10use kanban_tui::App;
11
12fn open_debug_log_file() -> Option<std::fs::File> {
13 std::env::var("KANBAN_DEBUG_LOG").ok().and_then(|log_path| {
14 std::fs::OpenOptions::new()
15 .create(true)
16 .append(true)
17 .open(&log_path)
18 .ok()
19 })
20}
21
22fn init_tracing_cli() {
23 use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
24
25 if let Some(log_file) = open_debug_log_file() {
26 tracing_subscriber::registry()
27 .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")))
28 .with(
29 tracing_subscriber::fmt::layer()
30 .with_writer(log_file)
31 .with_ansi(false)
32 .with_target(true)
33 .with_thread_ids(true)
34 .with_file(true)
35 .with_line_number(true),
36 )
37 .try_init()
38 .ok();
39 return;
40 }
41 tracing_subscriber::registry()
42 .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")))
43 .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
44 .try_init()
45 .ok();
46}
47
48#[cfg(feature = "tui")]
49fn init_tracing_tui(
50 error_log: std::sync::Arc<std::sync::Mutex<kanban_tui::error_log::ErrorLogState>>,
51) {
52 use kanban_tui::error_log::InMemoryLogLayer;
53 use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
54
55 let in_memory = InMemoryLogLayer::new(error_log);
56 if let Some(log_file) = open_debug_log_file() {
57 tracing_subscriber::registry()
58 .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")))
59 .with(
60 tracing_subscriber::fmt::layer()
61 .with_writer(log_file)
62 .with_ansi(false)
63 .with_target(true)
64 .with_thread_ids(true)
65 .with_file(true)
66 .with_line_number(true),
67 )
68 .with(in_memory)
69 .try_init()
70 .ok();
71 return;
72 }
73 tracing_subscriber::registry()
74 .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")))
75 .with(in_memory)
76 .try_init()
77 .ok();
78}
79
80fn parse_cli<I, T>(store_manager: &StoreManager, args: I) -> anyhow::Result<(Cli, clap::Command)>
81where
82 I: IntoIterator<Item = T>,
83 T: Into<std::ffi::OsString> + Clone,
84{
85 let backend_names: Vec<String> = store_manager
86 .local_backend_names()
87 .into_iter()
88 .map(str::to_owned)
89 .collect();
90 let mut cmd = Cli::command().mut_subcommand("migrate", |sub| {
91 sub.mut_arg("backend", |arg| {
92 arg.value_parser(clap::builder::PossibleValuesParser::new(
93 backend_names.clone(),
94 ))
95 })
96 });
97 let matches = cmd
105 .try_get_matches_from_mut(args)
106 .unwrap_or_else(|e| e.exit());
107 let cli = Cli::from_arg_matches(&matches)?;
108 Ok((cli, cmd))
109}
110
111#[derive(serde::Serialize)]
112struct InitFileResult<'a> {
113 file: &'a str,
114}
115
116fn reject_remote_locator(locator: &str, command: &str) -> anyhow::Result<()> {
117 if kanban_core::is_remote_locator(locator) {
118 anyhow::bail!(
119 "'{locator}' is a remote server; {command} manages local files. \
120 Point it at a file path, or manage the server's own storage on the server."
121 );
122 }
123 Ok(())
124}
125
126async fn create_empty_storage_file(
127 store_manager: &StoreManager,
128 file: &str,
129 config: &AppConfig,
130) -> anyhow::Result<()> {
131 let backend = store_manager
132 .make_backend(file, config)
133 .await
134 .map_err(|e| anyhow::anyhow!("{e}"))?;
135 backend.mark_dirty();
138 backend.flush().await.map_err(|e| anyhow::anyhow!("{e}"))?;
139 Ok(())
140}
141
142async fn dispatch_subcommand(ctx: &mut CliContext, cmd: Commands) -> anyhow::Result<()> {
143 ctx.set_scope(crate::scope::CommandScope::from_command(&cmd));
144 ctx.sync();
145 match cmd {
146 Commands::Board(board_cmd) => {
147 handlers::board::handle(ctx, board_cmd.action).await?;
148 }
149 Commands::Column(column_cmd) => {
150 handlers::column::handle(ctx, column_cmd.action).await?;
151 }
152 Commands::Card(card_cmd) => {
153 handlers::card::handle(ctx, card_cmd.action).await?;
154 }
155 Commands::Relation(relation_cmd) => {
156 handlers::relation::handle(ctx, relation_cmd.action).await?;
157 }
158 Commands::Sprint(sprint_cmd) => {
159 handlers::sprint::handle(ctx, sprint_cmd.action).await?;
160 }
161 Commands::Export(args) => {
162 handlers::export::handle_export(ctx, args).await?;
163 }
164 Commands::Import(args) => {
165 handlers::export::handle_import(ctx, args).await?;
166 }
167 Commands::Completions { .. } | Commands::Migrate(_) | Commands::Init { .. } => {
168 unreachable!()
169 }
170 }
171 Ok(())
172}
173
174pub struct CliApp {
180 registry: StoreRegistry,
181 backends: kanban_backend::KanbanBackendRegistry,
182 config: Option<AppConfig>,
183}
184
185impl Default for CliApp {
186 fn default() -> Self {
190 Self {
191 registry: StoreRegistry::new(),
192 backends: kanban_backend::KanbanBackendRegistry::new(),
193 config: None,
194 }
195 }
196}
197
198impl CliApp {
199 pub fn with_defaults() -> Self {
205 let mut registry = kanban_persistence::StoreRegistry::new();
206 let mut backends = kanban_backend::KanbanBackendRegistry::new();
207 #[cfg(feature = "sqlite")]
208 {
209 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
210 }
211 #[cfg(feature = "json")]
212 {
213 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
214 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
215 }
216 #[cfg(feature = "http")]
217 {
218 backends.register(Box::new(kanban_backend_http::HttpBackendFactory));
219 }
220 Self {
221 registry,
222 backends,
223 config: None,
224 }
225 }
226
227 pub fn register_backend(
285 mut self,
286 store_factory: Box<dyn StoreFactory>,
287 backend_factory: Box<dyn kanban_backend::KanbanBackendFactory>,
288 ) -> Self {
289 self.registry.register(store_factory);
290 self.backends.register(backend_factory);
291 self
292 }
293
294 pub fn with_config(mut self, config: AppConfig) -> Self {
296 self.config = Some(config);
297 self
298 }
299
300 pub fn registry(&self) -> &StoreRegistry {
302 &self.registry
303 }
304
305 pub fn backends(&self) -> &kanban_backend::KanbanBackendRegistry {
307 &self.backends
308 }
309
310 pub async fn run(self) -> anyhow::Result<()> {
313 self.run_with_args(std::env::args_os()).await
314 }
315
316 pub async fn run_with_args<I, T>(self, args: I) -> anyhow::Result<()>
324 where
325 I: IntoIterator<Item = T>,
326 T: Into<std::ffi::OsString> + Clone,
327 {
328 let result = self.run_inner(args).await;
329 if let Err(ref e) = result {
330 output::emit_error(&e.to_string());
331 }
332 result
333 }
334
335 async fn run_inner<I, T>(self, args: I) -> anyhow::Result<()>
336 where
337 I: IntoIterator<Item = T>,
338 T: Into<std::ffi::OsString> + Clone,
339 {
340 let store_manager = StoreManager::new(self.registry, self.backends);
341 let (Cli { command, file }, mut cmd) = parse_cli(&store_manager, args)?;
342
343 if let Some(Commands::Completions { shell }) = command {
344 clap_complete::generate(shell, &mut cmd, "kanban", &mut std::io::stdout());
345 return Ok(());
346 }
347
348 if !store_manager.has_backends() {
349 anyhow::bail!(
350 "No storage backends registered. \
351 Use CliApp::with_defaults() or call register_backend() before run()."
352 );
353 }
354
355 let config = self.config.unwrap_or_else(kanban_service::config::load);
356 let validated_file: Option<String> = match file {
357 Some(ref p) => Some(
358 kanban_service::validate_path(std::path::Path::new(p))?
359 .to_string_lossy()
360 .to_string(),
361 ),
362 None => None,
363 };
364 let effective_file = validated_file
365 .clone()
366 .unwrap_or_else(|| kanban_service::config::resolve_storage_location(&config));
367
368 let needs_data_file = !matches!(
369 &command,
370 None | Some(Commands::Completions { .. })
371 | Some(Commands::Migrate(_))
372 | Some(Commands::Init { .. })
373 | Some(Commands::Board(BoardCommand {
374 action: BoardAction::SetSort { .. },
375 }))
376 );
377 if needs_data_file && validated_file.is_none() && config.storage_location.is_none() {
378 anyhow::bail!(
379 "\
380No data file specified.
381
382Provide the file path in one of these ways:
383 kanban <path> (first positional argument)
384 KANBAN_FILE=<path> (environment variable)
385 storage_location = ... (config file setting)"
386 );
387 }
388
389 match command {
390 None => {
391 let has_explicit_file =
393 validated_file.is_some() || config.storage_location.is_some();
394 if has_explicit_file
395 && !kanban_core::is_remote_locator(&effective_file)
396 && !std::path::Path::new(&effective_file).exists()
397 {
398 create_empty_storage_file(&store_manager, &effective_file, &config).await?;
399 }
400 use std::io::IsTerminal;
401 if std::io::stdin().is_terminal() {
402 #[cfg(feature = "tui")]
403 {
404 let error_log = std::sync::Arc::new(std::sync::Mutex::new(
405 kanban_tui::error_log::ErrorLogState::default(),
406 ));
407 init_tracing_tui(std::sync::Arc::clone(&error_log));
408 let (mut app, save_rx) =
409 App::new_with_store(store_manager, validated_file).await?;
410 app.set_error_log(error_log);
411 app.run(save_rx).await?;
412 }
413 #[cfg(not(feature = "tui"))]
414 anyhow::bail!(
415 "TUI not available in this build. Run `kanban --help` for available subcommands."
416 );
417 }
418 }
420 Some(Commands::Completions { .. }) => unreachable!(),
421 Some(Commands::Migrate(args)) => {
422 init_tracing_cli();
423 reject_remote_locator(&args.source, "`migrate`")?;
424 if let Some(ref output) = args.output {
425 reject_remote_locator(output, "`migrate`")?;
426 }
427 handlers::migrate::handle(&store_manager, args).await?;
428 }
429 Some(Commands::Init { board }) => {
430 init_tracing_cli();
431 reject_remote_locator(&effective_file, "`init`")?;
432 match board {
433 Some(name) => {
434 let mut ctx =
435 CliContext::load(&store_manager, &effective_file, config).await?;
436 let created = ctx.mutate(|c| c.create_board_impl(name, None))?;
437 ctx.save().await?;
438 output::output_success(kanban_service::api::BoardResponse::from(&created));
439 }
440 None => {
441 if !std::path::Path::new(&effective_file).exists() {
442 create_empty_storage_file(&store_manager, &effective_file, &config)
443 .await?;
444 }
445 output::output_success(InitFileResult {
446 file: &effective_file,
447 });
448 }
449 }
450 }
451 Some(Commands::Board(BoardCommand {
452 action: BoardAction::SetSort { sort, order },
453 })) => {
454 init_tracing_cli();
455 if sort.is_none() && order.is_none() {
456 return crate::output::output_error(
457 "board set-sort requires at least one of --sort and/or --order",
458 );
459 }
460 if !kanban_core::is_remote_locator(&effective_file)
461 && !std::path::Path::new(&effective_file).exists()
462 {
463 create_empty_storage_file(&store_manager, &effective_file, &config).await?;
464 }
465 let mut ctx = CliContext::load(&store_manager, &effective_file, config).await?;
471 let (cur_field, cur_order) = ctx.effective_board_sort();
472 let field = sort.map(|f| f.to_board_sort_field()).unwrap_or(cur_field);
473 let order = order.map(|o| o.to_sort_order()).unwrap_or(cur_order);
474 ctx.set_board_sort(field, order)?;
475 output::output_success(serde_json::json!({
476 "board_sort_field": field.to_string(),
477 "board_sort_order": order.to_string(),
478 }));
479 }
480 Some(cmd) => {
481 init_tracing_cli();
482 if !kanban_core::is_remote_locator(&effective_file)
483 && !std::path::Path::new(&effective_file).exists()
484 {
485 return crate::output::output_error(&format!(
486 "Board file not found: '{}'",
487 effective_file
488 ));
489 }
490 let mut ctx = CliContext::load(&store_manager, &effective_file, config).await?;
491 dispatch_subcommand(&mut ctx, cmd).await?;
492 }
493 }
494
495 Ok(())
496 }
497}