kanban-cli 0.12.0

Command-line interface for the kanban project management tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use crate::cli::{BoardAction, BoardCommand, Cli, Commands};
use crate::context::CliContext;
use crate::handlers;
use crate::output;
use clap::{CommandFactory, FromArgMatches};
use kanban_core::AppConfig;
use kanban_persistence::{StoreFactory, StoreRegistry};
use kanban_service::StoreManager;
#[cfg(feature = "tui")]
use kanban_tui::App;

fn open_debug_log_file() -> Option<std::fs::File> {
    std::env::var("KANBAN_DEBUG_LOG").ok().and_then(|log_path| {
        std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_path)
            .ok()
    })
}

fn init_tracing_cli() {
    use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

    if let Some(log_file) = open_debug_log_file() {
        tracing_subscriber::registry()
            .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")))
            .with(
                tracing_subscriber::fmt::layer()
                    .with_writer(log_file)
                    .with_ansi(false)
                    .with_target(true)
                    .with_thread_ids(true)
                    .with_file(true)
                    .with_line_number(true),
            )
            .try_init()
            .ok();
        return;
    }
    tracing_subscriber::registry()
        .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")))
        .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
        .try_init()
        .ok();
}

#[cfg(feature = "tui")]
fn init_tracing_tui(
    error_log: std::sync::Arc<std::sync::Mutex<kanban_tui::error_log::ErrorLogState>>,
) {
    use kanban_tui::error_log::InMemoryLogLayer;
    use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

    let in_memory = InMemoryLogLayer::new(error_log);
    if let Some(log_file) = open_debug_log_file() {
        tracing_subscriber::registry()
            .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")))
            .with(
                tracing_subscriber::fmt::layer()
                    .with_writer(log_file)
                    .with_ansi(false)
                    .with_target(true)
                    .with_thread_ids(true)
                    .with_file(true)
                    .with_line_number(true),
            )
            .with(in_memory)
            .try_init()
            .ok();
        return;
    }
    tracing_subscriber::registry()
        .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")))
        .with(in_memory)
        .try_init()
        .ok();
}

fn parse_cli<I, T>(store_manager: &StoreManager, args: I) -> anyhow::Result<(Cli, clap::Command)>
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    let backend_names: Vec<String> = store_manager
        .local_backend_names()
        .into_iter()
        .map(str::to_owned)
        .collect();
    let mut cmd = Cli::command().mut_subcommand("migrate", |sub| {
        sub.mut_arg("backend", |arg| {
            arg.value_parser(clap::builder::PossibleValuesParser::new(
                backend_names.clone(),
            ))
        })
    });
    // For -V/--version and --help, clap returns Err with a kind that
    // signals "print this and exit cleanly". `e.exit()` dispatches
    // per-kind internally — DisplayHelp / DisplayVersion go to stdout
    // with exit code 0; real argument errors go to stderr with exit
    // code 2. No `match e.kind()` needed here. Without it the error
    // would reach the envelope seam, rendering the version / help text
    // as a CliResponse failure on stderr with exit code 1.
    let matches = cmd
        .try_get_matches_from_mut(args)
        .unwrap_or_else(|e| e.exit());
    let cli = Cli::from_arg_matches(&matches)?;
    Ok((cli, cmd))
}

#[derive(serde::Serialize)]
struct InitFileResult<'a> {
    file: &'a str,
}

fn reject_remote_locator(locator: &str, command: &str) -> anyhow::Result<()> {
    if kanban_core::is_remote_locator(locator) {
        anyhow::bail!(
            "'{locator}' is a remote server; {command} manages local files. \
             Point it at a file path, or manage the server's own storage on the server."
        );
    }
    Ok(())
}

async fn create_empty_storage_file(
    store_manager: &StoreManager,
    file: &str,
    config: &AppConfig,
) -> anyhow::Result<()> {
    let backend = store_manager
        .make_backend(file, config)
        .await
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    // `flush()` alone is a no-op here: a never-mutated backend's dirty flag
    // starts false, so nothing would land on disk without marking it dirty.
    backend.mark_dirty();
    backend.flush().await.map_err(|e| anyhow::anyhow!("{e}"))?;
    Ok(())
}

async fn dispatch_subcommand(ctx: &mut CliContext, cmd: Commands) -> anyhow::Result<()> {
    ctx.set_scope(crate::scope::CommandScope::from_command(&cmd));
    ctx.sync();
    match cmd {
        Commands::Board(board_cmd) => {
            handlers::board::handle(ctx, board_cmd.action).await?;
        }
        Commands::Column(column_cmd) => {
            handlers::column::handle(ctx, column_cmd.action).await?;
        }
        Commands::Card(card_cmd) => {
            handlers::card::handle(ctx, card_cmd.action).await?;
        }
        Commands::Relation(relation_cmd) => {
            handlers::relation::handle(ctx, relation_cmd.action).await?;
        }
        Commands::Sprint(sprint_cmd) => {
            handlers::sprint::handle(ctx, sprint_cmd.action).await?;
        }
        Commands::Export(args) => {
            handlers::export::handle_export(ctx, args).await?;
        }
        Commands::Import(args) => {
            handlers::export::handle_import(ctx, args).await?;
        }
        Commands::Completions { .. } | Commands::Migrate(_) | Commands::Init { .. } => {
            unreachable!()
        }
    }
    Ok(())
}

/// Builder entry point for the Kanban CLI.
///
/// A third-party backend crate constructs a `CliApp`, registers its own
/// `StoreFactory`, and calls [`CliApp::run`] from its own `main` — owning
/// the binary while reusing every CLI command here.
pub struct CliApp {
    registry: StoreRegistry,
    backends: kanban_backend::KanbanBackendRegistry,
    config: Option<AppConfig>,
}

impl Default for CliApp {
    /// Returns an empty `CliApp` with **no** registered backends. Callers
    /// must register at least one via [`CliApp::register_backend`] before
    /// `run` can produce a store.
    fn default() -> Self {
        Self {
            registry: StoreRegistry::new(),
            backends: kanban_backend::KanbanBackendRegistry::new(),
            config: None,
        }
    }
}

impl CliApp {
    /// Returns a `CliApp` pre-configured with all backends compiled in.
    /// SQLite is registered first so content-sniffing prefers it, JSON next
    /// as the catch-all fallback, and http last since it only ever claims a
    /// remote locator. When no backend features are active both registries
    /// are empty (same as [`Default`]).
    pub fn with_defaults() -> Self {
        let mut registry = kanban_persistence::StoreRegistry::new();
        let mut backends = kanban_backend::KanbanBackendRegistry::new();
        #[cfg(feature = "sqlite")]
        {
            backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
        }
        #[cfg(feature = "json")]
        {
            registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
            backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
        }
        #[cfg(feature = "http")]
        {
            backends.register(Box::new(kanban_backend_http::HttpBackendFactory));
        }
        Self {
            registry,
            backends,
            config: None,
        }
    }

    /// Registers an additional backend. `store_factory` builds the raw
    /// `PersistenceStore` (used by `make_store`/`make_store_with_config` for
    /// direct storage operations, e.g. `kanban init`'s empty-file creation);
    /// `backend_factory` builds the `KanbanBackend` that `make_backend`
    /// dispatches to. A backend that only ever needs `make_backend` cannot
    /// skip `store_factory` — both are required together, so a factory
    /// registered through this method is never reachable through only one
    /// dispatch path and unreachable through the other. Order matters for
    /// content sniffing on both registries — factories registered earlier
    /// win when multiple match.
    ///
    /// # Example — third-party binary with a custom backend
    ///
    /// A crate that owns its own `main` can reuse every CLI command while
    /// injecting a proprietary storage backend:
    ///
    /// ```no_run
    /// use kanban_cli::CliApp;
    /// use kanban_backend::KanbanBackendFactory;
    /// use kanban_core::AppConfig;
    /// use kanban_domain::KanbanResult;
    /// use kanban_persistence::{PersistenceError, PersistenceStore, StoreFactory};
    /// use std::sync::Arc;
    ///
    /// // A backend factory provided by a third-party crate.
    /// struct MyStoreFactory;
    /// impl StoreFactory for MyStoreFactory {
    ///     fn name(&self) -> &str { "my-backend" }
    ///     fn create(
    ///         &self,
    ///         locator: &str,
    ///     ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, PersistenceError> {
    ///         unimplemented!()
    ///     }
    /// }
    ///
    /// struct MyBackendFactory;
    /// #[async_trait::async_trait]
    /// impl KanbanBackendFactory for MyBackendFactory {
    ///     fn name(&self) -> &str { "my-backend" }
    ///     async fn create(
    ///         &self,
    ///         locator: &str,
    ///         config: &AppConfig,
    ///     ) -> KanbanResult<Arc<dyn kanban_backend::KanbanBackend>> {
    ///         unimplemented!()
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     CliApp::with_defaults()
    ///         .register_backend(Box::new(MyStoreFactory), Box::new(MyBackendFactory))
    ///         .run()
    ///         .await
    /// }
    /// ```
    pub fn register_backend(
        mut self,
        store_factory: Box<dyn StoreFactory>,
        backend_factory: Box<dyn kanban_backend::KanbanBackendFactory>,
    ) -> Self {
        self.registry.register(store_factory);
        self.backends.register(backend_factory);
        self
    }

    /// Overrides the `AppConfig` that `run` would otherwise load from disk.
    pub fn with_config(mut self, config: AppConfig) -> Self {
        self.config = Some(config);
        self
    }

    /// Exposes the underlying registry for inspection and tests.
    pub fn registry(&self) -> &StoreRegistry {
        &self.registry
    }

    /// Exposes the underlying backend registry for inspection and tests.
    pub fn backends(&self) -> &kanban_backend::KanbanBackendRegistry {
        &self.backends
    }

    /// Executes the CLI: parses args, loads config, and dispatches to the
    /// requested command (or launches the TUI if no subcommand was given).
    pub async fn run(self) -> anyhow::Result<()> {
        self.run_with_args(std::env::args_os()).await
    }

    /// Like [`run`], but accepts an explicit argument list instead of reading
    /// from `std::env::args_os()`. Useful for testing without spawning a
    /// subprocess.
    ///
    /// On failure, writes the `CliResponse` error envelope to stderr before
    /// returning, so every non-zero exit emits exactly one envelope regardless
    /// of whether the failure happened during startup or inside a handler.
    pub async fn run_with_args<I, T>(self, args: I) -> anyhow::Result<()>
    where
        I: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString> + Clone,
    {
        let result = self.run_inner(args).await;
        if let Err(ref e) = result {
            output::emit_error(&e.to_string());
        }
        result
    }

    async fn run_inner<I, T>(self, args: I) -> anyhow::Result<()>
    where
        I: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString> + Clone,
    {
        let store_manager = StoreManager::new(self.registry, self.backends);
        let (Cli { command, file }, mut cmd) = parse_cli(&store_manager, args)?;

        if let Some(Commands::Completions { shell }) = command {
            clap_complete::generate(shell, &mut cmd, "kanban", &mut std::io::stdout());
            return Ok(());
        }

        if !store_manager.has_backends() {
            anyhow::bail!(
                "No storage backends registered. \
                 Use CliApp::with_defaults() or call register_backend() before run()."
            );
        }

        let config = self.config.unwrap_or_else(kanban_service::config::load);
        let validated_file: Option<String> = match file {
            Some(ref p) => Some(
                kanban_service::validate_path(std::path::Path::new(p))?
                    .to_string_lossy()
                    .to_string(),
            ),
            None => None,
        };
        let effective_file = validated_file
            .clone()
            .unwrap_or_else(|| kanban_service::config::resolve_storage_location(&config));

        let needs_data_file = !matches!(
            &command,
            None | Some(Commands::Completions { .. })
                | Some(Commands::Migrate(_))
                | Some(Commands::Init { .. })
                | Some(Commands::Board(BoardCommand {
                    action: BoardAction::SetSort { .. },
                }))
        );
        if needs_data_file && validated_file.is_none() && config.storage_location.is_none() {
            anyhow::bail!(
                "\
No data file specified.

Provide the file path in one of these ways:
  kanban <path>           (first positional argument)
  KANBAN_FILE=<path>      (environment variable)
  storage_location = ...  (config file setting)"
            );
        }

        match command {
            None => {
                // KANBAN_FILE env var resolves into validated_file via clap's env attribute.
                let has_explicit_file =
                    validated_file.is_some() || config.storage_location.is_some();
                if has_explicit_file
                    && !kanban_core::is_remote_locator(&effective_file)
                    && !std::path::Path::new(&effective_file).exists()
                {
                    create_empty_storage_file(&store_manager, &effective_file, &config).await?;
                }
                use std::io::IsTerminal;
                if std::io::stdin().is_terminal() {
                    #[cfg(feature = "tui")]
                    {
                        let error_log = std::sync::Arc::new(std::sync::Mutex::new(
                            kanban_tui::error_log::ErrorLogState::default(),
                        ));
                        init_tracing_tui(std::sync::Arc::clone(&error_log));
                        let (mut app, save_rx) =
                            App::new_with_store(store_manager, validated_file).await?;
                        app.set_error_log(error_log);
                        app.run(save_rx).await?;
                    }
                    #[cfg(not(feature = "tui"))]
                    anyhow::bail!(
                        "TUI not available in this build. Run `kanban --help` for available subcommands."
                    );
                }
                // Non-TTY: file created above if needed, exit cleanly.
            }
            Some(Commands::Completions { .. }) => unreachable!(),
            Some(Commands::Migrate(args)) => {
                init_tracing_cli();
                reject_remote_locator(&args.source, "`migrate`")?;
                if let Some(ref output) = args.output {
                    reject_remote_locator(output, "`migrate`")?;
                }
                handlers::migrate::handle(&store_manager, args).await?;
            }
            Some(Commands::Init { board }) => {
                init_tracing_cli();
                reject_remote_locator(&effective_file, "`init`")?;
                match board {
                    Some(name) => {
                        let mut ctx =
                            CliContext::load(&store_manager, &effective_file, config).await?;
                        let created = ctx.mutate(|c| c.create_board_impl(name, None))?;
                        ctx.save().await?;
                        output::output_success(kanban_service::api::BoardResponse::from(&created));
                    }
                    None => {
                        if !std::path::Path::new(&effective_file).exists() {
                            create_empty_storage_file(&store_manager, &effective_file, &config)
                                .await?;
                        }
                        output::output_success(InitFileResult {
                            file: &effective_file,
                        });
                    }
                }
            }
            Some(Commands::Board(BoardCommand {
                action: BoardAction::SetSort { sort, order },
            })) => {
                init_tracing_cli();
                if sort.is_none() && order.is_none() {
                    return crate::output::output_error(
                        "board set-sort requires at least one of --sort and/or --order",
                    );
                }
                if !kanban_core::is_remote_locator(&effective_file)
                    && !std::path::Path::new(&effective_file).exists()
                {
                    create_empty_storage_file(&store_manager, &effective_file, &config).await?;
                }
                // Route through the service helper (R3): persist-first, no
                // context rebuild. Unspecified halves keep their current
                // persisted value; both are written back via the domain
                // canonical `Display` (R1) so the on-disk strings match
                // service/MCP/TUI.
                let mut ctx = CliContext::load(&store_manager, &effective_file, config).await?;
                let (cur_field, cur_order) = ctx.effective_board_sort();
                let field = sort.map(|f| f.to_board_sort_field()).unwrap_or(cur_field);
                let order = order.map(|o| o.to_sort_order()).unwrap_or(cur_order);
                ctx.set_board_sort(field, order)?;
                output::output_success(serde_json::json!({
                    "board_sort_field": field.to_string(),
                    "board_sort_order": order.to_string(),
                }));
            }
            Some(cmd) => {
                init_tracing_cli();
                if !kanban_core::is_remote_locator(&effective_file)
                    && !std::path::Path::new(&effective_file).exists()
                {
                    return crate::output::output_error(&format!(
                        "Board file not found: '{}'",
                        effective_file
                    ));
                }
                let mut ctx = CliContext::load(&store_manager, &effective_file, config).await?;
                dispatch_subcommand(&mut ctx, cmd).await?;
            }
        }

        Ok(())
    }
}