Skip to main content

kanban_cli/
app.rs

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    // For -V/--version and --help, clap returns Err with a kind that
99    // signals "print this and exit cleanly". `e.exit()` dispatches
100    // per-kind internally — DisplayHelp / DisplayVersion go to stdout
101    // with exit code 0; real argument errors go to stderr with exit
102    // code 2. No `match e.kind()` needed here. Without it the error
103    // propagates through main's generic eprintln!("Error: {e}") path,
104    // sending the version / help text to stderr with exit 1 and a
105    // doubled trailing newline.
106    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    use kanban_domain::Snapshot;
124    use kanban_persistence::{snapshot_to_json_bytes, PersistenceMetadata, StoreSnapshot};
125    let store = store_manager.make_store_with_config(Some(file), config)?;
126    let data = snapshot_to_json_bytes(&Snapshot::new()).map_err(|e| anyhow::anyhow!("{e}"))?;
127    let metadata = PersistenceMetadata::new(uuid::Uuid::new_v4());
128    store
129        .save(StoreSnapshot { data, metadata })
130        .await
131        .map_err(|e| anyhow::anyhow!("{e}"))?;
132    Ok(())
133}
134
135async fn dispatch_subcommand(ctx: &mut CliContext, cmd: Commands) -> anyhow::Result<()> {
136    match cmd {
137        Commands::Board(board_cmd) => {
138            handlers::board::handle(ctx, board_cmd.action).await?;
139        }
140        Commands::Column(column_cmd) => {
141            handlers::column::handle(ctx, column_cmd.action).await?;
142        }
143        Commands::Card(card_cmd) => {
144            handlers::card::handle(ctx, card_cmd.action).await?;
145        }
146        Commands::Relation(relation_cmd) => {
147            handlers::relation::handle(ctx, relation_cmd.action).await?;
148        }
149        Commands::Sprint(sprint_cmd) => {
150            handlers::sprint::handle(ctx, sprint_cmd.action).await?;
151        }
152        Commands::Export(args) => {
153            handlers::export::handle_export(ctx, args).await?;
154        }
155        Commands::Import(args) => {
156            handlers::export::handle_import(ctx, args).await?;
157        }
158        Commands::Completions { .. } | Commands::Migrate(_) | Commands::Init { .. } => {
159            unreachable!()
160        }
161    }
162    Ok(())
163}
164
165/// Builder entry point for the Kanban CLI.
166///
167/// A third-party backend crate constructs a `CliApp`, registers its own
168/// `StoreFactory`, and calls [`CliApp::run`] from its own `main` — owning
169/// the binary while reusing every CLI command here.
170pub struct CliApp {
171    registry: StoreRegistry,
172    backends: kanban_backend::KanbanBackendRegistry,
173    config: Option<AppConfig>,
174}
175
176impl Default for CliApp {
177    /// Returns an empty `CliApp` with **no** registered backends. Callers
178    /// must register at least one via [`CliApp::register_backend`] before
179    /// `run` can produce a store.
180    fn default() -> Self {
181        Self {
182            registry: StoreRegistry::new(),
183            backends: kanban_backend::KanbanBackendRegistry::new(),
184            config: None,
185        }
186    }
187}
188
189impl CliApp {
190    /// Returns a `CliApp` pre-configured with all backends compiled in.
191    /// SQLite is registered first so content-sniffing prefers it; JSON is
192    /// registered as the catch-all fallback. When no backend features are
193    /// active both registries are empty (same as [`Default`]).
194    pub fn with_defaults() -> Self {
195        let mut registry = kanban_persistence::StoreRegistry::new();
196        let mut backends = kanban_backend::KanbanBackendRegistry::new();
197        #[cfg(feature = "sqlite")]
198        {
199            registry.register(Box::new(kanban_persistence_sqlite::SqliteStoreFactory));
200            backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
201        }
202        #[cfg(feature = "json")]
203        {
204            registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
205            backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
206        }
207        Self {
208            registry,
209            backends,
210            config: None,
211        }
212    }
213
214    /// Registers an additional backend. `store_factory` builds the raw
215    /// `PersistenceStore` (used by `make_store`/`make_store_with_config` for
216    /// direct storage operations, e.g. `kanban init`'s empty-file creation);
217    /// `backend_factory` builds the `KanbanBackend` that `make_backend`
218    /// dispatches to. A backend that only ever needs `make_backend` cannot
219    /// skip `store_factory` — both are required together, so a factory
220    /// registered through this method is never reachable through only one
221    /// dispatch path and unreachable through the other. Order matters for
222    /// content sniffing on both registries — factories registered earlier
223    /// win when multiple match.
224    ///
225    /// # Example — third-party binary with a custom backend
226    ///
227    /// A crate that owns its own `main` can reuse every CLI command while
228    /// injecting a proprietary storage backend:
229    ///
230    /// ```no_run
231    /// use kanban_cli::CliApp;
232    /// use kanban_backend::KanbanBackendFactory;
233    /// use kanban_core::AppConfig;
234    /// use kanban_domain::KanbanResult;
235    /// use kanban_persistence::{PersistenceError, PersistenceStore, StoreFactory};
236    /// use std::sync::Arc;
237    ///
238    /// // A backend factory provided by a third-party crate.
239    /// struct MyStoreFactory;
240    /// impl StoreFactory for MyStoreFactory {
241    ///     fn name(&self) -> &str { "my-backend" }
242    ///     fn create(
243    ///         &self,
244    ///         locator: &str,
245    ///     ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, PersistenceError> {
246    ///         unimplemented!()
247    ///     }
248    /// }
249    ///
250    /// struct MyBackendFactory;
251    /// #[async_trait::async_trait]
252    /// impl KanbanBackendFactory for MyBackendFactory {
253    ///     fn name(&self) -> &str { "my-backend" }
254    ///     async fn create(
255    ///         &self,
256    ///         locator: &str,
257    ///         config: &AppConfig,
258    ///     ) -> KanbanResult<Arc<dyn kanban_backend::KanbanBackend>> {
259    ///         unimplemented!()
260    ///     }
261    /// }
262    ///
263    /// #[tokio::main]
264    /// async fn main() -> anyhow::Result<()> {
265    ///     CliApp::with_defaults()
266    ///         .register_backend(Box::new(MyStoreFactory), Box::new(MyBackendFactory))
267    ///         .run()
268    ///         .await
269    /// }
270    /// ```
271    pub fn register_backend(
272        mut self,
273        store_factory: Box<dyn StoreFactory>,
274        backend_factory: Box<dyn kanban_backend::KanbanBackendFactory>,
275    ) -> Self {
276        self.registry.register(store_factory);
277        self.backends.register(backend_factory);
278        self
279    }
280
281    /// Overrides the `AppConfig` that `run` would otherwise load from disk.
282    pub fn with_config(mut self, config: AppConfig) -> Self {
283        self.config = Some(config);
284        self
285    }
286
287    /// Exposes the underlying registry for inspection and tests.
288    pub fn registry(&self) -> &StoreRegistry {
289        &self.registry
290    }
291
292    /// Exposes the underlying backend registry for inspection and tests.
293    pub fn backends(&self) -> &kanban_backend::KanbanBackendRegistry {
294        &self.backends
295    }
296
297    /// Executes the CLI: parses args, loads config, and dispatches to the
298    /// requested command (or launches the TUI if no subcommand was given).
299    pub async fn run(self) -> anyhow::Result<()> {
300        self.run_with_args(std::env::args_os()).await
301    }
302
303    /// Like [`run`], but accepts an explicit argument list instead of reading
304    /// from `std::env::args_os()`. Useful for testing without spawning a
305    /// subprocess.
306    pub async fn run_with_args<I, T>(self, args: I) -> anyhow::Result<()>
307    where
308        I: IntoIterator<Item = T>,
309        T: Into<std::ffi::OsString> + Clone,
310    {
311        let store_manager = StoreManager::new(self.registry, self.backends);
312        let (Cli { command, file }, mut cmd) = parse_cli(&store_manager, args)?;
313
314        if let Some(Commands::Completions { shell }) = command {
315            clap_complete::generate(shell, &mut cmd, "kanban", &mut std::io::stdout());
316            return Ok(());
317        }
318
319        if !store_manager.has_backends() {
320            anyhow::bail!(
321                "No storage backends registered. \
322                 Use CliApp::with_defaults() or call register_backend() before run()."
323            );
324        }
325
326        let config = self.config.unwrap_or_else(kanban_service::config::load);
327        let validated_file: Option<String> = match file {
328            Some(ref p) => Some(
329                kanban_service::validate_path(std::path::Path::new(p))?
330                    .to_string_lossy()
331                    .to_string(),
332            ),
333            None => None,
334        };
335        let effective_file = validated_file
336            .clone()
337            .unwrap_or_else(|| kanban_service::config::resolve_storage_location(&config));
338
339        let needs_data_file = !matches!(
340            &command,
341            None | Some(Commands::Completions { .. })
342                | Some(Commands::Migrate(_))
343                | Some(Commands::Init { .. })
344                | Some(Commands::Board(BoardCommand {
345                    action: BoardAction::SetSort { .. },
346                }))
347        );
348        if needs_data_file && validated_file.is_none() && config.storage_location.is_none() {
349            anyhow::bail!(
350                "\
351No data file specified.
352
353Provide the file path in one of these ways:
354  kanban <path>           (first positional argument)
355  KANBAN_FILE=<path>      (environment variable)
356  storage_location = ...  (config file setting)"
357            );
358        }
359
360        match command {
361            None => {
362                // KANBAN_FILE env var resolves into validated_file via clap's env attribute.
363                let has_explicit_file =
364                    validated_file.is_some() || config.storage_location.is_some();
365                if has_explicit_file && !std::path::Path::new(&effective_file).exists() {
366                    create_empty_storage_file(&store_manager, &effective_file, &config).await?;
367                }
368                use std::io::IsTerminal;
369                if std::io::stdin().is_terminal() {
370                    #[cfg(feature = "tui")]
371                    {
372                        let error_log = std::sync::Arc::new(std::sync::Mutex::new(
373                            kanban_tui::error_log::ErrorLogState::default(),
374                        ));
375                        init_tracing_tui(std::sync::Arc::clone(&error_log));
376                        let (mut app, save_rx) =
377                            App::new_with_store(store_manager, validated_file).await?;
378                        app.set_error_log(error_log);
379                        app.run(save_rx).await?;
380                    }
381                    #[cfg(not(feature = "tui"))]
382                    anyhow::bail!(
383                        "TUI not available in this build. Run `kanban --help` for available subcommands."
384                    );
385                }
386                // Non-TTY: file created above if needed, exit cleanly.
387            }
388            Some(Commands::Completions { .. }) => unreachable!(),
389            Some(Commands::Migrate(args)) => {
390                init_tracing_cli();
391                handlers::migrate::handle(&store_manager, args).await?;
392            }
393            Some(Commands::Init { board }) => {
394                init_tracing_cli();
395                match board {
396                    Some(name) => {
397                        let mut ctx =
398                            CliContext::load(&store_manager, &effective_file, config).await?;
399                        let created = ctx.create_board(name, None)?;
400                        ctx.save().await?;
401                        output::output_success(kanban_service::api::BoardResponse::from(&created));
402                    }
403                    None => {
404                        if !std::path::Path::new(&effective_file).exists() {
405                            create_empty_storage_file(&store_manager, &effective_file, &config)
406                                .await?;
407                        }
408                        output::output_success(InitFileResult {
409                            file: &effective_file,
410                        });
411                    }
412                }
413            }
414            Some(Commands::Board(BoardCommand {
415                action: BoardAction::SetSort { sort, order },
416            })) => {
417                init_tracing_cli();
418                if sort.is_none() && order.is_none() {
419                    return crate::output::output_error(
420                        "board set-sort requires at least one of --sort and/or --order",
421                    );
422                }
423                if !std::path::Path::new(&effective_file).exists() {
424                    create_empty_storage_file(&store_manager, &effective_file, &config).await?;
425                }
426                // Route through the service helper (R3): persist-first, no
427                // context rebuild. Unspecified halves keep their current
428                // persisted value; both are written back via the domain
429                // canonical `Display` (R1) so the on-disk strings match
430                // service/MCP/TUI.
431                let mut ctx = CliContext::load(&store_manager, &effective_file, config).await?;
432                let (cur_field, cur_order) = ctx.effective_board_sort();
433                let field = sort.map(|f| f.to_board_sort_field()).unwrap_or(cur_field);
434                let order = order.map(|o| o.to_sort_order()).unwrap_or(cur_order);
435                ctx.set_board_sort(field, order)?;
436                output::output_success(serde_json::json!({
437                    "board_sort_field": field.to_string(),
438                    "board_sort_order": order.to_string(),
439                }));
440            }
441            Some(cmd) => {
442                init_tracing_cli();
443                if !std::path::Path::new(&effective_file).exists() {
444                    return crate::output::output_error(&format!(
445                        "Board file not found: '{}'",
446                        effective_file
447                    ));
448                }
449                let mut ctx = CliContext::load(&store_manager, &effective_file, config).await?;
450                dispatch_subcommand(&mut ctx, cmd).await?;
451            }
452        }
453
454        Ok(())
455    }
456}