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
//! Sync location command implementation

use anyhow::{Context, Result};
use colored::*;
use design::doc::DesignDoc;
use design::index::DocumentIndex;
use design::state::StateManager;
use std::fs;
use std::path::PathBuf;

/// Move document to match its header state
pub fn sync_location(
    index: &DocumentIndex,
    state_mgr: &StateManager,
    doc_number_or_path: &str,
) -> Result<()> {
    // Try to resolve document number or path
    let path = if let Ok(doc_number) = state_mgr.resolve_number_or_path(doc_number_or_path) {
        // Get the document from state
        let doc_record = state_mgr
            .state()
            .get(doc_number)
            .ok_or_else(|| anyhow::anyhow!("Document {} not found", doc_number))?;

        // Build full path to the document
        state_mgr.docs_dir().join(&doc_record.path)
    } else {
        // If resolution fails, treat as direct path (for documents without headers)
        PathBuf::from(doc_number_or_path)
    };

    // Validate file exists
    if !path.exists() {
        anyhow::bail!("File not found: {}", path.display());
    }

    // Check if document has headers, add them if missing
    let content = fs::read_to_string(&path).context("Failed to read file")?;

    let content = if !content.trim_start().starts_with("---") {
        println!("{}", "Document missing headers, adding them automatically...".yellow());
        let (new_content, _) = design::doc::add_missing_headers(&path, &content)?;
        fs::write(&path, &new_content).context("Failed to write headers")?;
        new_content
    } else {
        content
    };

    // Parse document to get header state
    let doc = DesignDoc::parse(&content, path.clone()).context("Failed to parse document")?;

    let header_state = doc.metadata.state;

    // Determine target directory from state
    let target_dir = PathBuf::from(index.docs_dir()).join(header_state.directory());

    // Check current directory
    let current_dir =
        path.parent().ok_or_else(|| anyhow::anyhow!("Cannot determine current directory"))?;

    // Canonicalize for comparison (handle . and ..)
    let current_dir_canonical = current_dir.canonicalize().unwrap_or(current_dir.to_path_buf());
    let target_dir_canonical = if target_dir.exists() {
        target_dir.canonicalize().unwrap_or(target_dir.clone())
    } else {
        target_dir.clone()
    };

    if current_dir_canonical == target_dir_canonical {
        println!(
            "{} {}",
            "✓".green().bold(),
            format!(
                "Document is already in the correct directory for state '{}'",
                header_state.as_str()
            )
            .green()
        );
        return Ok(());
    }

    // Move the file
    let filename = path.file_name().ok_or_else(|| anyhow::anyhow!("Invalid filename"))?;
    let target_path = target_dir.join(filename);

    design::git::git_mv(&path, &target_path).context("Failed to move document")?;

    println!(
        "{} {} {} {} (state: {})",
        "✓".green().bold(),
        "Moved".green(),
        filename.to_string_lossy().bold(),
        "to match header".green(),
        header_state.as_str().cyan()
    );
    println!("  {}: {}", "From".dimmed(), current_dir.display());
    println!("  {}: {}", "To".dimmed(), target_dir.display());

    // Update the index to reflect the location sync
    println!();
    if let Err(e) = crate::commands::update_index::update_index(index) {
        println!("{} Failed to update index", "Warning:".yellow());
        println!("  {}", e);
        println!("  Run 'odm update-index' manually to sync the index");
    }

    Ok(())
}

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

    fn create_test_doc_with_state(state: DocState) -> String {
        format!(
            r#"---
number: 1
title: "Test Document"
author: "Test Author"
created: 2024-01-01
updated: 2024-01-01
state: {}
---

# Test Document

Test content.
"#,
            state.as_str()
        )
    }

    fn setup_git_repo(temp: &TempDir) -> PathBuf {
        let repo_path = temp.path().to_path_buf();

        // Initialize git repo
        std::process::Command::new("git").arg("init").current_dir(&repo_path).output().unwrap();

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

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

        repo_path
    }

    fn create_test_index(temp: &TempDir) -> DocumentIndex {
        let mut state = DocumentState::new();

        let meta = DocMetadata {
            number: 1,
            title: "Test Document".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.upsert(
            1,
            DocumentRecord {
                metadata: meta,
                path: "0001-test.md".to_string(),
                checksum: "abc123".to_string(),
                file_size: 100,
                modified: chrono::Utc::now(),
            },
        );

        DocumentIndex::from_state(&state, temp.path()).unwrap()
    }

    /// Helper to run code in a directory and restore the original directory afterward
    fn in_dir<F, R>(dir: &std::path::Path, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let original_dir = std::env::current_dir().ok();
        std::env::set_current_dir(dir).unwrap();
        let result = f();

        if let Some(orig) = original_dir {
            let _ = std::env::set_current_dir(orig);
        }

        result
    }

    #[test]
    fn test_sync_location_file_not_found() {
        let temp = TempDir::new().unwrap();
        let index = create_test_index(&temp);
        let state_mgr = StateManager::new(temp.path()).unwrap();

        let result = sync_location(&index, &state_mgr, "/nonexistent/file.md");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    #[serial]
    fn test_sync_location_already_in_correct_location() {
        let temp = TempDir::new().unwrap();
        let repo_path = setup_git_repo(&temp);
        let index = create_test_index(&temp);

        // Create document in Draft directory with Draft state
        let draft_dir = repo_path.join("01-draft");
        fs::create_dir_all(&draft_dir).unwrap();

        let doc_path = draft_dir.join("test.md");
        let content = create_test_doc_with_state(DocState::Draft);
        fs::write(&doc_path, &content).unwrap();

        // Add to git
        std::process::Command::new("git")
            .args(&["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

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

        // Create StateManager after files are set up
        let mut state_mgr = StateManager::new(temp.path()).unwrap();
        state_mgr.quick_scan().unwrap();

        // Sync location - should report already in correct place (must run in repo directory)
        let result = in_dir(&repo_path, || sync_location(&index, &state_mgr, "1"));
        assert!(result.is_ok());

        // File should still be in same place
        assert!(doc_path.exists());
    }

    #[test]
    #[serial]
    fn test_sync_location_moves_to_match_header() {
        let temp = TempDir::new().unwrap();
        let repo_path = setup_git_repo(&temp);
        let index = create_test_index(&temp);

        // Create document in Draft directory but with Final state in header
        let draft_dir = repo_path.join("01-draft");
        fs::create_dir_all(&draft_dir).unwrap();

        let doc_path = draft_dir.join("test.md");
        let content = create_test_doc_with_state(DocState::Final);
        fs::write(&doc_path, &content).unwrap();

        // Add to git
        std::process::Command::new("git")
            .args(&["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

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

        // Create StateManager after files are set up
        let mut state_mgr = StateManager::new(temp.path()).unwrap();
        state_mgr.quick_scan().unwrap();

        // Sync location - should move to Final directory (must run in repo directory)
        let result = in_dir(&repo_path, || sync_location(&index, &state_mgr, "1"));
        assert!(result.is_ok());

        // File should be moved
        assert!(!doc_path.exists());

        let final_dir = repo_path.join("06-final");
        let new_path = final_dir.join("test.md");
        assert!(new_path.exists());
    }

    #[test]
    #[serial]
    fn test_sync_location_document_without_headers() {
        let temp = TempDir::new().unwrap();
        let repo_path = setup_git_repo(&temp);
        let index = create_test_index(&temp);

        // Create document without headers
        let draft_dir = repo_path.join("01-draft");
        fs::create_dir_all(&draft_dir).unwrap();

        let doc_path = draft_dir.join("test.md");
        let content = "# Test Document\n\nNo headers here.\n";
        fs::write(&doc_path, content).unwrap();

        // Add to git
        std::process::Command::new("git")
            .args(&["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

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

        // Create StateManager after files are set up
        let mut state_mgr = StateManager::new(temp.path()).unwrap();
        state_mgr.quick_scan().unwrap();

        // Sync location - should add headers automatically (must run in repo directory)
        // Use file path since document without headers won't be in state with a number
        let result =
            in_dir(&repo_path, || sync_location(&index, &state_mgr, doc_path.to_str().unwrap()));
        assert!(result.is_ok());

        // Verify headers were added (document should remain in draft after adding headers)
        let updated_content = fs::read_to_string(&doc_path).unwrap();
        assert!(updated_content.contains("---"));
        assert!(updated_content.contains("state:"));
    }

    #[test]
    #[serial]
    fn test_sync_location_creates_target_directory() {
        let temp = TempDir::new().unwrap();
        let repo_path = setup_git_repo(&temp);
        let index = create_test_index(&temp);

        // Create document in Draft directory with Rejected state
        let draft_dir = repo_path.join("01-draft");
        fs::create_dir_all(&draft_dir).unwrap();

        let doc_path = draft_dir.join("test.md");
        let content = create_test_doc_with_state(DocState::Rejected);
        fs::write(&doc_path, &content).unwrap();

        // Add to git
        std::process::Command::new("git")
            .args(&["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

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

        // Create StateManager after files are set up
        let mut state_mgr = StateManager::new(temp.path()).unwrap();
        state_mgr.quick_scan().unwrap();

        // Target directory shouldn't exist yet
        let rejected_dir = repo_path.join("08-rejected");
        assert!(!rejected_dir.exists());

        // Sync location - should create target directory (must run in repo directory)
        let result = in_dir(&repo_path, || sync_location(&index, &state_mgr, "1"));
        assert!(result.is_ok());

        // Verify directory was created and file was moved
        assert!(rejected_dir.exists());
        let new_path = rejected_dir.join("test.md");
        assert!(new_path.exists());
    }

    #[test]
    #[serial]
    fn test_sync_location_preserves_content() {
        let temp = TempDir::new().unwrap();
        let repo_path = setup_git_repo(&temp);
        let index = create_test_index(&temp);

        // Create document with specific content
        let draft_dir = repo_path.join("01-draft");
        fs::create_dir_all(&draft_dir).unwrap();

        let doc_path = draft_dir.join("test.md");
        let mut content = create_test_doc_with_state(DocState::Active);
        content.push_str("\n## Additional Section\n\nImportant content here.\n");
        fs::write(&doc_path, &content).unwrap();

        // Add to git
        std::process::Command::new("git")
            .args(&["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

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

        // Create StateManager after files are set up
        let mut state_mgr = StateManager::new(temp.path()).unwrap();
        state_mgr.quick_scan().unwrap();

        // Sync location (must run in repo directory for git mv)
        let result = in_dir(&repo_path, || sync_location(&index, &state_mgr, "1"));
        assert!(result.is_ok());

        // Verify content is preserved
        let active_dir = repo_path.join("05-active");
        let new_path = active_dir.join("test.md");

        let new_content = fs::read_to_string(&new_path).unwrap();
        assert!(new_content.contains("## Additional Section"));
        assert!(new_content.contains("Important content here."));
    }

    #[test]
    #[serial]
    fn test_sync_location_different_states() {
        let temp = TempDir::new().unwrap();
        let repo_path = setup_git_repo(&temp);
        let index = create_test_index(&temp);

        // Test multiple state mismatches
        for (dir_state, header_state) in [
            (DocState::Draft, DocState::UnderReview),
            (DocState::Active, DocState::Superseded),
            (DocState::Accepted, DocState::Final),
        ] {
            // Create directory for current location
            let current_dir = repo_path.join(dir_state.directory());
            fs::create_dir_all(&current_dir).unwrap();

            let doc_path = current_dir.join(format!("test-{}.md", header_state.as_str()));
            let content = create_test_doc_with_state(header_state);
            fs::write(&doc_path, &content).unwrap();

            // Add to git
            std::process::Command::new("git")
                .args(&["add", "."])
                .current_dir(&repo_path)
                .output()
                .unwrap();

            std::process::Command::new("git")
                .args(&["commit", "-m", "Add document"])
                .current_dir(&repo_path)
                .output()
                .unwrap();

            // Create/update StateManager after files are set up
            let mut state_mgr = StateManager::new(temp.path()).unwrap();
            state_mgr.quick_scan().unwrap();

            // Sync location (must run in repo directory for git mv)
            // Use file path since we're testing multiple documents
            let result = in_dir(&repo_path, || {
                sync_location(&index, &state_mgr, doc_path.to_str().unwrap())
            });
            assert!(
                result.is_ok(),
                "Failed to sync {} to {}",
                dir_state.as_str(),
                header_state.as_str()
            );

            // Verify moved to correct directory
            let target_dir = repo_path.join(header_state.directory());
            let new_path = target_dir.join(format!("test-{}.md", header_state.as_str()));
            assert!(new_path.exists(), "Document not found at {}", new_path.display());
        }
    }
}