padz 0.10.1

A fast, project-aware scratch pad for the command line
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! # CLI Layer
//!
//! This module is **one possible UI client** for padz—it is not the application itself.
//!
//! The CLI layer is the **only** place in the codebase that:
//! - Knows about terminal I/O (stdout, stderr)
//! - Uses `std::process::exit`
//! - Handles argument parsing
//! - Formats output for human consumption
//!
//! ## Responsibilities
//!
//! 1. **Argument Parsing**: Convert shell arguments into typed commands via clap
//! 2. **Context Setup**: Initialize `AppContext` with API, scope, and configuration
//! 3. **API Dispatch**: Call the appropriate `PadzApi` method
//! 4. **Output Formatting**: Convert `CmdResult` into terminal output (colors, tables, etc.)
//! 5. **Error Handling**: Convert errors to user-friendly messages and exit codes
//!
//! ## Testing Strategy
//!
//! CLI tests verify two directions:
//!
//! **Input Testing**: Given shell argument strings, verify:
//! - Arguments parse correctly
//! - Correct API method is called
//! - Arguments are passed correctly to API
//!
//! **Output Testing**: Given a `CmdResult`, verify:
//! - Correct text is written to stdout
//! - Colors and formatting are applied correctly
//! - Error messages go to stderr
//!
//! CLI tests should **not** test business logic—that's the command layer's job.
//!
//! ## Structure
//!
//! - `run()`: Main dispatch logic (called by `main.rs`)
//! - `init_context()`: Builds `AppContext` with API and configuration
//! - `handle_*()`: Per-command handlers that call API and format output
//! - `print_*()`: Output formatting functions

use super::render::{
    print_messages, render_full_pads, render_pad_list, render_pad_list_deleted, render_text_list,
};
use super::setup::{
    parse_cli, Cli, Commands, CompletionShell, CoreCommands, DataCommands, MiscCommands,
    PadCommands,
};
use outstanding::OutputMode;
use padzapp::api::{ConfigAction, PadFilter, PadStatusFilter, PadzApi, TodoStatus};
use padzapp::clipboard::{copy_to_clipboard, format_for_clipboard, get_from_clipboard};
use padzapp::editor::open_in_editor;
use padzapp::error::Result;
use padzapp::init::initialize;
use padzapp::model::Scope;
use padzapp::model::{extract_title_and_body, parse_pad_content};
use padzapp::store::fs::FileStore;
use std::io::{IsTerminal, Read};
use std::path::{Path, PathBuf};

/// Helper to read a pad file and copy its content to the system clipboard.
/// Silently ignores errors (clipboard operations are best-effort).
fn copy_pad_to_clipboard(path: &Path) {
    if let Ok(content) = std::fs::read_to_string(path) {
        if let Some((title, body)) = extract_title_and_body(&content) {
            let clipboard_text = format_for_clipboard(&title, &body);
            let _ = copy_to_clipboard(&clipboard_text);
        }
    }
}

struct AppContext {
    api: PadzApi<FileStore>,
    scope: Scope,
    import_extensions: Vec<String>,
    output_mode: OutputMode,
}

pub fn run() -> Result<()> {
    // parse_cli() uses outstanding-clap's Outstanding which handles
    // help display (including topics) and errors automatically.
    // It also extracts the output mode from the --output flag.
    let (cli, output_mode) = parse_cli();

    // Handle completions before context init (they don't need API)
    if let Some(Commands::Misc(MiscCommands::Completions { shell })) = &cli.command {
        return handle_completions(*shell);
    }

    let mut ctx = init_context(&cli, output_mode)?;

    match cli.command {
        Some(Commands::Core(cmd)) => match cmd {
            CoreCommands::Create {
                title,
                no_editor,
                inside,
            } => {
                // Join all title words with spaces
                let title = if title.is_empty() {
                    None
                } else {
                    Some(title.join(" "))
                };
                handle_create(&mut ctx, title, no_editor, inside)
            }
            CoreCommands::List {
                search,
                deleted,
                peek,
                planned,
                done,
                in_progress,
            } => handle_list(&mut ctx, search, deleted, peek, planned, done, in_progress),
            CoreCommands::Search { term } => handle_search(&mut ctx, term),
        },
        Some(Commands::Pad(cmd)) => match cmd {
            PadCommands::View { indexes, peek } => handle_view(&mut ctx, indexes, peek),
            PadCommands::Edit { indexes } => handle_edit(&mut ctx, indexes),
            PadCommands::Open { indexes } => handle_open(&mut ctx, indexes),
            PadCommands::Delete {
                indexes,
                done_status,
            } => handle_delete(&mut ctx, indexes, done_status),
            PadCommands::Restore { indexes } => handle_restore(&mut ctx, indexes),
            PadCommands::Pin { indexes } => handle_pin(&mut ctx, indexes),
            PadCommands::Unpin { indexes } => handle_unpin(&mut ctx, indexes),
            PadCommands::Path { indexes } => handle_paths(&mut ctx, indexes),
            PadCommands::Complete { indexes } => handle_complete(&mut ctx, indexes),
            PadCommands::Reopen { indexes } => handle_reopen(&mut ctx, indexes),
            PadCommands::Move { indexes, root } => handle_move(&mut ctx, indexes, root),
        },
        Some(Commands::Data(cmd)) => match cmd {
            DataCommands::Purge {
                indexes,
                yes,
                recursive,
            } => handle_purge(&mut ctx, indexes, yes, recursive),
            DataCommands::Export {
                single_file,
                indexes,
            } => handle_export(&mut ctx, indexes, single_file),
            DataCommands::Import { paths } => handle_import(&mut ctx, paths),
        },
        Some(Commands::Misc(cmd)) => match cmd {
            MiscCommands::Doctor => handle_doctor(&mut ctx),
            MiscCommands::Config { key, value } => handle_config(&mut ctx, key, value),
            MiscCommands::Init => handle_init(&ctx),
            MiscCommands::Completions { shell } => handle_completions(shell),
        },
        None => handle_list(&mut ctx, None, false, false, false, false, false),
    }
}

fn init_context(cli: &Cli, output_mode: OutputMode) -> Result<AppContext> {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    let ctx = initialize(&cwd, cli.global);

    Ok(AppContext {
        api: ctx.api,
        scope: ctx.scope,
        import_extensions: ctx.config.import_extensions.clone(),
        output_mode,
    })
}

fn handle_create(
    ctx: &mut AppContext,
    title: Option<String>,
    no_editor: bool,
    inside: Option<String>,
) -> Result<()> {
    // === Pre-dispatch: Resolve input from stdin/clipboard ===
    let (final_title, initial_content, should_open_editor) = resolve_create_input(title, no_editor);

    // === Dispatch: Call API ===
    let title_to_use = final_title.unwrap_or_else(|| "Untitled".to_string());
    let parent = inside.as_deref();
    let result = ctx
        .api
        .create_pad(ctx.scope, title_to_use, initial_content, parent)?;

    // === Output: Render messages ===
    print_messages(&result.messages, ctx.output_mode);

    // === Post-dispatch: Editor and clipboard side effects ===
    if should_open_editor && !result.pad_paths.is_empty() {
        let path = &result.pad_paths[0];
        open_in_editor(path)?;
        copy_pad_to_clipboard(path);
    }

    Ok(())
}

/// Pre-dispatch logic for create: resolve title and content from stdin/clipboard.
/// Returns (title, content, should_open_editor).
fn resolve_create_input(title: Option<String>, no_editor: bool) -> (Option<String>, String, bool) {
    let mut final_title = title;
    let mut initial_content = String::new();
    let mut should_open_editor = !no_editor;

    // 1. Check for piped input (stdin)
    if !std::io::stdin().is_terminal() {
        let mut buffer = String::new();
        if std::io::stdin().read_to_string(&mut buffer).is_ok() && !buffer.trim().is_empty() {
            if final_title.is_none() {
                if let Some((parsed_title, _)) = parse_pad_content(&buffer) {
                    final_title = Some(parsed_title);
                }
            }
            initial_content = buffer;
            should_open_editor = false; // Piped input skips editor
        }
    }

    // 2. If still no content/title, check clipboard
    if final_title.is_none() && initial_content.is_empty() {
        if let Ok(clipboard_content) = get_from_clipboard() {
            if !clipboard_content.trim().is_empty() {
                if let Some((parsed_title, _)) = parse_pad_content(&clipboard_content) {
                    final_title = Some(parsed_title);
                }
                initial_content = clipboard_content;
            }
        }
    }

    (final_title, initial_content, should_open_editor)
}

fn handle_list(
    ctx: &mut AppContext,
    search: Option<String>,
    deleted: bool,
    peek: bool,
    planned: bool,
    done: bool,
    in_progress: bool,
) -> Result<()> {
    // Determine todo status filter
    let todo_status = if planned {
        Some(TodoStatus::Planned)
    } else if done {
        Some(TodoStatus::Done)
    } else if in_progress {
        Some(TodoStatus::InProgress)
    } else {
        None // No filter = show all
    };

    let filter = PadFilter {
        status: if deleted {
            PadStatusFilter::Deleted
        } else {
            PadStatusFilter::Active
        },
        search_term: search,
        todo_status,
    };

    let result = ctx.api.get_pads(ctx.scope, filter)?;

    // Use outstanding-based rendering
    let output = if deleted {
        render_pad_list_deleted(&result.listed_pads, peek, ctx.output_mode)
    } else {
        render_pad_list(&result.listed_pads, peek, ctx.output_mode)
    };
    print!("{}", output);

    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_view(ctx: &mut AppContext, indexes: Vec<String>, peek: bool) -> Result<()> {
    let result = ctx.api.view_pads(ctx.scope, &indexes)?;
    let output = if peek {
        // Reuse list rendering for peek view
        render_pad_list(&result.listed_pads, true, ctx.output_mode)
    } else {
        render_full_pads(&result.listed_pads, ctx.output_mode)
    };
    print!("{}", output);
    print_messages(&result.messages, ctx.output_mode);

    // Copy viewed pads to clipboard
    // Note: dp.pad.content already includes the title as the first line
    if !result.listed_pads.is_empty() {
        let clipboard_text: String = result
            .listed_pads
            .iter()
            .map(|dp| dp.pad.content.clone())
            .collect::<Vec<_>>()
            .join("\n\n---\n\n");
        let _ = copy_to_clipboard(&clipboard_text);
    }

    Ok(())
}

fn handle_edit(ctx: &mut AppContext, indexes: Vec<String>) -> Result<()> {
    // === Dispatch: Call API (view returns paths) ===
    let result = ctx.api.view_pads(ctx.scope, &indexes)?;

    // === Post-dispatch: Editor and clipboard side effects ===
    for path in &result.pad_paths {
        open_in_editor(path)?;
        copy_pad_to_clipboard(path);
    }

    Ok(())
}

fn handle_open(ctx: &mut AppContext, indexes: Vec<String>) -> Result<()> {
    // Open behaves exactly like edit now - just open the file.
    // The "sync only if changed" logic is handled by the lazy reconciler (padz list).
    handle_edit(ctx, indexes)
}

fn handle_delete(ctx: &mut AppContext, indexes: Vec<String>, done_status: bool) -> Result<()> {
    if done_status {
        // Delete all pads with Done status
        let filter = PadFilter {
            status: PadStatusFilter::Active,
            search_term: None,
            todo_status: Some(TodoStatus::Done),
        };
        let pads = ctx.api.get_pads(ctx.scope, filter)?;

        if pads.listed_pads.is_empty() {
            println!("No done pads to delete.");
            return Ok(());
        }

        // Collect indexes of done pads
        let done_indexes: Vec<String> = pads
            .listed_pads
            .iter()
            .map(|dp| dp.index.to_string())
            .collect();

        let result = ctx.api.delete_pads(ctx.scope, &done_indexes)?;
        print_messages(&result.messages, ctx.output_mode);
    } else {
        let result = ctx.api.delete_pads(ctx.scope, &indexes)?;
        print_messages(&result.messages, ctx.output_mode);
    }
    Ok(())
}

fn handle_restore(ctx: &mut AppContext, indexes: Vec<String>) -> Result<()> {
    let result = ctx.api.restore_pads(ctx.scope, &indexes)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_pin(ctx: &mut AppContext, indexes: Vec<String>) -> Result<()> {
    let result = ctx.api.pin_pads(ctx.scope, &indexes)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_unpin(ctx: &mut AppContext, indexes: Vec<String>) -> Result<()> {
    let result = ctx.api.unpin_pads(ctx.scope, &indexes)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_complete(ctx: &mut AppContext, indexes: Vec<String>) -> Result<()> {
    let result = ctx.api.complete_pads(ctx.scope, &indexes)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_move(ctx: &mut AppContext, mut indexes: Vec<String>, root: bool) -> Result<()> {
    let destination = if root {
        // If moving to root, all indexes are sources
        None
    } else {
        // Otherwise, last index is destination
        if indexes.len() < 2 {
            // Need at least source and dest
            // Actually, if indexes.len() == 1 and user expects "move 1 to root" they must use --root
            // We should clarify this in error message
            return Err(padzapp::error::PadzError::Api(
                "Missing destination. Use `padz move <SOURCE>... <DEST>` or `padz move <SOURCE>... --root`".to_string()
            ));
        }
        Some(indexes.pop().unwrap())
    };

    let result = ctx
        .api
        .move_pads(ctx.scope, &indexes, destination.as_deref())?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_reopen(ctx: &mut AppContext, indexes: Vec<String>) -> Result<()> {
    let result = ctx.api.reopen_pads(ctx.scope, &indexes)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_search(ctx: &mut AppContext, term: String) -> Result<()> {
    let filter = PadFilter {
        status: PadStatusFilter::Active,
        search_term: Some(term),
        todo_status: None,
    };
    let result = ctx.api.get_pads(ctx.scope, filter)?;
    let output = render_pad_list(&result.listed_pads, false, ctx.output_mode);
    print!("{}", output);
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_paths(ctx: &mut AppContext, indexes: Vec<String>) -> Result<()> {
    let result = ctx.api.pad_paths(ctx.scope, &indexes)?;
    let lines: Vec<String> = result
        .pad_paths
        .iter()
        .map(|path| path.display().to_string())
        .collect();
    let output = render_text_list(&lines, "No pad paths found.", ctx.output_mode);
    print!("{}", output);
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_purge(
    ctx: &mut AppContext,
    indexes: Vec<String>,
    yes: bool,
    recursive: bool,
) -> Result<()> {
    // Pass confirmation flag directly to API
    // If not confirmed, API returns an error with a message about using --yes/-y
    let result = ctx.api.purge_pads(ctx.scope, &indexes, recursive, yes)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_export(
    ctx: &mut AppContext,
    indexes: Vec<String>,
    single_file: Option<String>,
) -> Result<()> {
    let result = if let Some(title) = single_file {
        ctx.api
            .export_pads_single_file(ctx.scope, &indexes, &title)?
    } else {
        ctx.api.export_pads(ctx.scope, &indexes)?
    };
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_import(ctx: &mut AppContext, paths: Vec<String>) -> Result<()> {
    let paths: Vec<PathBuf> = paths.iter().map(PathBuf::from).collect();
    let result = ctx
        .api
        .import_pads(ctx.scope, paths, &ctx.import_extensions)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_doctor(ctx: &mut AppContext) -> Result<()> {
    let result = ctx.api.doctor(ctx.scope)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_config(ctx: &mut AppContext, key: Option<String>, value: Option<String>) -> Result<()> {
    let action = match (key.clone(), value) {
        (None, _) => ConfigAction::ShowAll,
        (Some(k), None) => ConfigAction::ShowKey(k),
        (Some(k), Some(v)) => ConfigAction::Set(k, v),
    };

    let result = ctx.api.config(ctx.scope, action)?;
    let mut lines = Vec::new();

    // If showing all, we need to iterate available keys manually since we don't have an iterator yet.
    // Or we just show known keys.
    if let Some(config) = &result.config {
        // If specific key was requested, show just that (handled by messages mostly,
        // but let's see what result.config has).
        // If action was ShowAll, we show everything.
        // If action was ShowKey, API might return config but messages have the info.

        if key.is_none() {
            // Show all known keys
            for (k, v) in config.list_all() {
                lines.push(format!("{} = {}", k, v));
            }
        }
    }
    let output = render_text_list(&lines, "No configuration values.", ctx.output_mode);
    print!("{}", output);
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_init(ctx: &AppContext) -> Result<()> {
    let result = ctx.api.init(ctx.scope)?;
    print_messages(&result.messages, ctx.output_mode);
    Ok(())
}

fn handle_completions(shell: CompletionShell) -> Result<()> {
    // Output the shell setup script generated by clap_complete
    // Users should add to their shell rc: eval "$(padz completions bash)"
    use super::setup::build_command;
    use clap_complete::env::{CompleteEnv, EnvCompleter};

    let shell_name = match shell {
        CompletionShell::Bash => "bash",
        CompletionShell::Zsh => "zsh",
    };

    // Generate the shell completion script by simulating the COMPLETE env var
    // clap_complete outputs the registration script when COMPLETE is set
    let completer = CompleteEnv::with_factory(build_command);
    let mut buf = Vec::new();

    match shell {
        CompletionShell::Bash => {
            clap_complete::env::Bash
                .write_registration("COMPLETE", "padz", "padz", "padz", &mut buf)
                .expect("Failed to generate bash completions");
        }
        CompletionShell::Zsh => {
            clap_complete::env::Zsh
                .write_registration("COMPLETE", "padz", "padz", "padz", &mut buf)
                .expect("Failed to generate zsh completions");
        }
    }

    println!("# {} completion for padz", shell_name);
    println!(
        "# Add to your shell rc file: eval \"$(padz completions {})\"",
        shell_name
    );
    println!();
    print!("{}", String::from_utf8_lossy(&buf));

    // Suppress unused variable warning
    let _ = completer;

    Ok(())
}