zub-store 0.0.3

Git-like content-addressed filesystem store with metadata preservation
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
use std::fs;
use std::path::Path;

use crate::error::{Error, IoResultExt, Result};
use crate::fs::{
    apply_metadata, create_block_device, create_char_device, create_fifo, create_hardlink,
    create_socket_placeholder, create_symlink, write_sparse_file, CheckoutHardlinkTracker,
};
use crate::hash::Hash;
use crate::object::{blob_path, read_blob, read_commit, read_tree};
use crate::ops::union::ConflictResolution;
use crate::refs::resolve_ref;
use crate::repo::Repo;
use crate::types::{EntryKind, Tree};

/// checkout options for union checkout
#[derive(Default, Clone)]
pub struct UnionCheckoutOptions {
    /// overwrite existing files
    pub force: bool,
    /// conflict resolution strategy
    pub on_conflict: ConflictResolution,
    /// use hardlinks when possible
    pub hardlink: bool,
}

/// checkout multiple refs as a union to a target directory
///
/// unlike the in-store union operation, this writes directly to the filesystem.
/// useful for inspecting or modifying before committing.
pub fn checkout_union(
    repo: &Repo,
    refs: &[&str],
    target: &Path,
    opts: UnionCheckoutOptions,
) -> Result<()> {
    if refs.is_empty() {
        return Err(Error::InvalidRef("no refs to checkout".to_string()));
    }

    // check target
    if target.exists() {
        if !opts.force {
            let is_empty = target.read_dir().with_path(target)?.next().is_none();
            if !is_empty {
                return Err(Error::TargetNotEmpty(target.to_path_buf()));
            }
        }
    } else {
        fs::create_dir_all(target).with_path(target)?;
    }

    let mut hardlink_tracker = CheckoutHardlinkTracker::new();

    // process each ref in order
    for ref_name in refs {
        let commit_hash = resolve_ref(repo, ref_name)?;
        let commit = read_commit(repo, &commit_hash)?;
        let tree = read_tree(repo, &commit.tree)?;

        checkout_tree_union(
            repo,
            &tree,
            target,
            "",
            opts.on_conflict,
            &mut hardlink_tracker,
        )?;
    }

    Ok(())
}

/// checkout a tree with union semantics
fn checkout_tree_union(
    repo: &Repo,
    tree: &Tree,
    target: &Path,
    prefix: &str,
    on_conflict: ConflictResolution,
    hardlink_tracker: &mut CheckoutHardlinkTracker,
) -> Result<()> {
    fs::create_dir_all(target).with_path(target)?;

    // first pass: non-hardlink entries
    for entry in tree.entries() {
        let entry_path = target.join(&entry.name);
        let logical_path = if prefix.is_empty() {
            entry.name.clone()
        } else {
            format!("{}/{}", prefix, entry.name)
        };

        match &entry.kind {
            EntryKind::Hardlink { .. } => continue, // second pass

            EntryKind::Regular {
                hash, sparse_map, ..
            } => {
                if entry_path.exists() {
                    // check if it's a directory (type conflict)
                    if entry_path.is_dir() {
                        return Err(Error::UnionTypeConflict {
                            path: entry_path.clone(),
                            first_type: "directory",
                            second_type: "regular",
                        });
                    }

                    match on_conflict {
                        ConflictResolution::Error => {
                            return Err(Error::UnionConflict(entry_path));
                        }
                        ConflictResolution::First => continue, // keep existing
                        ConflictResolution::Last => {
                            fs::remove_file(&entry_path).with_path(&entry_path)?;
                        }
                    }
                }

                checkout_file(repo, &entry_path, hash, sparse_map.as_deref())?;
                hardlink_tracker.record(&logical_path, entry_path);
            }

            EntryKind::Symlink { hash } => {
                if entry_path.exists() || entry_path.symlink_metadata().is_ok() {
                    if entry_path.is_dir() {
                        return Err(Error::UnionTypeConflict {
                            path: entry_path.clone(),
                            first_type: "directory",
                            second_type: "symlink",
                        });
                    }

                    match on_conflict {
                        ConflictResolution::Error => {
                            return Err(Error::UnionConflict(entry_path));
                        }
                        ConflictResolution::First => continue,
                        ConflictResolution::Last => {
                            fs::remove_file(&entry_path).with_path(&entry_path)?;
                        }
                    }
                }

                checkout_symlink(repo, &entry_path, hash)?;
                hardlink_tracker.record(&logical_path, entry_path);
            }

            EntryKind::Directory {
                hash,
                uid,
                gid,
                mode,
                xattrs,
            } => {
                if entry_path.exists() && !entry_path.is_dir() {
                    // file exists where we want a directory
                    return Err(Error::UnionTypeConflict {
                        path: entry_path.clone(),
                        first_type: "regular",
                        second_type: "directory",
                    });
                }

                let subtree = read_tree(repo, hash)?;
                checkout_tree_union(
                    repo,
                    &subtree,
                    &entry_path,
                    &logical_path,
                    on_conflict,
                    hardlink_tracker,
                )?;

                // apply directory metadata
                apply_metadata(&entry_path, *uid, *gid, *mode, xattrs)?;
            }

            EntryKind::BlockDevice {
                major,
                minor,
                uid,
                gid,
                mode,
                xattrs,
            } => {
                if entry_path.exists() {
                    match on_conflict {
                        ConflictResolution::Error => {
                            return Err(Error::UnionConflict(entry_path));
                        }
                        ConflictResolution::First => continue,
                        ConflictResolution::Last => {
                            fs::remove_file(&entry_path).with_path(&entry_path)?;
                        }
                    }
                }

                match create_block_device(&entry_path, *major, *minor, *uid, *gid, *mode, xattrs) {
                    Ok(()) => {}
                    Err(Error::DeviceNodePermission(_)) => {
                        eprintln!(
                            "warning: cannot create block device {:?} without privileges, skipping",
                            entry_path
                        );
                    }
                    Err(e) => return Err(e),
                }
            }

            EntryKind::CharDevice {
                major,
                minor,
                uid,
                gid,
                mode,
                xattrs,
            } => {
                if entry_path.exists() {
                    match on_conflict {
                        ConflictResolution::Error => {
                            return Err(Error::UnionConflict(entry_path));
                        }
                        ConflictResolution::First => continue,
                        ConflictResolution::Last => {
                            fs::remove_file(&entry_path).with_path(&entry_path)?;
                        }
                    }
                }

                match create_char_device(&entry_path, *major, *minor, *uid, *gid, *mode, xattrs) {
                    Ok(()) => {}
                    Err(Error::DeviceNodePermission(_)) => {
                        eprintln!(
                            "warning: cannot create char device {:?} without privileges, skipping",
                            entry_path
                        );
                    }
                    Err(e) => return Err(e),
                }
            }

            EntryKind::Fifo {
                uid,
                gid,
                mode,
                xattrs,
            } => {
                if entry_path.exists() {
                    match on_conflict {
                        ConflictResolution::Error => {
                            return Err(Error::UnionConflict(entry_path));
                        }
                        ConflictResolution::First => continue,
                        ConflictResolution::Last => {
                            fs::remove_file(&entry_path).with_path(&entry_path)?;
                        }
                    }
                }

                create_fifo(&entry_path, *uid, *gid, *mode, xattrs)?;
            }

            EntryKind::Socket {
                uid,
                gid,
                mode,
                xattrs,
            } => {
                if entry_path.exists() {
                    match on_conflict {
                        ConflictResolution::Error => {
                            return Err(Error::UnionConflict(entry_path));
                        }
                        ConflictResolution::First => continue,
                        ConflictResolution::Last => {
                            fs::remove_file(&entry_path).with_path(&entry_path)?;
                        }
                    }
                }

                create_socket_placeholder(&entry_path, *uid, *gid, *mode, xattrs)?;
            }
        }
    }

    // second pass: hardlinks
    for entry in tree.entries() {
        if let EntryKind::Hardlink { target_path } = &entry.kind {
            let entry_path = target.join(&entry.name);

            if entry_path.exists() {
                match on_conflict {
                    ConflictResolution::Error => {
                        return Err(Error::UnionConflict(entry_path));
                    }
                    ConflictResolution::First => continue,
                    ConflictResolution::Last => {
                        fs::remove_file(&entry_path).with_path(&entry_path)?;
                    }
                }
            }

            let target_fs_path = hardlink_tracker
                .get(target_path)
                .ok_or_else(|| Error::HardlinkTargetNotFound(target_path.clone()))?;

            create_hardlink(&entry_path, target_fs_path)?;
        }
    }

    Ok(())
}

fn checkout_file(
    repo: &Repo,
    dest: &Path,
    hash: &Hash,
    sparse_map: Option<&[crate::types::SparseRegion]>,
) -> Result<()> {
    match sparse_map {
        Some(regions) if !regions.is_empty() => {
            let data = read_blob(repo, hash)?;
            let total_size: u64 = regions.iter().map(|r| r.end()).max().unwrap_or(0);
            write_sparse_file(dest, &data, regions, total_size)?;

            let blob = blob_path(repo, hash);
            let meta = fs::metadata(&blob).with_path(&blob)?;
            fs::set_permissions(dest, meta.permissions()).with_path(dest)?;
        }
        Some(_) => {
            fs::write(dest, b"").with_path(dest)?;
        }
        None => {
            let blob = blob_path(repo, hash);
            fs::hard_link(&blob, dest).with_path(dest)?;
        }
    }
    Ok(())
}

fn checkout_symlink(repo: &Repo, dest: &Path, hash: &Hash) -> Result<()> {
    let target_bytes = read_blob(repo, hash)?;
    let target = String::from_utf8_lossy(&target_bytes);

    let blob = blob_path(repo, hash);
    let meta = fs::symlink_metadata(&blob).with_path(&blob)?;

    use std::os::unix::fs::MetadataExt;
    create_symlink(dest, &target, meta.uid(), meta.gid(), &[])?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ops::commit::commit;
    use tempfile::tempdir;

    fn test_repo() -> (tempfile::TempDir, Repo) {
        let dir = tempdir().unwrap();
        let repo_path = dir.path().join("repo");
        let repo = Repo::init(&repo_path).unwrap();
        (dir, repo)
    }

    #[test]
    fn test_union_checkout_no_overlap() {
        let (dir, repo) = test_repo();

        let source1 = dir.path().join("source1");
        fs::create_dir(&source1).unwrap();
        fs::write(source1.join("file1.txt"), "content1").unwrap();
        commit(&repo, &source1, "ref1", None, None).unwrap();

        let source2 = dir.path().join("source2");
        fs::create_dir(&source2).unwrap();
        fs::write(source2.join("file2.txt"), "content2").unwrap();
        commit(&repo, &source2, "ref2", None, None).unwrap();

        let target = dir.path().join("target");
        checkout_union(&repo, &["ref1", "ref2"], &target, Default::default()).unwrap();

        assert!(target.join("file1.txt").exists());
        assert!(target.join("file2.txt").exists());
    }

    #[test]
    fn test_union_checkout_conflict_last() {
        let (dir, repo) = test_repo();

        let source1 = dir.path().join("source1");
        fs::create_dir(&source1).unwrap();
        fs::write(source1.join("conflict.txt"), "version1").unwrap();
        commit(&repo, &source1, "ref1", None, None).unwrap();

        let source2 = dir.path().join("source2");
        fs::create_dir(&source2).unwrap();
        fs::write(source2.join("conflict.txt"), "version2").unwrap();
        commit(&repo, &source2, "ref2", None, None).unwrap();

        let target = dir.path().join("target");
        let opts = UnionCheckoutOptions {
            on_conflict: ConflictResolution::Last,
            ..Default::default()
        };
        checkout_union(&repo, &["ref1", "ref2"], &target, opts).unwrap();

        let content = fs::read_to_string(target.join("conflict.txt")).unwrap();
        assert_eq!(content, "version2");
    }

    #[test]
    fn test_union_checkout_conflict_first() {
        let (dir, repo) = test_repo();

        let source1 = dir.path().join("source1");
        fs::create_dir(&source1).unwrap();
        fs::write(source1.join("conflict.txt"), "version1").unwrap();
        commit(&repo, &source1, "ref1", None, None).unwrap();

        let source2 = dir.path().join("source2");
        fs::create_dir(&source2).unwrap();
        fs::write(source2.join("conflict.txt"), "version2").unwrap();
        commit(&repo, &source2, "ref2", None, None).unwrap();

        let target = dir.path().join("target");
        let opts = UnionCheckoutOptions {
            on_conflict: ConflictResolution::First,
            ..Default::default()
        };
        checkout_union(&repo, &["ref1", "ref2"], &target, opts).unwrap();

        let content = fs::read_to_string(target.join("conflict.txt")).unwrap();
        assert_eq!(content, "version1");
    }

    #[test]
    fn test_union_checkout_directory_merge() {
        let (dir, repo) = test_repo();

        let source1 = dir.path().join("source1");
        fs::create_dir_all(source1.join("shared")).unwrap();
        fs::write(source1.join("shared/a.txt"), "a").unwrap();
        commit(&repo, &source1, "ref1", None, None).unwrap();

        let source2 = dir.path().join("source2");
        fs::create_dir_all(source2.join("shared")).unwrap();
        fs::write(source2.join("shared/b.txt"), "b").unwrap();
        commit(&repo, &source2, "ref2", None, None).unwrap();

        let target = dir.path().join("target");
        checkout_union(&repo, &["ref1", "ref2"], &target, Default::default()).unwrap();

        assert!(target.join("shared/a.txt").exists());
        assert!(target.join("shared/b.txt").exists());
    }
}