oxur-odm 0.3.5

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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Rename command implementation

use anyhow::{bail, Context, Result};
use colored::Colorize;
use design::state::StateManager;
use std::path::{Path, PathBuf};

pub fn execute(state_mgr: &mut StateManager, old_id_or_path: &str, new_path: &str) -> Result<()> {
    println!();
    println!("{}", "Renaming document...".cyan().bold());
    println!();

    // Step 1: Resolve old path from ID or path
    let docs_dir = state_mgr.docs_dir();
    let old_path = if let Ok(num) = old_id_or_path.parse::<u32>() {
        // It's a document number - get the path from state
        let doc = state_mgr
            .state()
            .get(num)
            .ok_or_else(|| anyhow::anyhow!("Document {} not found", num))?;
        docs_dir.join(&doc.path).to_string_lossy().to_string()
    } else {
        // It's a file path
        old_id_or_path.to_string()
    };

    // Step 2: Parse and validate paths
    let (old_full, new_full) = parse_and_validate_paths(&old_path, new_path, docs_dir)?;

    println!("  From: {}", old_full.display().to_string().white());
    println!("  To:   {}", new_full.display().to_string().cyan());
    println!();

    // Step 2: Extract and verify numbers match
    let old_number = extract_number_from_path(&old_full)?;
    let new_number = extract_number_from_path(&new_full)?;

    if old_number != new_number {
        bail!(
            "{}

Cannot change document number during rename.
  Old number: {}
  New number: {}

To change document state/location, use: {}",
            "Number mismatch!".red().bold(),
            format!("{:04}", old_number).yellow(),
            format!("{:04}", new_number).yellow(),
            "odm transition <doc> <state>".cyan()
        );
    }

    println!("  ✓ Number preserved: {}", format!("{:04}", old_number).yellow());
    println!();

    // Step 3: Verify document exists in state
    let _doc_record = state_mgr.state().get(old_number).ok_or_else(|| {
        anyhow::anyhow!("Document {} not found in state. Run 'odm scan' to sync.", old_number)
    })?;

    // Step 4: Perform git mv
    design::git::git_mv(&old_full, &new_full).context("Failed to rename file with git")?;
    println!("  ✓ Renamed file with git mv");

    // Step 5: Update state manager - record the file move
    state_mgr.record_file_move(&old_full, &new_full).context("Failed to update state")?;
    println!("  ✓ Updated state");

    // Step 6: Save state
    state_mgr.save().context("Failed to save state")?;

    println!();
    println!("{}", "Rename complete!".green().bold());
    println!("  View with: {}", format!("odm show {}", old_number).yellow());
    println!();

    // Step 7: Update the index to reflect the rename
    println!();
    let index = design::index::DocumentIndex::from_state(state_mgr.state(), state_mgr.docs_dir())
        .context("Failed to create index")?;
    if let Err(e) = crate::commands::update_index::update_index(&index) {
        use colored::Colorize;
        println!("{} Failed to update index", "Warning:".yellow());
        println!("  {}", e);
        println!("  Run 'odm update-index' manually to sync the index");
    }

    Ok(())
}

/// Parse paths and validate they're within docs directory
fn parse_and_validate_paths(old: &str, new: &str, docs_dir: &Path) -> Result<(PathBuf, PathBuf)> {
    // Parse old path
    let old_path = resolve_path(old, docs_dir)?;

    // Validate old path exists
    if !old_path.exists() {
        bail!("Document not found: {}", old_path.display());
    }

    // Parse new path - for rename, preserve directory if new path is just a filename
    let new_path = if PathBuf::from(new).components().count() == 1 {
        // Just a filename - keep it in the same directory as the old file
        if let Some(parent) = old_path.parent() {
            parent.join(new)
        } else {
            resolve_path(new, docs_dir)?
        }
    } else {
        resolve_path(new, docs_dir)?
    };

    // Validate new path doesn't exist
    if new_path.exists() {
        bail!("Destination already exists: {}", new_path.display());
    }

    // Validate both are .md files
    if old_path.extension().and_then(|e| e.to_str()) != Some("md") {
        bail!("Old path must be a markdown file (.md)");
    }
    if new_path.extension().and_then(|e| e.to_str()) != Some("md") {
        bail!("New path must be a markdown file (.md)");
    }

    // Validate both are within docs directory
    let old_canonical = old_path.canonicalize().context("Failed to resolve old path")?;
    let docs_canonical = docs_dir.canonicalize().context("Failed to resolve docs directory")?;

    if !old_canonical.starts_with(&docs_canonical) {
        bail!("Old path must be within the docs directory");
    }

    // For new path, check its parent directory is within docs
    if let Some(new_parent) = new_path.parent() {
        if new_parent.exists() {
            let new_parent_canonical =
                new_parent.canonicalize().context("Failed to resolve new path parent")?;
            if !new_parent_canonical.starts_with(&docs_canonical) {
                bail!("New path must be within the docs directory");
            }
        }
    }

    Ok((old_path, new_path))
}

/// Resolve a path relative to docs directory or as absolute
fn resolve_path(path_str: &str, docs_dir: &Path) -> Result<PathBuf> {
    let path = PathBuf::from(path_str);

    // If it's already absolute, use as-is
    if path.is_absolute() {
        return Ok(path);
    }

    // Try relative to current directory first
    let relative_to_cwd = std::env::current_dir()?.join(&path);
    if relative_to_cwd.exists() {
        return Ok(relative_to_cwd);
    }

    // Try relative to docs directory
    let relative_to_docs = docs_dir.join(&path);
    if relative_to_docs.exists() {
        return Ok(relative_to_docs);
    }

    // For new paths (that don't exist), try to infer
    // If it looks like just a filename, put it in docs dir
    if path.components().count() == 1 {
        return Ok(docs_dir.join(&path));
    }

    // Otherwise use relative to current directory
    Ok(relative_to_cwd)
}

/// Extract document number from filename
fn extract_number_from_path(path: &Path) -> Result<u32> {
    let filename = path
        .file_name()
        .and_then(|f| f.to_str())
        .ok_or_else(|| anyhow::anyhow!("Invalid filename"))?;

    // Use existing extraction function
    let number = design::doc::extract_number_from_filename(filename);

    if number == 0 {
        bail!(
            "Could not extract document number from filename: {}. Expected format: 0001-title.md",
            filename
        );
    }

    Ok(number)
}

#[cfg(test)]
mod tests {
    use super::*;
    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);
        }
    }

    /// Helper to create a test StateManager with necessary setup
    fn setup_test_state_manager() -> (TempDir, StateManager) {
        let temp = TempDir::new().unwrap();
        let docs_dir = temp.path();

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

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

        std::process::Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(docs_dir)
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(docs_dir)
            .output()
            .unwrap();

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

        (temp, state_mgr)
    }

    #[test]
    fn test_extract_number() {
        assert_eq!(extract_number_from_path(Path::new("0001-test.md")).unwrap(), 1);
        assert_eq!(extract_number_from_path(Path::new("0042-feature.md")).unwrap(), 42);
        assert_eq!(extract_number_from_path(Path::new("/path/to/0123-doc.md")).unwrap(), 123);
    }

    #[test]
    fn test_extract_number_invalid() {
        assert!(extract_number_from_path(Path::new("test.md")).is_err());
        assert!(extract_number_from_path(Path::new("abc-test.md")).is_err());
    }

    #[test]
    fn test_extract_number_from_path_with_no_number() {
        let result = extract_number_from_path(Path::new("test-document.md"));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Could not extract document number"));
    }

    #[test]
    fn test_resolve_path_absolute() {
        let temp = TempDir::new().unwrap();
        let docs_dir = temp.path();
        let absolute_path = docs_dir.join("test.md");
        fs::write(&absolute_path, "test").unwrap();

        let result = resolve_path(absolute_path.to_str().unwrap(), docs_dir).unwrap();
        assert_eq!(result, absolute_path);
    }

    #[test]
    fn test_resolve_path_relative_to_docs() {
        let temp = TempDir::new().unwrap();
        let docs_dir = temp.path();
        let test_file = docs_dir.join("test.md");
        fs::write(&test_file, "test").unwrap();

        let result = resolve_path("test.md", docs_dir).unwrap();
        assert_eq!(result, test_file);
    }

    #[test]
    fn test_execute_document_not_in_state() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create a document but don't scan it (not in state)
        let old_path = temp.path().join("01-draft/0001-old-name.md");
        fs::write(
            &old_path,
            r#"---
number: 1
title: Old Name
state: Draft
created: 2024-01-01
updated: 2024-01-01
author: Test Author
---

# Old Name
"#,
        )
        .unwrap();

        // Try to rename without scanning - should fail
        let old_str = old_path.to_str().unwrap();
        let new_str = temp.path().join("01-draft/0001-new-name.md").to_str().unwrap().to_string();

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

    #[test]
    fn test_execute_number_mismatch_fails() {
        let (temp, mut state_mgr) = setup_test_state_manager();

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

# Test
"#,
        )
        .unwrap();

        // 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", "Initial"])
            .current_dir(temp.path())
            .output()
            .unwrap();

        // Scan to track
        state_mgr.quick_scan().unwrap();

        // Try to rename with different number - should fail
        let old_str = old_path.to_str().unwrap();
        let new_str = temp.path().join("01-draft/0002-test.md").to_str().unwrap().to_string();

        let result = execute(&mut state_mgr, old_str, &new_str);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Number mismatch"));
    }

    #[test]
    fn test_execute_old_file_not_found() {
        let (_temp, mut state_mgr) = setup_test_state_manager();

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

    #[test]
    fn test_execute_new_file_already_exists() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create two documents
        let old_path = temp.path().join("01-draft/0001-old.md");
        let new_path = temp.path().join("01-draft/0001-new.md");

        fs::write(&old_path, "old").unwrap();
        fs::write(&new_path, "new").unwrap();

        // 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", "Initial"])
            .current_dir(temp.path())
            .output()
            .unwrap();

        let result =
            execute(&mut state_mgr, old_path.to_str().unwrap(), new_path.to_str().unwrap());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Destination already exists"));
    }

    #[test]
    fn test_execute_not_markdown_file() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        let old_path = temp.path().join("01-draft/0001-test.txt");
        fs::write(&old_path, "test").unwrap();

        let result = execute(
            &mut state_mgr,
            old_path.to_str().unwrap(),
            temp.path().join("01-draft/0001-new.txt").to_str().unwrap(),
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must be a markdown file"));
    }

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

        let outside_path = temp.path().join("outside.md");
        fs::write(&outside_path, "test").unwrap();

        let result = parse_and_validate_paths(outside_path.to_str().unwrap(), "new.md", &docs_dir);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must be within the docs directory"));
    }

    // Note: We cannot test successful rename in unit tests because git mv requires
    // the files to be in the main repository, not in a temp directory. The success
    // path is covered by integration tests and manual testing.

    #[test]
    fn test_execute_new_path_not_markdown() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create a markdown file
        let old_path = temp.path().join("01-draft/0001-test.md");
        fs::write(&old_path, "test").unwrap();

        // Try to rename to non-markdown extension
        let new_path = temp.path().join("01-draft/0001-test.txt");

        let result =
            execute(&mut state_mgr, old_path.to_str().unwrap(), new_path.to_str().unwrap());

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must be a markdown file"));
    }

    #[test]
    fn test_extract_number_from_path_invalid_filename() {
        // Test with a path that has an invalid filename component
        let result = extract_number_from_path(Path::new(""));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid filename"));
    }

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

        // Create a file in current directory (temp root, not docs)
        let cwd_file = temp.path().join("file-in-cwd.md");
        fs::write(&cwd_file, "test").unwrap();

        // Change to temp directory
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        // Resolve relative path - should find it in cwd
        let result = resolve_path("file-in-cwd.md", &docs_dir);

        // Restore original directory

        assert!(result.is_ok());
        // Canonicalize both paths to handle /var vs /private/var on macOS
        assert_eq!(result.unwrap().canonicalize().unwrap(), cwd_file.canonicalize().unwrap());
    }

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

        // Change to temp directory
        let _guard = DirGuard::new();
        _guard.change_to(temp.path());

        // Try to resolve a multi-component path that doesn't exist
        // Should return relative to cwd
        let result = resolve_path("subdir/newfile.md", &docs_dir).unwrap();

        // Restore original directory

        // Should resolve to cwd + path
        assert!(result.to_str().unwrap().contains("subdir"));
        assert!(result.to_str().unwrap().ends_with("newfile.md"));
    }

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

        // Create a file inside docs
        let old_path = docs_dir.join("0001-test.md");
        fs::write(&old_path, "test").unwrap();

        // Create a directory outside docs
        let outside_dir = temp.path().join("outside");
        fs::create_dir_all(&outside_dir).unwrap();

        // Try to rename to a file in the outside directory
        let new_path = outside_dir.join("0001-test.md");

        let result = parse_and_validate_paths(
            old_path.to_str().unwrap(),
            new_path.to_str().unwrap(),
            &docs_dir,
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must be within the docs directory"));
    }

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

        // Create a file inside docs
        let old_path = docs_dir.join("0001-test.md");
        fs::write(&old_path, "test").unwrap();

        // Create a path with no parent (root path)
        // This tests the None case for new_path.parent()
        let result = parse_and_validate_paths(
            old_path.to_str().unwrap(),
            "/0001-test.md", // Root level, no parent
            &docs_dir,
        );

        // Should fail because root is not within docs directory
        assert!(result.is_err());
    }

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

        // Create a file inside docs
        let old_path = docs_dir.join("0001-test.md");
        fs::write(&old_path, "test").unwrap();

        // Try to rename to a path whose parent directory doesn't exist yet
        // This is valid - the parent will be created during rename
        let new_path = docs_dir.join("nonexistent-dir/0001-test.md");

        let result = parse_and_validate_paths(
            old_path.to_str().unwrap(),
            new_path.to_str().unwrap(),
            &docs_dir,
        );

        // Should succeed because the parent doesn't exist (line 110)
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_with_document_id() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create and track a document
        let old_path = temp.path().join("01-draft/0001-old-name.md");
        fs::write(
            &old_path,
            r#"---
number: 1
title: Old Name
state: Draft
created: 2024-01-01
updated: 2024-01-01
author: Test Author
---

# Old Name
"#,
        )
        .unwrap();

        // 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", "Initial"])
            .current_dir(temp.path())
            .output()
            .unwrap();

        // Scan to track
        state_mgr.quick_scan().unwrap();

        // Verify document is in state
        let doc = state_mgr.state().get(1);
        assert!(doc.is_some());

        // Test with document ID "1" instead of file path
        // Note: This will fail git mv in tests, but we can test that it resolves the ID correctly
        let result = execute(&mut state_mgr, "1", "0001-new-name.md");

        // The test will fail at git mv stage (expected in test environment)
        // but if it fails with "Document not found", that means ID resolution failed
        if let Err(e) = result {
            let err_msg = e.to_string();
            // Should NOT fail with "Document not found" - that would mean ID resolution failed
            assert!(!err_msg.contains("Document 1 not found"), "ID resolution failed: {}", err_msg);
            // It's OK to fail with git errors in test environment
        }
    }

    #[test]
    fn test_execute_with_invalid_document_id() {
        let (_temp, mut state_mgr) = setup_test_state_manager();

        // Try to rename with a document ID that doesn't exist
        let result = execute(&mut state_mgr, "9999", "0001-new-name.md");

        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Document 9999 not found"));
    }
}