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_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    // For -V/--version and --help, clap returns Err with a kind that
98    // signals "print this and exit cleanly". `e.exit()` dispatches
99    // per-kind internally — DisplayHelp / DisplayVersion go to stdout
100    // with exit code 0; real argument errors go to stderr with exit
101    // code 2. No `match e.kind()` needed here. Without it the error
102    // would reach the envelope seam, rendering the version / help text
103    // as a CliResponse failure on stderr with exit code 1.
104    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    // `flush()` alone is a no-op here: a never-mutated backend's dirty flag
136    // starts false, so nothing would land on disk without marking it dirty.
137    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
174/// Builder entry point for the Kanban CLI.
175///
176/// A third-party backend crate constructs a `CliApp`, registers its own
177/// `StoreFactory`, and calls [`CliApp::run`] from its own `main` — owning
178/// the binary while reusing every CLI command here.
179pub struct CliApp {
180    registry: StoreRegistry,
181    backends: kanban_backend::KanbanBackendRegistry,
182    config: Option<AppConfig>,
183}
184
185impl Default for CliApp {
186    /// Returns an empty `CliApp` with **no** registered backends. Callers
187    /// must register at least one via [`CliApp::register_backend`] before
188    /// `run` can produce a store.
189    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    /// Returns a `CliApp` pre-configured with all backends compiled in.
200    /// SQLite is registered first so content-sniffing prefers it, JSON next
201    /// as the catch-all fallback, and http last since it only ever claims a
202    /// remote locator. When no backend features are active both registries
203    /// are empty (same as [`Default`]).
204    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    /// Registers an additional backend. `store_factory` builds the raw
228    /// `PersistenceStore` (used by `make_store`/`make_store_with_config` for
229    /// direct storage operations, e.g. `kanban init`'s empty-file creation);
230    /// `backend_factory` builds the `KanbanBackend` that `make_backend`
231    /// dispatches to. A backend that only ever needs `make_backend` cannot
232    /// skip `store_factory` — both are required together, so a factory
233    /// registered through this method is never reachable through only one
234    /// dispatch path and unreachable through the other. Order matters for
235    /// content sniffing on both registries — factories registered earlier
236    /// win when multiple match.
237    ///
238    /// # Example — third-party binary with a custom backend
239    ///
240    /// A crate that owns its own `main` can reuse every CLI command while
241    /// injecting a proprietary storage backend:
242    ///
243    /// ```no_run
244    /// use kanban_cli::CliApp;
245    /// use kanban_backend::KanbanBackendFactory;
246    /// use kanban_core::AppConfig;
247    /// use kanban_domain::KanbanResult;
248    /// use kanban_persistence::{PersistenceError, PersistenceStore, StoreFactory};
249    /// use std::sync::Arc;
250    ///
251    /// // A backend factory provided by a third-party crate.
252    /// struct MyStoreFactory;
253    /// impl StoreFactory for MyStoreFactory {
254    ///     fn name(&self) -> &str { "my-backend" }
255    ///     fn create(
256    ///         &self,
257    ///         locator: &str,
258    ///     ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, PersistenceError> {
259    ///         unimplemented!()
260    ///     }
261    /// }
262    ///
263    /// struct MyBackendFactory;
264    /// #[async_trait::async_trait]
265    /// impl KanbanBackendFactory for MyBackendFactory {
266    ///     fn name(&self) -> &str { "my-backend" }
267    ///     async fn create(
268    ///         &self,
269    ///         locator: &str,
270    ///         config: &AppConfig,
271    ///     ) -> KanbanResult<Arc<dyn kanban_backend::KanbanBackend>> {
272    ///         unimplemented!()
273    ///     }
274    /// }
275    ///
276    /// #[tokio::main]
277    /// async fn main() -> anyhow::Result<()> {
278    ///     CliApp::with_defaults()
279    ///         .register_backend(Box::new(MyStoreFactory), Box::new(MyBackendFactory))
280    ///         .run()
281    ///         .await
282    /// }
283    /// ```
284    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    /// Overrides the `AppConfig` that `run` would otherwise load from disk.
295    pub fn with_config(mut self, config: AppConfig) -> Self {
296        self.config = Some(config);
297        self
298    }
299
300    /// Exposes the underlying registry for inspection and tests.
301    pub fn registry(&self) -> &StoreRegistry {
302        &self.registry
303    }
304
305    /// Exposes the underlying backend registry for inspection and tests.
306    pub fn backends(&self) -> &kanban_backend::KanbanBackendRegistry {
307        &self.backends
308    }
309
310    /// Executes the CLI: parses args, loads config, and dispatches to the
311    /// requested command (or launches the TUI if no subcommand was given).
312    pub async fn run(self) -> anyhow::Result<()> {
313        self.run_with_args(std::env::args_os()).await
314    }
315
316    /// Like [`run`], but accepts an explicit argument list instead of reading
317    /// from `std::env::args_os()`. Useful for testing without spawning a
318    /// subprocess.
319    ///
320    /// On failure, writes the `CliResponse` error envelope to stderr before
321    /// returning, so every non-zero exit emits exactly one envelope regardless
322    /// of whether the failure happened during startup or inside a handler.
323    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                // KANBAN_FILE env var resolves into validated_file via clap's env attribute.
392                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                // Non-TTY: file created above if needed, exit cleanly.
419            }
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                // Route through the service helper (R3): persist-first, no
466                // context rebuild. Unspecified halves keep their current
467                // persisted value; both are written back via the domain
468                // canonical `Display` (R1) so the on-disk strings match
469                // service/MCP/TUI.
470                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}