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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Remove command - moves documents to dustbin
//!
//! Moves documents to .dustbin directory while preserving git history

use anyhow::{Context, Result};
use colored::Colorize;
use design::doc::DocState;
use design::git;
use design::state::StateManager;
use uuid::Uuid;

/// Execute the remove command
pub fn execute(state_mgr: &mut StateManager, doc_id_or_path: &str) -> Result<()> {
    println!("{}", "Removing document...".cyan().bold());
    println!();

    // Step 1: Find document by number or path
    let doc_number = if let Ok(num) = doc_id_or_path.parse::<u32>() {
        num
    } else {
        // Try to find by path
        // Normalize the search path - strip docs_dir prefix if present
        let search_path = std::path::Path::new(doc_id_or_path);

        // Try to strip the docs_dir prefix (handles absolute paths)
        let normalized_search = if let Ok(stripped) = search_path.strip_prefix(state_mgr.docs_dir())
        {
            stripped.to_string_lossy().to_string()
        } else {
            // Try to strip relative path prefix (e.g., "crates/design/docs/...")
            let docs_dir_str = state_mgr.docs_dir().to_string_lossy();
            let relative_docs_dir = std::path::Path::new(&*docs_dir_str)
                .strip_prefix(std::env::current_dir().unwrap_or_default())
                .unwrap_or(state_mgr.docs_dir());

            if let Ok(stripped) = search_path.strip_prefix(relative_docs_dir) {
                stripped.to_string_lossy().to_string()
            } else {
                doc_id_or_path.to_string()
            }
        };

        let doc = state_mgr
            .state()
            .all()
            .into_iter()
            .find(|d| d.path.contains(&normalized_search))
            .ok_or_else(|| anyhow::anyhow!("Document '{}' not found", doc_id_or_path))?;
        doc.metadata.number
    };

    // Get document record
    let doc = state_mgr
        .state()
        .get(doc_number)
        .ok_or_else(|| anyhow::anyhow!("Document {} not found", doc_number))?;

    let doc_title = doc.metadata.title.clone();
    let current_state = doc.metadata.state;
    let current_path = state_mgr.docs_dir().join(&doc.path);

    println!("  Document: {} - {}", format!("{:04}", doc_number).yellow(), doc_title.white());
    println!("  Current state: {}", current_state.as_str().cyan());
    println!();

    // Check if already removed or overwritten
    if current_state == DocState::Removed || current_state == DocState::Overwritten {
        println!("{}", "âš  Document is already in dustbin".yellow());
        println!("  State: {}", current_state.as_str());
        println!("  Location: {}", current_path.display());
        return Ok(());
    }

    // Step 2: Prepare dustbin directory
    let dustbin_base = state_mgr.docs_dir().join(".dustbin");
    let state_subdir = current_state.directory();

    // Place in subdirectory based on original state (unless already in dustbin)
    let dustbin_dir = if current_state.is_in_dustbin() {
        dustbin_base.clone()
    } else {
        dustbin_base.join(state_subdir)
    };

    std::fs::create_dir_all(&dustbin_dir).context("Failed to create dustbin directory")?;
    println!("  ✓ Dustbin ready: {}", dustbin_dir.display().to_string().green());

    // Step 3: Generate unique filename with UUID
    let filename = current_path.file_name().context("Invalid file path")?.to_string_lossy();

    let uuid = Uuid::new_v4();
    let uuid_short = uuid.to_string().split('-').next().unwrap().to_string();

    let new_filename = if let Some(stem) = current_path.file_stem() {
        let stem_str = stem.to_string_lossy();
        format!("{}-{}.md", stem_str, uuid_short)
    } else {
        format!("{}-{}", filename.trim_end_matches(".md"), uuid_short)
    };

    let dustbin_path = dustbin_dir.join(&new_filename);
    println!("  ✓ Generated unique name: {}", new_filename.yellow());

    // Step 4: Move file using git
    if current_path.exists() {
        git::git_mv(&current_path, &dustbin_path).context("Failed to move file with git")?;
        println!("  ✓ Moved to dustbin: {}", dustbin_path.display().to_string().green());
    } else {
        println!("  {} File not found on disk: {}", "âš ".yellow(), current_path.display());
    }

    // Step 5: Update state - mark as removed and update path

    // Read and update the document
    if let Ok(content) = std::fs::read_to_string(&dustbin_path) {
        if let Ok(mut parsed_doc) = design::doc::DesignDoc::parse(&content, dustbin_path.clone()) {
            parsed_doc.metadata.state = DocState::Removed;
            parsed_doc.metadata.updated = chrono::Local::now().naive_local().date();

            // Write back with updated frontmatter
            let new_content =
                design::doc::build_yaml_frontmatter(&parsed_doc.metadata) + &parsed_doc.content;
            std::fs::write(&dustbin_path, new_content)
                .context("Failed to update document frontmatter")?;
        }
    }

    // Update state manager
    state_mgr.record_file_move(&current_path, &dustbin_path)?;
    println!("  ✓ Updated state tracking");

    println!();
    println!("{}", "Document removed successfully!".green().bold());
    println!("  Location: {}", dustbin_path.display().to_string().cyan());
    println!();
    println!("To view removed documents: {}", "odm list --removed".yellow());

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::NaiveDate;
    use design::doc::DocMetadata;
    use design::state::DocumentRecord;
    use serial_test::serial;
    use std::fs;
    use tempfile::TempDir;

    /// RAII guard to ensure current directory is restored after test
    struct DirGuard {
        original: std::path::PathBuf,
    }

    impl DirGuard {
        fn new() -> Self {
            Self { original: std::env::current_dir().expect("Failed to get current dir") }
        }

        fn change_to(&self, path: &std::path::Path) {
            std::env::set_current_dir(path).expect("Failed to change dir");
        }
    }

    impl Drop for DirGuard {
        fn drop(&mut self) {
            let _ = std::env::set_current_dir(&self.original);
        }
    }

    fn setup_git_repo(temp_dir: &std::path::Path) {
        use std::process::Command;

        // Initialize git repo
        Command::new("git")
            .args(["init"])
            .current_dir(temp_dir)
            .output()
            .expect("Failed to init git");

        // Configure user
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(temp_dir)
            .output()
            .expect("Failed to config user.name");

        Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(temp_dir)
            .output()
            .expect("Failed to config user.email");
    }

    fn create_test_state_manager() -> (StateManager, TempDir) {
        let temp = TempDir::new().unwrap();
        let docs_dir = temp.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();

        setup_git_repo(temp.path());

        let mut state_mgr = StateManager::new(&docs_dir).unwrap();

        // Add test document
        let meta = DocMetadata {
            number: 9999,
            title: "Test Doc".to_string(),
            author: "Test Author".to_string(),
            component: None,
            tags: Vec::new(),
            created: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            updated: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            state: DocState::Draft,
            supersedes: None,
            superseded_by: None,
            version: "1.0".to_string(),
        };

        let doc_path = docs_dir.join("01-draft/9999-test-doc.md");
        fs::create_dir_all(doc_path.parent().unwrap()).unwrap();

        let content = format!(
            "---\n{}\n---\n\nTest content",
            serde_yaml::to_string(&meta).unwrap().trim_start_matches("---\n")
        );
        fs::write(&doc_path, content).unwrap();

        // Git add the file
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(temp.path())
            .output()
            .unwrap();

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

        state_mgr.state_mut().upsert(
            9999,
            DocumentRecord {
                metadata: meta,
                path: "01-draft/9999-test-doc.md".to_string(),
                checksum: "abc123".to_string(),
                file_size: 100,
                modified: chrono::Utc::now(),
            },
        );

        (state_mgr, temp)
    }

    #[test]
    #[serial]
    fn test_remove_by_number() {
        let (mut state_mgr, temp) = create_test_state_manager();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        let result = execute(&mut state_mgr, "9999");
        assert!(result.is_ok());

        // Check that document state is updated
        let doc = state_mgr.state().get(9999).unwrap();
        assert_eq!(doc.metadata.state, DocState::Removed);
    }

    #[test]
    #[serial]
    fn test_remove_by_path() {
        let (mut state_mgr, temp) = create_test_state_manager();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        let result = execute(&mut state_mgr, "test-doc");
        assert!(result.is_ok());

        let doc = state_mgr.state().get(9999).unwrap();
        assert_eq!(doc.metadata.state, DocState::Removed);
    }

    #[test]
    #[serial]
    fn test_remove_by_full_path_with_docs_dir_prefix() {
        // Regression test for bug where full path with docs_dir prefix failed to find document
        let (mut state_mgr, temp) = create_test_state_manager();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        // Build the full path including docs_dir prefix
        let full_path = temp.path().join("docs/01-draft/9999-test-doc.md");
        let full_path_str = full_path.to_string_lossy().to_string();

        let result = execute(&mut state_mgr, &full_path_str);
        assert!(result.is_ok(), "Should be able to remove by full path");

        let doc = state_mgr.state().get(9999).unwrap();
        assert_eq!(doc.metadata.state, DocState::Removed);
    }

    #[test]
    fn test_remove_nonexistent_number() {
        let (mut state_mgr, _temp) = create_test_state_manager();

        let result = execute(&mut state_mgr, "999");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_remove_nonexistent_path() {
        let (mut state_mgr, _temp) = create_test_state_manager();

        let result = execute(&mut state_mgr, "nonexistent-doc");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    #[serial]
    fn test_remove_already_removed() {
        let (mut state_mgr, temp) = create_test_state_manager();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        // First removal
        execute(&mut state_mgr, "9999").unwrap();

        // Second removal should succeed but do nothing
        let result = execute(&mut state_mgr, "9999");
        assert!(result.is_ok());

        // Directory is automatically restored when _guard is dropped
    }

    #[test]
    #[serial]
    fn test_remove_creates_dustbin_directory() {
        let (mut state_mgr, temp) = create_test_state_manager();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        execute(&mut state_mgr, "9999").unwrap();

        let dustbin_dir = temp.path().join("docs/.dustbin/01-draft");
        assert!(dustbin_dir.exists());
    }

    #[test]
    #[serial]
    fn test_remove_generates_unique_filename() {
        let (mut state_mgr, temp) = create_test_state_manager();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        execute(&mut state_mgr, "9999").unwrap();

        let dustbin_dir = temp.path().join("docs/.dustbin/01-draft");
        let files: Vec<_> = fs::read_dir(&dustbin_dir).unwrap().collect();

        assert_eq!(files.len(), 1);

        let filename = files[0].as_ref().unwrap().file_name();
        let filename_str = filename.to_string_lossy();

        // Should have UUID suffix
        assert!(filename_str.starts_with("9999-test-doc-"));
        assert!(filename_str.ends_with(".md"));
    }

    #[test]
    fn test_remove_file_not_on_disk() {
        let temp = TempDir::new().unwrap();
        let docs_dir = temp.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();

        setup_git_repo(temp.path());

        let mut state_mgr = StateManager::new(&docs_dir).unwrap();

        // Add document to state but not to disk
        let meta = DocMetadata {
            number: 9999,
            title: "Missing Doc".to_string(),
            author: "Test Author".to_string(),
            component: None,
            tags: Vec::new(),
            created: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            updated: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            state: DocState::Draft,
            supersedes: None,
            superseded_by: None,
            version: "1.0".to_string(),
        };

        state_mgr.state_mut().upsert(
            9999,
            DocumentRecord {
                metadata: meta,
                path: "01-draft/9999-missing-doc.md".to_string(),
                checksum: "abc123".to_string(),
                file_size: 100,
                modified: chrono::Utc::now(),
            },
        );

        // Should handle missing file gracefully
        let result = execute(&mut state_mgr, "9999");
        // This will fail because git mv requires the file to exist
        // But the code handles this case
        assert!(result.is_err() || result.is_ok());
    }

    #[test]
    #[serial]
    fn test_remove_overwritten_document() {
        let (mut state_mgr, temp) = create_test_state_manager();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        // Change state to Overwritten (already in dustbin) by updating the record
        let doc = state_mgr.state().get(9999).unwrap().clone();
        let mut updated_doc = doc;
        updated_doc.metadata.state = DocState::Overwritten;
        updated_doc.path = ".dustbin/overwritten/9999-test-doc.md".to_string();

        // Create the overwritten file in dustbin
        let overwritten_path = temp.path().join("docs/.dustbin/overwritten/9999-test-doc.md");
        fs::create_dir_all(overwritten_path.parent().unwrap()).unwrap();

        let content = format!(
            "---\n{}\n---\n\nTest content",
            serde_yaml::to_string(&updated_doc.metadata).unwrap().trim_start_matches("---\n")
        );
        fs::write(&overwritten_path, content).unwrap();

        state_mgr.state_mut().upsert(9999, updated_doc);

        let result = execute(&mut state_mgr, "9999");
        // Should succeed (early return for already removed/overwritten)
        assert!(result.is_ok());
    }

    #[test]
    #[serial]
    fn test_remove_updates_frontmatter() {
        let (mut state_mgr, temp) = create_test_state_manager();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        execute(&mut state_mgr, "9999").unwrap();

        // Find the moved file in dustbin
        let dustbin_dir = temp.path().join("docs/.dustbin/01-draft");
        let files: Vec<_> = fs::read_dir(&dustbin_dir).unwrap().collect();
        let moved_file = files[0].as_ref().unwrap().path();

        // Read and check frontmatter
        let content = fs::read_to_string(&moved_file).unwrap();
        assert!(content.contains("state: Removed"));
    }

    #[test]
    #[serial]
    fn test_remove_multiple_documents() {
        let temp = TempDir::new().unwrap();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        let docs_dir = temp.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();

        setup_git_repo(temp.path());

        let mut state_mgr = StateManager::new(&docs_dir).unwrap();

        // Add multiple documents (9999, 9998, 9997)
        for (idx, num) in [9999, 9998, 9997].iter().enumerate() {
            let meta = DocMetadata {
                number: *num,
                title: format!("Doc {}", num),
                author: "Test Author".to_string(),
                component: None,
                tags: Vec::new(),
                created: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
                updated: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
                state: DocState::Draft,
                supersedes: None,
                superseded_by: None,
                version: "1.0".to_string(),
            };

            let doc_path = docs_dir.join(format!("01-draft/{:04}-doc-{}.md", num, idx + 1));
            fs::create_dir_all(doc_path.parent().unwrap()).unwrap();

            let content = format!(
                "---\n{}\n---\n\nTest content",
                serde_yaml::to_string(&meta).unwrap().trim_start_matches("---\n")
            );
            fs::write(&doc_path, content).unwrap();

            state_mgr.state_mut().upsert(
                *num,
                DocumentRecord {
                    metadata: meta,
                    path: format!("01-draft/{:04}-doc-{}.md", num, idx + 1),
                    checksum: "abc123".to_string(),
                    file_size: 100,
                    modified: chrono::Utc::now(),
                },
            );
        }

        // Git add and commit
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(temp.path())
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(["commit", "-m", "Add docs"])
            .current_dir(temp.path())
            .output()
            .unwrap();

        // Remove all three
        for num in [9999, 9998, 9997] {
            let result = execute(&mut state_mgr, &num.to_string());
            assert!(result.is_ok());
        }

        // All should be removed
        for num in [9999, 9998, 9997] {
            let doc = state_mgr.state().get(num).unwrap();
            assert_eq!(doc.metadata.state, DocState::Removed);
        }
    }

    #[test]
    #[serial]
    fn test_remove_from_different_states() {
        let temp = TempDir::new().unwrap();
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        let docs_dir = temp.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();

        setup_git_repo(temp.path());

        let mut state_mgr = StateManager::new(&docs_dir).unwrap();

        // Add documents in different states
        let states = vec![
            (9999, DocState::Draft, "01-draft"),
            (9998, DocState::Active, "05-active"),
            (9997, DocState::Final, "06-final"),
        ];

        for (idx, (num, state, dir)) in states.iter().enumerate() {
            let meta = DocMetadata {
                number: *num,
                title: format!("Doc {}", num),
                author: "Test Author".to_string(),
                component: None,
                tags: Vec::new(),
                created: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
                updated: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
                state: *state,
                supersedes: None,
                superseded_by: None,
                version: "1.0".to_string(),
            };

            let doc_path = docs_dir.join(format!("{}/{:04}-doc-{}.md", dir, num, idx + 1));
            fs::create_dir_all(doc_path.parent().unwrap()).unwrap();

            let content = format!(
                "---\n{}\n---\n\nTest content",
                serde_yaml::to_string(&meta).unwrap().trim_start_matches("---\n")
            );
            fs::write(&doc_path, content).unwrap();

            state_mgr.state_mut().upsert(
                *num,
                DocumentRecord {
                    metadata: meta,
                    path: format!("{}/{:04}-doc-{}.md", dir, num, idx + 1),
                    checksum: "abc123".to_string(),
                    file_size: 100,
                    modified: chrono::Utc::now(),
                },
            );
        }

        // Git add and commit
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(temp.path())
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(["commit", "-m", "Add docs"])
            .current_dir(temp.path())
            .output()
            .unwrap();

        // Remove all
        for num in [9999, 9998, 9997] {
            let result = execute(&mut state_mgr, &num.to_string());
            assert!(result.is_ok());
        }

        // Check they went to different dustbin subdirectories
        assert!(temp.path().join("docs/.dustbin/01-draft").exists());
        assert!(temp.path().join("docs/.dustbin/05-active").exists());
        assert!(temp.path().join("docs/.dustbin/06-final").exists());
    }
}