wlk 0.1.0

File-centric, event-sourced version control system with implicit branching
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
use crate::delta::{apply_operation, Delta, DeltaId, DeltaOperation};
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};

/// A shadow file tracks the complete version history of a single file
#[derive(Debug, Serialize, Deserialize)]
pub struct ShadowFile {
    /// Name of the tracked file
    pub file: String,

    /// Initial snapshot (root of the delta tree)
    pub initial_snapshot: Delta,

    /// All subsequent deltas (forms a tree structure via parent references)
    pub deltas: Vec<Delta>,

    /// Current HEAD - which delta represents the working file state
    pub current_head: DeltaId,
}

impl ShadowFile {
    /// Create a new shadow file with initial content
    pub fn new(filename: &str, initial_content: String) -> Self {
        let initial_snapshot = Delta::initial_snapshot(initial_content);
        let current_head = initial_snapshot.id.clone();

        ShadowFile {
            file: filename.to_string(),
            initial_snapshot,
            deltas: vec![],
            current_head,
        }
    }

    /// Apply a new delta operation, creating a new delta as a child of current HEAD
    pub fn apply_delta(
        &mut self,
        operation: DeltaOperation,
        annotation: Option<String>,
    ) -> Result<DeltaId> {
        let delta = Delta::new(self.current_head.clone(), operation, annotation);
        let delta_id = delta.id.clone();

        self.deltas.push(delta);
        self.current_head = delta_id.clone();

        Ok(delta_id)
    }

    /// Move HEAD to a different delta (rewind/fast-forward)
    pub fn set_head(&mut self, delta_id: &DeltaId) -> Result<()> {
        // Verify the delta exists
        if delta_id != "d0" && !self.deltas.iter().any(|d| &d.id == delta_id) {
            return Err(anyhow!("Delta {} not found", delta_id));
        }

        self.current_head = delta_id.clone();
        Ok(())
    }

    /// Reconstruct file content at a specific delta
    pub fn reconstruct_at(&self, target_id: &DeltaId) -> Result<String> {
        // Build path from root to target
        let path = self
            .build_path_to(target_id)
            .context(format!("Failed to build path to delta {}", target_id))?;

        // Start with initial snapshot
        let mut content = match &self.initial_snapshot.operation {
            DeltaOperation::Snapshot { content } => content.clone(),
            _ => return Err(anyhow!("Initial delta must be a snapshot")),
        };

        // Apply deltas in order
        for delta_id in path {
            let delta = self.find_delta(&delta_id)?;
            content = apply_operation(&content, &delta.operation)
                .map_err(|e| anyhow!("Failed to apply delta {}: {}", delta_id, e))?;
        }

        Ok(content)
    }

    /// Get the current working file content (at HEAD)
    pub fn current_content(&self) -> Result<String> {
        self.reconstruct_at(&self.current_head)
    }

    /// Build a path from root (d0) to target delta
    fn build_path_to(&self, target_id: &DeltaId) -> Result<Vec<DeltaId>> {
        if target_id == "d0" {
            return Ok(vec![]);
        }

        let mut path = vec![];
        let mut current = target_id.clone();

        // Walk backwards to root
        while current != "d0" {
            let delta = self.find_delta(&current)?;
            path.push(current.clone());
            current = delta.parent.clone();
        }

        // Reverse to get root-to-target order
        path.reverse();
        Ok(path)
    }

    /// Find a delta by ID
    fn find_delta(&self, id: &DeltaId) -> Result<&Delta> {
        self.deltas
            .iter()
            .find(|d| &d.id == id)
            .ok_or_else(|| anyhow!("Delta {} not found", id))
    }

    /// Get all children of a given delta (for finding branches)
    pub fn get_children(&self, parent_id: &DeltaId) -> Vec<&Delta> {
        self.deltas
            .iter()
            .filter(|d| &d.parent == parent_id)
            .collect()
    }

    /// Find all branch points (deltas with multiple children)
    pub fn find_branch_points(&self) -> Vec<DeltaId> {
        let mut children_count: HashMap<DeltaId, usize> = HashMap::new();

        // Count children for each delta
        children_count.insert("d0".to_string(), 0);
        for delta in &self.deltas {
            *children_count.entry(delta.parent.clone()).or_insert(0) += 1;
        }

        // Find deltas with 2+ children
        children_count
            .into_iter()
            .filter(|(_, count)| *count >= 2)
            .map(|(id, _)| id)
            .collect()
    }

    /// Find all leaf nodes (deltas with no children)
    pub fn find_leaves(&self) -> Vec<&Delta> {
        let all_parents: HashSet<DeltaId> = self.deltas.iter().map(|d| d.parent.clone()).collect();

        self.deltas
            .iter()
            .filter(|d| !all_parents.contains(&d.id))
            .collect()
    }

    /// Get the complete history as a list (depth-first traversal)
    pub fn get_history(&self) -> Vec<&Delta> {
        let mut history = vec![];
        let mut visited = HashSet::new();

        // Start from initial snapshot, traverse all paths
        let root_id = "d0".to_string();
        self.traverse_from(&root_id, &mut history, &mut visited);

        history
    }

    fn traverse_from<'a>(
        &'a self,
        current: &DeltaId,
        history: &mut Vec<&'a Delta>,
        visited: &mut HashSet<DeltaId>,
    ) {
        if visited.contains(current) {
            return;
        }
        visited.insert(current.clone());

        // Get all children and traverse them
        let children = self.get_children(current);
        for child in children {
            history.push(child);
            self.traverse_from(&child.id, history, visited);
        }
    }

    /// Save shadow file to disk as JSON
    pub fn save(&self, path: &Path) -> Result<()> {
        let json = serde_json::to_string_pretty(self).context("Failed to serialize shadow file")?;
        fs::write(path, json).context(format!("Failed to write shadow file to {:?}", path))?;
        Ok(())
    }

    /// Search deltas by annotation text
    pub fn search_by_annotation(&self, query: &str) -> Vec<&Delta> {
        self.deltas
            .iter()
            .filter(|d| {
                d.annotation
                    .as_ref()
                    .map(|a| a.to_lowercase().contains(&query.to_lowercase()))
                    .unwrap_or(false)
            })
            .collect()
    }

    /// Get deltas within a time range
    pub fn deltas_in_range(
        &self,
        start: chrono::DateTime<chrono::Utc>,
        end: chrono::DateTime<chrono::Utc>,
    ) -> Vec<&Delta> {
        self.deltas
            .iter()
            .filter(|d| d.timestamp >= start && d.timestamp <= end)
            .collect()
    }

    /// Get deltas by author
    pub fn deltas_by_author(&self, author: &str) -> Vec<&Delta> {
        self.deltas
            .iter()
            .filter(|d| d.author.as_ref().map(|a| a == author).unwrap_or(false))
            .collect()
    }

    /// Load shadow file from disk
    pub fn load(path: &Path) -> Result<Self> {
        let json = fs::read_to_string(path)
            .context(format!("Failed to read shadow file from {:?}", path))?;
        let shadow: ShadowFile =
            serde_json::from_str(&json).context("Failed to deserialize shadow file")?;
        Ok(shadow)
    }

    /// Get path to shadow file for a given working file
    pub fn shadow_path(working_file: &Path) -> Result<PathBuf> {
        let parent = working_file
            .parent()
            .ok_or_else(|| anyhow!("File has no parent directory"))?;
        let filename = working_file
            .file_name()
            .ok_or_else(|| anyhow!("Invalid filename"))?;

        let wlk_dir = parent.join(".wlk");
        let shadow_name = format!("{}.wlk", filename.to_string_lossy());

        Ok(wlk_dir.join(shadow_name))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_shadow_file() {
        let shadow = ShadowFile::new("test.txt", "initial content".to_string());
        assert_eq!(shadow.file, "test.txt");
        assert_eq!(shadow.current_head, "d0");
        assert_eq!(shadow.deltas.len(), 0);
    }

    #[test]
    fn test_apply_delta() {
        let mut shadow = ShadowFile::new("test.txt", "Hello".to_string());

        let id = shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 5,
                    value: " world".to_string(),
                },
                Some("Added world".to_string()),
            )
            .unwrap();

        assert_eq!(shadow.deltas.len(), 1);
        assert_eq!(shadow.current_head, id);

        let content = shadow.current_content().unwrap();
        assert_eq!(content, "Hello world");
    }

    #[test]
    fn test_reconstruct_at() {
        let mut shadow = ShadowFile::new("test.txt", "base".to_string());

        let d1 = shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 4,
                    value: "A".to_string(),
                },
                None,
            )
            .unwrap();

        let d2 = shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 5,
                    value: "B".to_string(),
                },
                None,
            )
            .unwrap();

        // Test reconstruction at each point
        assert_eq!(shadow.reconstruct_at(&"d0".to_string()).unwrap(), "base");
        assert_eq!(shadow.reconstruct_at(&d1).unwrap(), "baseA");
        assert_eq!(shadow.reconstruct_at(&d2).unwrap(), "baseAB");
    }

    #[test]
    fn test_branch_creation() {
        let mut shadow = ShadowFile::new("test.txt", "base".to_string());

        let d1 = shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 4,
                    value: "1".to_string(),
                },
                None,
            )
            .unwrap();

        // Rewind to d0 and create alternate branch
        shadow.set_head(&"d0".to_string()).unwrap();
        let d2 = shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 4,
                    value: "2".to_string(),
                },
                None,
            )
            .unwrap();

        // Verify both branches exist
        assert_eq!(shadow.reconstruct_at(&d1).unwrap(), "base1");
        assert_eq!(shadow.reconstruct_at(&d2).unwrap(), "base2");

        // Verify branch point detection
        let branch_points = shadow.find_branch_points();
        assert!(branch_points.contains(&"d0".to_string()));
    }

    #[test]
    fn test_find_leaves() {
        let mut shadow = ShadowFile::new("test.txt", "base".to_string());

        shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 4,
                    value: "1".to_string(),
                },
                None,
            )
            .unwrap();

        shadow.set_head(&"d0".to_string()).unwrap();
        shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 4,
                    value: "2".to_string(),
                },
                None,
            )
            .unwrap();

        let leaves = shadow.find_leaves();
        assert_eq!(leaves.len(), 2);
    }

    #[test]
    fn test_multiple_operations() {
        let mut shadow = ShadowFile::new("test.txt", "Hello World!".to_string());

        // Insert "beautiful " after "Hello " (at index 6, after "Hello ")
        shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 6,
                    value: "beautiful ".to_string(),
                },
                Some("Add adjective".to_string()),
            )
            .unwrap();

        // Now content is "Hello beautiful World!"
        // Replace "World" with "Rust" (starts at index 16)
        shadow
            .apply_delta(
                DeltaOperation::Replace {
                    index: 16,
                    length: 5,
                    value: "Rust".to_string(),
                },
                Some("Change language".to_string()),
            )
            .unwrap();

        let final_content = shadow.current_content().unwrap();
        assert_eq!(final_content, "Hello beautiful Rust!");
    }

    #[test]
    fn test_snapshot_operation() {
        let mut shadow = ShadowFile::new("test.txt", "old content".to_string());

        shadow
            .apply_delta(
                DeltaOperation::Insert {
                    index: 3,
                    value: "XXX".to_string(),
                },
                None,
            )
            .unwrap();

        // Create snapshot
        shadow
            .apply_delta(
                DeltaOperation::Snapshot {
                    content: "completely new".to_string(),
                },
                Some("Fresh start".to_string()),
            )
            .unwrap();

        let content = shadow.current_content().unwrap();
        assert_eq!(content, "completely new");
    }
}