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