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_domain::KanbanOperations;
8use kanban_persistence::{StoreFactory, StoreRegistry};
9use kanban_service::StoreManager;
10#[cfg(feature = "tui")]
11use kanban_tui::App;
12
13fn open_debug_log_file() -> Option<std::fs::File> {
14 std::env::var("KANBAN_DEBUG_LOG").ok().and_then(|log_path| {
15 std::fs::OpenOptions::new()
16 .create(true)
17 .append(true)
18 .open(&log_path)
19 .ok()
20 })
21}
22
23fn init_tracing_cli() {
24 use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
25
26 if let Some(log_file) = open_debug_log_file() {
27 tracing_subscriber::registry()
28 .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")))
29 .with(
30 tracing_subscriber::fmt::layer()
31 .with_writer(log_file)
32 .with_ansi(false)
33 .with_target(true)
34 .with_thread_ids(true)
35 .with_file(true)
36 .with_line_number(true),
37 )
38 .try_init()
39 .ok();
40 return;
41 }
42 tracing_subscriber::registry()
43 .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")))
44 .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
45 .try_init()
46 .ok();
47}
48
49#[cfg(feature = "tui")]
50fn init_tracing_tui(
51 error_log: std::sync::Arc<std::sync::Mutex<kanban_tui::error_log::ErrorLogState>>,
52) {
53 use kanban_tui::error_log::InMemoryLogLayer;
54 use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
55
56 let in_memory = InMemoryLogLayer::new(error_log);
57 if let Some(log_file) = open_debug_log_file() {
58 tracing_subscriber::registry()
59 .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")))
60 .with(
61 tracing_subscriber::fmt::layer()
62 .with_writer(log_file)
63 .with_ansi(false)
64 .with_target(true)
65 .with_thread_ids(true)
66 .with_file(true)
67 .with_line_number(true),
68 )
69 .with(in_memory)
70 .try_init()
71 .ok();
72 return;
73 }
74 tracing_subscriber::registry()
75 .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")))
76 .with(in_memory)
77 .try_init()
78 .ok();
79}
80
81fn parse_cli<I, T>(store_manager: &StoreManager, args: I) -> anyhow::Result<(Cli, clap::Command)>
82where
83 I: IntoIterator<Item = T>,
84 T: Into<std::ffi::OsString> + Clone,
85{
86 let backend_names: Vec<String> = store_manager
87 .backend_names()
88 .into_iter()
89 .map(str::to_owned)
90 .collect();
91 let mut cmd = Cli::command().mut_subcommand("migrate", |sub| {
92 sub.mut_arg("backend", |arg| {
93 arg.value_parser(clap::builder::PossibleValuesParser::new(
94 backend_names.clone(),
95 ))
96 })
97 });
98 let matches = cmd
107 .try_get_matches_from_mut(args)
108 .unwrap_or_else(|e| e.exit());
109 let cli = Cli::from_arg_matches(&matches)?;
110 Ok((cli, cmd))
111}
112
113#[derive(serde::Serialize)]
114struct InitFileResult<'a> {
115 file: &'a str,
116}
117
118async fn create_empty_storage_file(
119 store_manager: &StoreManager,
120 file: &str,
121 config: &AppConfig,
122) -> anyhow::Result<()> {
123 let backend = store_manager
124 .make_backend(file, config)
125 .await
126 .map_err(|e| anyhow::anyhow!("{e}"))?;
127 if backend.needs_save_worker() {
130 backend
131 .as_data_store()
132 .apply_snapshot(kanban_domain::Snapshot::new())
133 .map_err(|e| anyhow::anyhow!("{e}"))?;
134 }
135 backend.flush().await.map_err(|e| anyhow::anyhow!("{e}"))?;
136 Ok(())
137}
138
139async fn dispatch_subcommand(ctx: &mut CliContext, cmd: Commands) -> anyhow::Result<()> {
140 match cmd {
141 Commands::Board(board_cmd) => {
142 handlers::board::handle(ctx, board_cmd.action).await?;
143 }
144 Commands::Column(column_cmd) => {
145 handlers::column::handle(ctx, column_cmd.action).await?;
146 }
147 Commands::Card(card_cmd) => {
148 handlers::card::handle(ctx, card_cmd.action).await?;
149 }
150 Commands::Relation(relation_cmd) => {
151 handlers::relation::handle(ctx, relation_cmd.action).await?;
152 }
153 Commands::Sprint(sprint_cmd) => {
154 handlers::sprint::handle(ctx, sprint_cmd.action).await?;
155 }
156 Commands::Export(args) => {
157 handlers::export::handle_export(ctx, args).await?;
158 }
159 Commands::Import(args) => {
160 handlers::export::handle_import(ctx, args).await?;
161 }
162 Commands::Completions { .. } | Commands::Migrate(_) | Commands::Init { .. } => {
163 unreachable!()
164 }
165 }
166 Ok(())
167}
168
169pub struct CliApp {
175 registry: StoreRegistry,
176 backends: kanban_backend::KanbanBackendRegistry,
177 config: Option<AppConfig>,
178}
179
180impl Default for CliApp {
181 fn default() -> Self {
185 Self {
186 registry: StoreRegistry::new(),
187 backends: kanban_backend::KanbanBackendRegistry::new(),
188 config: None,
189 }
190 }
191}
192
193impl CliApp {
194 pub fn with_defaults() -> Self {
199 let mut registry = kanban_persistence::StoreRegistry::new();
200 let mut backends = kanban_backend::KanbanBackendRegistry::new();
201 #[cfg(feature = "sqlite")]
202 {
203 registry.register(Box::new(kanban_persistence_sqlite::SqliteStoreFactory));
204 backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
205 }
206 #[cfg(feature = "json")]
207 {
208 registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
209 backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
210 }
211 Self {
212 registry,
213 backends,
214 config: None,
215 }
216 }
217
218 pub fn register_backend(
276 mut self,
277 store_factory: Box<dyn StoreFactory>,
278 backend_factory: Box<dyn kanban_backend::KanbanBackendFactory>,
279 ) -> Self {
280 self.registry.register(store_factory);
281 self.backends.register(backend_factory);
282 self
283 }
284
285 pub fn with_config(mut self, config: AppConfig) -> Self {
287 self.config = Some(config);
288 self
289 }
290
291 pub fn registry(&self) -> &StoreRegistry {
293 &self.registry
294 }
295
296 pub fn backends(&self) -> &kanban_backend::KanbanBackendRegistry {
298 &self.backends
299 }
300
301 pub async fn run(self) -> anyhow::Result<()> {
304 self.run_with_args(std::env::args_os()).await
305 }
306
307 pub async fn run_with_args<I, T>(self, args: I) -> anyhow::Result<()>
311 where
312 I: IntoIterator<Item = T>,
313 T: Into<std::ffi::OsString> + Clone,
314 {
315 let store_manager = StoreManager::new(self.registry, self.backends);
316 let (Cli { command, file }, mut cmd) = parse_cli(&store_manager, args)?;
317
318 if let Some(Commands::Completions { shell }) = command {
319 clap_complete::generate(shell, &mut cmd, "kanban", &mut std::io::stdout());
320 return Ok(());
321 }
322
323 if !store_manager.has_backends() {
324 anyhow::bail!(
325 "No storage backends registered. \
326 Use CliApp::with_defaults() or call register_backend() before run()."
327 );
328 }
329
330 let config = self.config.unwrap_or_else(kanban_service::config::load);
331 let validated_file: Option<String> = match file {
332 Some(ref p) => Some(
333 kanban_service::validate_path(std::path::Path::new(p))?
334 .to_string_lossy()
335 .to_string(),
336 ),
337 None => None,
338 };
339 let effective_file = validated_file
340 .clone()
341 .unwrap_or_else(|| kanban_service::config::resolve_storage_location(&config));
342
343 let needs_data_file = !matches!(
344 &command,
345 None | Some(Commands::Completions { .. })
346 | Some(Commands::Migrate(_))
347 | Some(Commands::Init { .. })
348 | Some(Commands::Board(BoardCommand {
349 action: BoardAction::SetSort { .. },
350 }))
351 );
352 if needs_data_file && validated_file.is_none() && config.storage_location.is_none() {
353 anyhow::bail!(
354 "\
355No data file specified.
356
357Provide the file path in one of these ways:
358 kanban <path> (first positional argument)
359 KANBAN_FILE=<path> (environment variable)
360 storage_location = ... (config file setting)"
361 );
362 }
363
364 match command {
365 None => {
366 let has_explicit_file =
368 validated_file.is_some() || config.storage_location.is_some();
369 if has_explicit_file && !std::path::Path::new(&effective_file).exists() {
370 create_empty_storage_file(&store_manager, &effective_file, &config).await?;
371 }
372 use std::io::IsTerminal;
373 if std::io::stdin().is_terminal() {
374 #[cfg(feature = "tui")]
375 {
376 let error_log = std::sync::Arc::new(std::sync::Mutex::new(
377 kanban_tui::error_log::ErrorLogState::default(),
378 ));
379 init_tracing_tui(std::sync::Arc::clone(&error_log));
380 let (mut app, save_rx) =
381 App::new_with_store(store_manager, validated_file).await?;
382 app.set_error_log(error_log);
383 app.run(save_rx).await?;
384 }
385 #[cfg(not(feature = "tui"))]
386 anyhow::bail!(
387 "TUI not available in this build. Run `kanban --help` for available subcommands."
388 );
389 }
390 }
392 Some(Commands::Completions { .. }) => unreachable!(),
393 Some(Commands::Migrate(args)) => {
394 init_tracing_cli();
395 handlers::migrate::handle(&store_manager, args).await?;
396 }
397 Some(Commands::Init { board }) => {
398 init_tracing_cli();
399 match board {
400 Some(name) => {
401 let mut ctx =
402 CliContext::load(&store_manager, &effective_file, config).await?;
403 let created = ctx.create_board(name, None)?;
404 ctx.save().await?;
405 output::output_success(kanban_service::api::BoardResponse::from(&created));
406 }
407 None => {
408 if !std::path::Path::new(&effective_file).exists() {
409 create_empty_storage_file(&store_manager, &effective_file, &config)
410 .await?;
411 }
412 output::output_success(InitFileResult {
413 file: &effective_file,
414 });
415 }
416 }
417 }
418 Some(Commands::Board(BoardCommand {
419 action: BoardAction::SetSort { sort, order },
420 })) => {
421 init_tracing_cli();
422 if sort.is_none() && order.is_none() {
423 return crate::output::output_error(
424 "board set-sort requires at least one of --sort and/or --order",
425 );
426 }
427 if !std::path::Path::new(&effective_file).exists() {
428 create_empty_storage_file(&store_manager, &effective_file, &config).await?;
429 }
430 let mut ctx = CliContext::load(&store_manager, &effective_file, config).await?;
436 let (cur_field, cur_order) = ctx.effective_board_sort();
437 let field = sort.map(|f| f.to_board_sort_field()).unwrap_or(cur_field);
438 let order = order.map(|o| o.to_sort_order()).unwrap_or(cur_order);
439 ctx.set_board_sort(field, order)?;
440 output::output_success(serde_json::json!({
441 "board_sort_field": field.to_string(),
442 "board_sort_order": order.to_string(),
443 }));
444 }
445 Some(cmd) => {
446 init_tracing_cli();
447 if !std::path::Path::new(&effective_file).exists() {
448 return crate::output::output_error(&format!(
449 "Board file not found: '{}'",
450 effective_file
451 ));
452 }
453 let mut ctx = CliContext::load(&store_manager, &effective_file, config).await?;
454 dispatch_subcommand(&mut ctx, cmd).await?;
455 }
456 }
457
458 Ok(())
459 }
460}