oxur-odm 0.2.0

An odd document manager - CLI tool for managing design documentation
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
//! Design documentation CLI tool

use anyhow::Result;
use clap::Parser;
use design::index::DocumentIndex;
use design::state::StateManager;
use serde::Deserialize;

mod cli;
mod commands;

use cli::{Cli, Commands, DebugCommands};
use commands::*;

/// Repo-root configuration (loaded from .odmrc at git root)
#[derive(Debug, Deserialize)]
struct RepoConfig {
    /// Preferred docs directory path (relative to repo root)
    docs_dir: Option<String>,
}

fn main() -> Result<()> {
    let mut cli = Cli::parse();

    // Smart default: If user didn't override --docs-dir, try to use repo-relative path
    apply_smart_default(&mut cli);

    // Setup state manager
    let mut state_mgr = match setup_state_manager(&cli) {
        Ok(mgr) => mgr,
        Err(e) => {
            design::errors::print_error_with_suggestion(
                "Failed to initialize state manager",
                &e,
                &format!("Make sure '{}' exists and contains design documents", cli.docs_dir),
            );
            std::process::exit(1);
        }
    };

    // Scan on startup
    if let Err(e) = scan_on_startup(&mut state_mgr, &cli.command) {
        design::errors::print_error("Startup scan failed", &e);
        // Non-fatal, continue
    }

    // Create document index
    let index = match create_document_index(&state_mgr, &cli.docs_dir) {
        Ok(idx) => idx,
        Err(e) => {
            design::errors::print_error_with_suggestion(
                "Failed to load document index",
                &e,
                &format!("Make sure '{}' exists and contains design documents", cli.docs_dir),
            );
            std::process::exit(1);
        }
    };

    // Execute command
    if let Err(e) = execute_command(cli.command, &index, &mut state_mgr) {
        design::errors::print_error("Command failed", &e);
        std::process::exit(1);
    }

    Ok(())
}

/// Load repo-root configuration from .odmrc
fn load_repo_config() -> Option<RepoConfig> {
    let root = design::git::get_repo_root()?;
    let config_path = root.join(".odmrc");

    if !config_path.exists() {
        return None;
    }

    let contents = std::fs::read_to_string(&config_path).ok()?;
    toml::from_str(&contents).ok()
}

/// Apply smart default for docs directory
pub(crate) fn apply_smart_default(cli: &mut Cli) {
    // Only apply smart defaults if user didn't override --docs-dir
    if cli.docs_dir != "docs" {
        return;
    }

    // Try to get repo root
    let Some(root) = design::git::get_repo_root() else {
        return;
    };

    // First, check for explicit .odmrc configuration at repo root
    if let Some(config) = load_repo_config() {
        if let Some(docs_dir) = config.docs_dir {
            // Use configured path (relative to repo root)
            let configured_path = root.join(&docs_dir);
            cli.docs_dir = configured_path.to_string_lossy().to_string();
            return;
        }
    }

    // No explicit config, fall back to heuristic:
    // If crates/design/docs exists OR if crates/design exists (suggesting workspace layout),
    // use crates/design/docs
    let workspace_path = root.join("crates/design/docs");
    let workspace_design = root.join("crates/design");

    if workspace_path.exists() || workspace_design.exists() {
        cli.docs_dir = workspace_path.to_string_lossy().to_string();
    }
    // Otherwise, stick with default "docs"
}

/// Initialize and configure the state manager
pub(crate) fn setup_state_manager(cli: &Cli) -> Result<StateManager> {
    StateManager::new(&cli.docs_dir)
}

/// Scan for filesystem changes on startup (unless running scan command explicitly)
pub(crate) fn scan_on_startup(state_mgr: &mut StateManager, command: &Commands) -> Result<()> {
    let needs_scan = !matches!(command, Commands::Scan { .. });

    if needs_scan {
        let result = state_mgr.quick_scan()?;
        if result.has_changes() {
            let total = result.total_changes();
            if total > 0 {
                let msg = format!(
                    "Detected {} change(s) ({} new, {} modified, {} deleted)",
                    total,
                    result.new_files.len(),
                    result.changed.len(),
                    result.deleted.len()
                );
                oxur_cli::common::output::info(&msg);
            }
        }
    }

    Ok(())
}

/// Create document index from state with filesystem fallback
pub(crate) fn create_document_index(
    state_mgr: &StateManager,
    docs_dir: &str,
) -> Result<DocumentIndex> {
    match DocumentIndex::from_state(state_mgr.state(), docs_dir) {
        Ok(idx) => Ok(idx),
        Err(_) => {
            oxur_cli::common::output::warning(
                "State loading failed, falling back to filesystem scan",
            );
            DocumentIndex::new(docs_dir)
        }
    }
}

/// Dispatch and execute the requested command
pub(crate) fn execute_command(
    command: Commands,
    index: &DocumentIndex,
    state_mgr: &mut StateManager,
) -> Result<()> {
    match command {
        Commands::List { state, verbose, removed, dev, component, tags, limit, all } => {
            let filters = commands::list::ListFilters { state, component, tags, limit, all };
            list_documents_with_state(index, Some(state_mgr), &filters, verbose, removed, dev)
        }
        Commands::Show { number, metadata_only } => show_document(index, number, metadata_only),
        Commands::New { title, author, component, tags } => {
            new_document(index, title, author, component, tags)
        }
        Commands::Validate { fix } => validate_documents(index, state_mgr, fix),
        Commands::Index { format } => generate_index(index, &format),
        Commands::AddHeaders { path } => add_headers(&path),
        Commands::Transition { path, state } => {
            transition_document(index, state_mgr, &path, &state)
        }
        Commands::SyncLocation { path } => sync_location(index, state_mgr, &path),
        Commands::UpdateIndex => update_index(index),
        Commands::Add { path, state, dry_run, interactive, yes, preview } => {
            if preview {
                preview_add(&path, state_mgr)
            } else {
                add_document(state_mgr, &path, state.as_deref(), dry_run, interactive, yes)
            }
        }
        Commands::AddBatch { patterns, dry_run, interactive } => {
            add_batch(state_mgr, patterns, dry_run, interactive)
        }
        Commands::Scan { fix, verbose } => scan_documents(state_mgr, fix, verbose),
        Commands::Debug(debug_cmd) => match debug_cmd {
            DebugCommands::State { number, format } => {
                if let Some(num) = number {
                    show_document_state(state_mgr, num)
                } else {
                    show_state(state_mgr, &format)
                }
            }
            DebugCommands::Checksums { verbose } => show_checksums(state_mgr, verbose),
            DebugCommands::Stats => show_stats(state_mgr),
            DebugCommands::Diff => show_diff(state_mgr),
            DebugCommands::Orphans => show_orphans(state_mgr),
            DebugCommands::Verify { number } => verify_document(state_mgr, number),
        },
        Commands::Search { query, state, metadata, case_sensitive } => {
            search(state_mgr, &query, state, metadata, case_sensitive)
        }
        Commands::Info { subcommand } => commands::info::execute(subcommand, state_mgr),
        Commands::Remove { doc } => remove_document(state_mgr, &doc),
        Commands::Rename { old, new } => commands::rename::execute(state_mgr, &old, &new),
        Commands::Replace { old, new, version } => replace_document(state_mgr, &old, &new, version),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Helper to create a test docs directory with sample documents
    fn setup_test_docs_dir() -> TempDir {
        let temp = TempDir::new().unwrap();
        let docs_dir = temp.path();

        // Create directory structure
        fs::create_dir_all(docs_dir.join("01-draft")).unwrap();
        fs::create_dir_all(docs_dir.join(".odm")).unwrap();

        // Create a sample document
        let doc_path = docs_dir.join("01-draft/0001-test-document.md");
        fs::write(
            &doc_path,
            r#"---
number: 1
title: Test Document
author: Test Author
state: Draft
created: 2024-01-01
updated: 2024-01-01
---

# Test Document

This is a test document.
"#,
        )
        .unwrap();

        // Initialize git repo for state manager
        std::process::Command::new("git").args(["init"]).current_dir(docs_dir).output().unwrap();

        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(docs_dir)
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(["commit", "-m", "Initial commit"])
            .current_dir(docs_dir)
            .output()
            .unwrap();

        temp
    }

    #[test]
    fn test_setup_state_manager_success() {
        let temp = setup_test_docs_dir();
        let cli = Cli {
            docs_dir: temp.path().to_str().unwrap().to_string(),
            command: Commands::List {
                state: None,
                verbose: false,
                removed: false,
                dev: false,
                component: None,
                tags: Vec::new(),
                limit: 20,
                all: false,
            },
        };

        let result = setup_state_manager(&cli);
        assert!(result.is_ok());

        let state_mgr = result.unwrap();
        assert_eq!(state_mgr.docs_dir(), temp.path());
    }

    #[test]
    fn test_scan_on_startup_with_scan_command() {
        let temp = setup_test_docs_dir();
        let mut state_mgr = StateManager::new(temp.path()).unwrap();

        // When command is Scan, should skip the scan
        let command = Commands::Scan { fix: false, verbose: false };

        let result = scan_on_startup(&mut state_mgr, &command);
        assert!(result.is_ok());
    }

    #[test]
    fn test_scan_on_startup_with_other_command() {
        let temp = setup_test_docs_dir();
        let mut state_mgr = StateManager::new(temp.path()).unwrap();

        // When command is not Scan, should perform scan
        let command = Commands::List {
            state: None,
            verbose: false,
            removed: false,
            dev: false,
            component: None,
            tags: Vec::new(),
            limit: 20,
            all: false,
        };

        let result = scan_on_startup(&mut state_mgr, &command);
        assert!(result.is_ok());
    }

    #[test]
    fn test_scan_on_startup_detects_new_file() {
        let temp = setup_test_docs_dir();
        let mut state_mgr = StateManager::new(temp.path()).unwrap();

        // Initial scan to clear state
        state_mgr.quick_scan().unwrap();

        // Add a new file
        let new_doc = temp.path().join("01-draft/0002-new-doc.md");
        fs::write(
            &new_doc,
            r#"---
number: 2
title: New Document
author: Test Author
state: Draft
created: 2024-01-02
updated: 2024-01-02
---

# New Document
"#,
        )
        .unwrap();

        let command = Commands::List {
            state: None,
            verbose: false,
            removed: false,
            dev: false,
            component: None,
            tags: Vec::new(),
            limit: 20,
            all: false,
        };

        // This should detect the new file
        let result = scan_on_startup(&mut state_mgr, &command);
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_document_index_success() {
        let temp = setup_test_docs_dir();
        let state_mgr = StateManager::new(temp.path()).unwrap();

        let result = create_document_index(&state_mgr, temp.path().to_str().unwrap());
        assert!(result.is_ok());

        let index = result.unwrap();
        // Just verify the index was created - don't check for specific documents
        // since the index might be empty depending on state
        assert!(index.next_number() >= 1);
    }

    #[test]
    fn test_create_document_index_fallback() {
        let temp = setup_test_docs_dir();
        let state_mgr = StateManager::new(temp.path()).unwrap();

        // Even if state loading fails, should fall back to filesystem scan
        let result = create_document_index(&state_mgr, temp.path().to_str().unwrap());
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_command_list() {
        let temp = setup_test_docs_dir();
        let mut state_mgr = StateManager::new(temp.path()).unwrap();
        let index = DocumentIndex::new(temp.path()).unwrap();

        let command = Commands::List {
            state: None,
            verbose: false,
            removed: false,
            dev: false,
            component: None,
            tags: Vec::new(),
            limit: 20,
            all: false,
        };

        let result = execute_command(command, &index, &mut state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_command_show() {
        let temp = setup_test_docs_dir();
        let mut state_mgr = StateManager::new(temp.path()).unwrap();
        let index = DocumentIndex::new(temp.path()).unwrap();

        let command = Commands::Show { number: 1, metadata_only: false };

        let result = execute_command(command, &index, &mut state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_command_show_nonexistent() {
        let temp = setup_test_docs_dir();
        let mut state_mgr = StateManager::new(temp.path()).unwrap();
        let index = DocumentIndex::new(temp.path()).unwrap();

        let command = Commands::Show { number: 9999, metadata_only: false };

        let result = execute_command(command, &index, &mut state_mgr);
        assert!(result.is_err());
    }

    #[test]
    fn test_apply_smart_default_when_default_docs() {
        // When using default "docs", should apply smart default based on repo structure
        let mut cli = Cli {
            docs_dir: "docs".to_string(),
            command: Commands::List {
                state: None,
                verbose: false,
                removed: false,
                dev: false,
                component: None,
                tags: Vec::new(),
                limit: 20,
                all: false,
            },
        };

        apply_smart_default(&mut cli);

        // Behavior depends on environment:
        // 1. If .odmrc exists with docs_dir, uses that
        // 2. If crates/design exists, uses crates/design/docs
        // 3. Otherwise stays as "docs"
        // We can't assert the exact value since it depends on the environment,
        // but we can verify the function runs without panicking
        assert!(cli.docs_dir == "docs" || cli.docs_dir.contains("crates/design/docs"));
    }

    #[test]
    fn test_apply_smart_default_when_custom_path() {
        // When using a custom path, should not change it
        let mut cli = Cli {
            docs_dir: "/custom/path".to_string(),
            command: Commands::List {
                state: None,
                verbose: false,
                removed: false,
                dev: false,
                component: None,
                tags: Vec::new(),
                limit: 20,
                all: false,
            },
        };

        apply_smart_default(&mut cli);

        // Should remain unchanged
        assert_eq!(cli.docs_dir, "/custom/path");
    }
}