clonetree 0.0.2

A copy-on-write directory library for Rust with fast reflink cloning
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
//! A library for efficiently cloning directory trees with copy-on-write support.
//!
//! This crate provides functionality to clone entire directory structures while
//! leveraging filesystem-level copy-on-write (CoW) capabilities when available
//! through reflinks. This can result in significant space savings and improved
//! performance compared to traditional file copying.
//!
//! # Features
//!
//! - **Copy-on-Write Support**: Automatically uses reflinks when available on
//!   supported filesystems (Btrfs, XFS, APFS, etc.)
//! - **Symlink Preservation**: Symbolic links are recreated with their original targets
//! - **Empty Directory Preservation**: Empty directories in the source tree are preserved
//! - **Glob Filtering**: Include or exclude files using glob patterns
//! - **Efficient Traversal**: Built on the `ignore` crate for fast directory walking
//! - **Type-Safe Errors**: Comprehensive error handling with descriptive error types
//!
//! # Example
//!
//! ```no_run
//! use clonetree::{clone_tree, Options};
//!
//! # fn main() -> clonetree::Result<()> {
//! // Clone a directory tree
//! let options = Options::new();
//! clone_tree("/source/path", "/destination/path", &options)?;
//!
//! // Clone with glob filters
//! let options = Options::new()
//!     .glob("**/*.rs")      // Include only Rust files
//!     .glob("!target/**");  // Exclude target directory
//! clone_tree("/source", "/dest", &options)?;
//! # Ok(())
//! # }
//! ```
//!
//! # Validation
//!
//! The `clone_tree` function enforces the following constraints:
//! - Source path must exist and be a directory
//! - Destination path must not exist
//!
//! These constraints are validated before any filesystem operations begin.
//! If you need to replace an existing destination, remove it first with
//! [`std::fs::remove_dir_all`].
//!
//! # Symlink Handling
//!
//! Symbolic links in the source tree are preserved as symbolic links in the
//! destination. The link targets are copied verbatim (not resolved), so relative
//! symlinks maintain their relative paths.
//!
//! - **`FullTraversal` strategy**: Symlinks are recreated using platform-native
//!   symlink creation (`symlink(2)` on Unix, `CreateSymbolicLink` on Windows).
//! - **`SingleCall` strategy** (macOS only): The kernel's `clonefile(2)` preserves
//!   symlinks automatically as part of the atomic directory clone.
//!
//! # Concurrency Considerations
//!
//! The validation checks (source exists, destination does not exist) and the actual
//! clone operation are not atomic. This creates a time-of-check to time-of-use (TOCTOU)
//! race window where:
//!
//! - Another process could create the destination after validation but before cloning
//! - Another process could modify or delete the source during traversal
//!
//! **Strategy-specific behavior:**
//!
//! - **`SingleCall` strategy** (macOS): The `clonefile(2)` syscall is atomic—if the
//!   destination is created by another process first, cloning will fail with an I/O error
//!   rather than corrupting data.
//!
//! - **`FullTraversal` strategy**: Not atomic. Concurrent destination creation may result
//!   in partial writes or merged directory contents. Source modifications during traversal
//!   may cause some files to be skipped or fail to copy.
//!
//! For concurrent scenarios, callers should implement their own synchronization (e.g.,
//! file locks, exclusive access to the destination parent directory).

use std::{
    collections::HashSet,
    env, fs, io,
    path::{Component, Path, PathBuf},
    result,
};

use ignore::{overrides::OverrideBuilder, WalkBuilder};
use reflink_copy::{reflink, reflink_or_copy};
use thiserror::Error;

/// Errors that can occur while cloning directory trees.
#[derive(Error, Debug)]
pub enum Error {
    /// Propagated I/O error from an underlying filesystem operation.
    #[error("IO error: {0}")]
    Io(#[from] io::Error),

    #[error("Failed to create directory at {path}: {source}")]
    /// Creation of a destination directory failed.
    CreateDirectory {
        /// Destination directory path that failed to be created.
        path: PathBuf,
        #[source]
        /// Source I/O error returned by the filesystem.
        source: io::Error,
    },

    #[error("Failed to copy file from {src} to {dest}: {source}")]
    /// Copying or reflinking a file from source to destination failed.
    Copy {
        /// Source file being copied.
        src: PathBuf,
        /// Destination path for the copy.
        dest: PathBuf,
        #[source]
        /// Underlying I/O error from the copy operation.
        source: io::Error,
    },

    #[error("Invalid glob pattern '{pattern}': {source}")]
    /// Supplied glob pattern could not be parsed by the ignore crate.
    InvalidGlob {
        /// Glob expression supplied by the caller.
        pattern: String,
        #[source]
        /// Parser error from the ignore crate.
        source: ignore::Error,
    },

    #[error("Destination already exists: {path}")]
    /// Destination already exists and overwrite was not requested.
    DestinationExists {
        /// Conflicting destination path.
        path: PathBuf,
    },

    #[error("Destination is not a directory: {path}")]
    /// Destination exists but is not a directory.
    DestinationNotDirectory {
        /// Destination path that is not a directory.
        path: PathBuf,
    },

    #[error("Source is not a directory: {path}")]
    /// Source path exists but is not a directory.
    SourceNotDirectory {
        /// Source path that is not a directory.
        path: PathBuf,
    },

    #[error("Source does not exist: {path}")]
    /// Source path does not exist.
    SourceNotFound {
        /// Missing source path.
        path: PathBuf,
    },

    #[error("Operation error: {0}")]
    /// Generic error message for unexpected conditions.
    Other(String),

    #[error("Single-call cloning is only available on macOS")]
    /// Single-call cloning was requested on an unsupported platform.
    SingleCallUnsupported,

    #[error("Single-call cloning cannot be combined with glob filters: {patterns:?}")]
    /// Single-call cloning cannot be used when glob filters are present.
    IncompatibleOptions {
        /// Glob patterns provided alongside the single-call strategy.
        patterns: Vec<String>,
    },

    #[error("Source and destination resolve to the same path: {path}")]
    /// Source and destination paths are identical after resolution.
    IdenticalPaths {
        /// Resolved absolute path shared by source and destination.
        path: PathBuf,
    },

    #[error("Destination lies inside the source tree: src={src}, dest={dest}")]
    /// Destination is a descendant of the source path.
    DestinationInsideSource {
        /// Canonicalized source path.
        src: PathBuf,
        /// Canonicalized destination path.
        dest: PathBuf,
    },

    #[error("Source lies inside the destination tree: src={src}, dest={dest}")]
    /// Source is a descendant of the destination path.
    SourceInsideDestination {
        /// Canonicalized source path.
        src: PathBuf,
        /// Canonicalized destination path.
        dest: PathBuf,
    },

    #[error("Error while walking source tree: {source}")]
    /// An error occurred while traversing the source directory tree.
    Walk {
        #[source]
        /// Underlying error from the ignore crate's walker.
        source: ignore::Error,
    },
}

/// Convenience result type for clonetree operations.
pub type Result<T> = result::Result<T, Error>;

/// Strategy used when cloning a directory tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CloneStrategy {
    /// Choose the fastest supported strategy. On macOS this prefers a
    /// single `clonefile` call when possible; otherwise it falls back to the
    /// full directory traversal used on other platforms.
    #[default]
    Auto,
    /// Force a single system call to clone the root directory (macOS only).
    /// This cannot be combined with glob filters because the kernel copies the
    /// entire tree.
    SingleCall,
    /// Walk the tree in userspace and reflink each file individually.
    FullTraversal,
}

/// Builder-style options that control cloning behaviour.
#[derive(Debug, Default)]
pub struct Options {
    /// Glob patterns applied to the source tree (negated patterns exclude).
    globs: Vec<String>,
    /// How files and directories should be cloned.
    strategy: CloneStrategy,
}

impl Options {
    /// Construct a new options set with defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a glob pattern to include or exclude when traversing.
    pub fn glob<S: Into<String>>(mut self, pattern: S) -> Self {
        self.globs.push(pattern.into());
        self
    }

    /// Specify the cloning strategy to use.
    pub fn strategy(mut self, strategy: CloneStrategy) -> Self {
        self.strategy = strategy;
        self
    }
}

/// Clone a directory tree from `src` to `dest` using the provided `options`.
/// Validates inputs up-front and selects the appropriate cloning strategy.
pub fn clone_tree<P: AsRef<Path>, Q: AsRef<Path>>(
    src: P,
    dest: Q,
    options: &Options,
) -> Result<()> {
    let src = src.as_ref();
    let dest = dest.as_ref();

    // Validate source exists
    if !src.exists() {
        return Err(Error::SourceNotFound {
            path: src.to_path_buf(),
        });
    }

    // Validate source is a directory
    if !src.is_dir() {
        return Err(Error::SourceNotDirectory {
            path: src.to_path_buf(),
        });
    }

    // Validate destination state early to keep semantics predictable
    if dest.exists() && !dest.is_dir() {
        return Err(Error::DestinationNotDirectory {
            path: dest.to_path_buf(),
        });
    }

    // Resolve absolute paths to guard against unsafe relationships
    let src_canon = canonicalize_existing(src)?;
    let dest_resolved = canonicalize_for_destination(dest)?;

    if src_canon == dest_resolved {
        return Err(Error::IdenticalPaths { path: src_canon });
    }

    if dest_resolved.starts_with(&src_canon) {
        return Err(Error::DestinationInsideSource {
            src: src_canon,
            dest: dest_resolved,
        });
    }

    if src_canon.starts_with(&dest_resolved) {
        return Err(Error::SourceInsideDestination {
            src: src_canon,
            dest: dest_resolved,
        });
    }

    if dest.exists() {
        return Err(Error::DestinationExists {
            path: dest.to_path_buf(),
        });
    }

    let use_single_call = should_use_single_call(options)?;

    if use_single_call {
        return clone_tree_single_call(src, dest, options);
    }

    clone_tree_full_traversal(src, dest, options)
}

/// Determine whether to use the single-call strategy based on options and platform.
fn should_use_single_call(options: &Options) -> Result<bool> {
    if !options.globs.is_empty() {
        if matches!(options.strategy, CloneStrategy::SingleCall) {
            return Err(Error::IncompatibleOptions {
                patterns: options.globs.clone(),
            });
        }
        return Ok(false);
    }

    match options.strategy {
        CloneStrategy::SingleCall => {
            if cfg!(target_os = "macos") {
                Ok(true)
            } else {
                Err(Error::SingleCallUnsupported)
            }
        }
        CloneStrategy::Auto => Ok(cfg!(target_os = "macos")),
        CloneStrategy::FullTraversal => Ok(false),
    }
}

#[cfg(target_os = "macos")]
/// Use the platform single-call clone when available (macOS `clonefile`).
fn clone_tree_single_call<P: AsRef<Path>, Q: AsRef<Path>>(
    src: P,
    dest: Q,
    _options: &Options,
) -> Result<()> {
    let src = src.as_ref();
    let dest = dest.as_ref();

    // Create parent directory if needed
    if let Some(parent) = dest.parent() {
        if !parent.exists() {
            fs::create_dir_all(parent).map_err(|source| Error::CreateDirectory {
                path: parent.to_path_buf(),
                source,
            })?;
        }
    }

    reflink(src, dest).map_err(|source| Error::Copy {
        src: src.to_path_buf(),
        dest: dest.to_path_buf(),
        source,
    })
}

#[cfg(not(target_os = "macos"))]
/// Stub for platforms that do not support single-call cloning.
fn clone_tree_single_call<P: AsRef<Path>, Q: AsRef<Path>>(
    _src: P,
    _dest: Q,
    _options: &Options,
) -> Result<()> {
    Err(Error::SingleCallUnsupported)
}

/// Walk the source tree and reflink or copy each file into `dest`.
fn clone_tree_full_traversal<P: AsRef<Path>, Q: AsRef<Path>>(
    src: P,
    dest: Q,
    options: &Options,
) -> Result<()> {
    let src = src.as_ref();
    let dest = dest.as_ref();

    // Create destination directory
    fs::create_dir_all(dest).map_err(|source| Error::CreateDirectory {
        path: dest.to_path_buf(),
        source,
    })?;

    // Track created directories to avoid redundant create_dir_all calls
    let mut created_dirs = HashSet::new();
    created_dirs.insert(dest.to_path_buf());

    // Build walker with standard filters disabled
    let mut builder = WalkBuilder::new(src);
    builder.standard_filters(false);

    // Add glob patterns using overrides
    if !options.globs.is_empty() {
        let mut overrides = OverrideBuilder::new(src);
        for pattern in &options.globs {
            overrides
                .add(pattern)
                .map_err(|source| Error::InvalidGlob {
                    pattern: pattern.clone(),
                    source,
                })?;
        }
        builder.overrides(
            overrides
                .build()
                .map_err(|e| Error::Other(format!("Failed to build glob overrides: {e}")))?,
        );
    }

    // Walk the source directory
    for entry in builder.build() {
        let entry = entry.map_err(|source| Error::Walk { source })?;
        let path = entry.path();

        // Skip the root directory itself
        if path == src {
            continue;
        }

        // Calculate relative path and destination path
        let relative_path = path
            .strip_prefix(src)
            .map_err(|e| Error::Other(format!("Failed to strip prefix from path: {e}")))?;
        let dest_path = dest.join(relative_path);

        // Create parent directories if needed
        if let Some(parent) = dest_path.parent() {
            if !created_dirs.contains(parent) {
                fs::create_dir_all(parent).map_err(|source| Error::CreateDirectory {
                    path: parent.to_path_buf(),
                    source,
                })?;
                created_dirs.insert(parent.to_path_buf());
            }
        }

        // Handle symlinks by recreating them
        if entry.path_is_symlink() {
            let target = fs::read_link(path).map_err(|source| Error::Copy {
                src: path.to_path_buf(),
                dest: dest_path.clone(),
                source,
            })?;

            create_symlink(&target, &dest_path, path).map_err(|source| Error::Copy {
                src: path.to_path_buf(),
                dest: dest_path.clone(),
                source,
            })?;
        } else if entry.file_type().is_some_and(|ft| ft.is_file()) {

            // Copy file using reflink when available
            reflink_or_copy(path, &dest_path).map_err(|source| Error::Copy {
                src: path.to_path_buf(),
                dest: dest_path.clone(),
                source,
            })?;
        } else if entry.file_type().is_some_and(|ft| ft.is_dir()) {
            // Create directories explicitly to preserve empty directories
            if !created_dirs.contains(&dest_path) {
                fs::create_dir_all(&dest_path).map_err(|source| Error::CreateDirectory {
                    path: dest_path.clone(),
                    source,
                })?;
                created_dirs.insert(dest_path);
            }
        }
    }

    Ok(())
}

/// Create a symbolic link at `dest` pointing to `target`.
///
/// The `original_path` is used on Windows to determine if the target is a directory.
#[cfg(unix)]
#[allow(clippy::absolute_paths)] // Platform-specific import not worth conditional use
fn create_symlink(target: &Path, dest: &Path, _original_path: &Path) -> io::Result<()> {
    std::os::unix::fs::symlink(target, dest)
}

/// Create a symbolic link at `dest` pointing to `target`.
///
/// The `original_path` is used on Windows to determine if the target is a directory.
#[cfg(windows)]
#[allow(clippy::absolute_paths)] // Platform-specific import not worth conditional use
fn create_symlink(target: &Path, dest: &Path, original_path: &Path) -> io::Result<()> {
    // On Windows, we need to know if the target is a directory
    let target_is_dir = original_path
        .parent()
        .map(|p| p.join(target))
        .and_then(|full| fs::metadata(full).ok())
        .is_some_and(|m| m.is_dir());

    if target_is_dir {
        std::os::windows::fs::symlink_dir(target, dest)
    } else {
        std::os::windows::fs::symlink_file(target, dest)
    }
}

/// Canonicalize an existing path, ensuring symlinks are resolved.
fn canonicalize_existing(path: &Path) -> Result<PathBuf> {
    fs::canonicalize(path).map_err(Error::from)
}

/// Convert a path to an absolute, cleaned form even if the final component does not yet exist.
fn canonicalize_for_destination(path: &Path) -> Result<PathBuf> {
    if path.exists() {
        return canonicalize_existing(path);
    }

    let absolute = absolutize(path)?;

    let mut existing = absolute.as_path();
    while !existing.exists() {
        existing = existing
            .parent()
            .ok_or_else(|| Error::Other("Destination path must include a parent".to_owned()))?;
    }

    let resolved_existing = canonicalize_existing(existing)?;
    let remainder = absolute
        .strip_prefix(existing)
        .map_err(|e| Error::Other(format!("Failed to strip prefix: {e}")))?;

    Ok(clean_path(&resolved_existing.join(remainder)))
}

/// Produce an absolute path with `.`/`..` removed, based on the current directory.
fn absolutize(path: &Path) -> Result<PathBuf> {
    let joined = if path.is_absolute() {
        path.to_path_buf()
    } else {
        env::current_dir()?.join(path)
    };

    Ok(clean_path(&joined))
}

/// Normalize a path by removing `.` and `..` components without touching symlinks.
///
/// Preserves the root component and does not pop past it. For example:
/// - `/foo/../bar` becomes `/bar`
/// - `/foo/../../bar` becomes `/bar` (cannot pop past root)
/// - `foo/../bar` becomes `bar`
/// - `foo/../../bar` becomes `../bar` (relative paths can accumulate `..`)
fn clean_path(path: &Path) -> PathBuf {
    let mut cleaned = PathBuf::new();
    let mut depth = 0usize; // Track depth below root for relative paths
    let mut has_root = false;

    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if depth > 0 {
                    cleaned.pop();
                    depth -= 1;
                } else if !has_root {
                    // Relative path going above starting point - preserve the ..
                    cleaned.push(component);
                }
                // If we have a root but depth is 0, ignore the .. (can't go above root)
            }
            Component::RootDir | Component::Prefix(_) => {
                cleaned.push(component);
                has_root = true;
            }
            Component::Normal(_) => {
                cleaned.push(component);
                depth += 1;
            }
        }
    }

    cleaned
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::TempDir;

    use super::*;

    fn write_file(path: &Path, contents: &str) {
        fs::write(path, contents).unwrap();
    }

    fn mkdir(path: &Path) {
        fs::create_dir_all(path).unwrap();
    }

    #[test]
    fn test_clone_tree_basic() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        // Create source structure
        fs::create_dir_all(&src)?;
        write_file(&src.join("file1.txt"), "content1");
        fs::create_dir(src.join("subdir"))?;
        write_file(&src.join("subdir/file2.txt"), "content2");

        // Clone the tree
        let opts = Options::new();
        clone_tree(&src, &dest, &opts)?;

        // Verify structure
        assert!(dest.join("file1.txt").exists());
        assert!(dest.join("subdir/file2.txt").exists());
        assert_eq!(fs::read_to_string(dest.join("file1.txt"))?, "content1");
        assert_eq!(
            fs::read_to_string(dest.join("subdir/file2.txt"))?,
            "content2"
        );

        Ok(())
    }

    #[test]
    fn test_clone_tree_with_excludes() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        // Create source structure
        fs::create_dir_all(&src)?;
        fs::write(src.join("file.txt"), "keep")?;
        fs::create_dir(src.join("target"))?;
        fs::write(src.join("target/build.out"), "exclude")?;
        fs::create_dir(src.join(".git"))?;
        write_file(&src.join(".git/config"), "exclude");

        // Clone with exclude globs (! prefix excludes)
        // Note: !dir/ excludes the directory itself, !dir/** only excludes contents
        let opts = Options::new().glob("!target/").glob("!.git/");
        clone_tree(&src, &dest, &opts)?;

        // Verify excludes worked
        assert!(dest.join("file.txt").exists());
        assert!(!dest.join("target").exists());
        assert!(!dest.join(".git").exists());

        Ok(())
    }

    #[test]
    fn test_clone_tree_with_positive_globs() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        // Create source structure
        fs::create_dir_all(&src)?;
        write_file(&src.join("include1.txt"), "include");
        write_file(&src.join("include2.txt"), "include");
        write_file(&src.join("exclude.log"), "exclude");
        fs::create_dir(src.join("data"))?;
        write_file(&src.join("data/file.txt"), "include");
        write_file(&src.join("data/debug.log"), "exclude");

        // Clone with positive globs (only include .txt files)
        let opts = Options::new().glob("**/*.txt");
        clone_tree(&src, &dest, &opts)?;

        // Verify only .txt files were included
        assert!(dest.join("include1.txt").exists());
        assert!(dest.join("include2.txt").exists());
        assert!(dest.join("data/file.txt").exists());
        assert!(!dest.join("exclude.log").exists());
        assert!(!dest.join("data/debug.log").exists());

        Ok(())
    }

    #[test]
    fn test_source_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let src = temp_dir.path().join("nonexistent");
        let dest = temp_dir.path().join("dest");

        let opts = Options::new();
        let result = clone_tree(&src, &dest, &opts);

        assert!(matches!(result, Err(Error::SourceNotFound { .. })));
    }

    #[test]
    fn test_source_not_directory() {
        let temp_dir = TempDir::new().unwrap();
        let src = temp_dir.path().join("file.txt");
        let dest = temp_dir.path().join("dest");

        // Create source as a file, not a directory
        fs::write(&src, "content").unwrap();

        let opts = Options::new();
        let result = clone_tree(&src, &dest, &opts);

        assert!(matches!(result, Err(Error::SourceNotDirectory { .. })));
    }

    #[test]
    fn test_destination_exists() {
        let temp_dir = TempDir::new().unwrap();
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        // Create both source and destination directories
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&dest).unwrap();

        let opts = Options::new();
        let result = clone_tree(&src, &dest, &opts);

        assert!(matches!(result, Err(Error::DestinationExists { .. })));
    }

    #[test]
    fn single_call_strategy_rejected_with_globs() {
        let opts = Options::new()
            .glob("**/*.rs")
            .strategy(CloneStrategy::SingleCall);
        let temp_dir = TempDir::new().unwrap();
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        fs::create_dir_all(&src).unwrap();

        let result = clone_tree(&src, &dest, &opts);
        assert!(matches!(result, Err(Error::IncompatibleOptions { .. })));
    }

    #[test]
    fn identical_paths_are_rejected() {
        let temp_dir = TempDir::new().unwrap();
        let src = temp_dir.path().join("dir");
        mkdir(&src);

        let opts = Options::new();
        let result = clone_tree(&src, &src, &opts);

        assert!(matches!(result, Err(Error::IdenticalPaths { .. })));
    }

    #[test]
    fn destination_inside_source_is_rejected() {
        let temp_dir = TempDir::new().unwrap();
        let src = temp_dir.path().join("src");
        let dest = src.join("nested/dest");
        mkdir(&src);

        let opts = Options::new();
        let result = clone_tree(&src, &dest, &opts);

        assert!(matches!(result, Err(Error::DestinationInsideSource { .. })));
    }

    #[test]
    fn source_inside_destination_is_rejected() {
        let temp_dir = TempDir::new().unwrap();
        let dest = temp_dir.path().join("dest");
        let src = dest.join("inner/src");
        mkdir(&src);

        let opts = Options::new();
        let result = clone_tree(&src, &dest, &opts);

        assert!(matches!(result, Err(Error::SourceInsideDestination { .. })));
    }

    #[cfg(unix)]
    #[test]
    fn symlinks_are_recreated() -> Result<()> {
        use std::os::unix::fs as unix_fs;

        let temp_dir = TempDir::new()?;
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        // Create source structure with symlinks
        fs::create_dir_all(&src)?;
        write_file(&src.join("file.txt"), "content");
        unix_fs::symlink("file.txt", src.join("link_to_file.txt"))?;

        // Create a subdirectory and symlink to it
        fs::create_dir(src.join("subdir"))?;
        write_file(&src.join("subdir/nested.txt"), "nested");
        unix_fs::symlink("subdir", src.join("link_to_dir"))?;

        // Clone the tree
        let opts = Options::new().strategy(CloneStrategy::FullTraversal);
        clone_tree(&src, &dest, &opts)?;

        // Verify file was copied
        assert!(dest.join("file.txt").exists());
        assert_eq!(fs::read_to_string(dest.join("file.txt"))?, "content");

        // Verify symlink to file was recreated as a symlink
        let link_meta = fs::symlink_metadata(dest.join("link_to_file.txt"))?;
        assert!(link_meta.file_type().is_symlink(), "should be a symlink");
        assert_eq!(fs::read_link(dest.join("link_to_file.txt"))?, PathBuf::from("file.txt"));
        // Verify the symlink works
        assert_eq!(fs::read_to_string(dest.join("link_to_file.txt"))?, "content");

        // Verify symlink to directory was recreated
        let dir_link_meta = fs::symlink_metadata(dest.join("link_to_dir"))?;
        assert!(dir_link_meta.file_type().is_symlink(), "should be a symlink");
        assert_eq!(fs::read_link(dest.join("link_to_dir"))?, PathBuf::from("subdir"));

        Ok(())
    }

    /// Verify that SingleCall strategy on macOS preserves symlinks via clonefile(2).
    /// This documents that the kernel handles symlinks correctly in single-call mode.
    #[cfg(target_os = "macos")]
    #[test]
    fn single_call_preserves_symlinks() -> Result<()> {
        use std::os::unix::fs as unix_fs;

        let temp_dir = TempDir::new()?;
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        // Create source structure with symlinks
        fs::create_dir_all(&src)?;
        write_file(&src.join("file.txt"), "content");
        unix_fs::symlink("file.txt", src.join("link_to_file.txt"))?;
        fs::create_dir(src.join("subdir"))?;
        unix_fs::symlink("subdir", src.join("link_to_dir"))?;

        // Clone using SingleCall strategy
        let opts = Options::new().strategy(CloneStrategy::SingleCall);
        clone_tree(&src, &dest, &opts)?;

        // Verify symlinks are preserved (clonefile preserves symlinks)
        let link_meta = fs::symlink_metadata(dest.join("link_to_file.txt"))?;
        assert!(link_meta.file_type().is_symlink(), "should be a symlink");
        assert_eq!(
            fs::read_link(dest.join("link_to_file.txt"))?,
            PathBuf::from("file.txt")
        );

        let dir_link_meta = fs::symlink_metadata(dest.join("link_to_dir"))?;
        assert!(dir_link_meta.file_type().is_symlink(), "should be a symlink");
        assert_eq!(
            fs::read_link(dest.join("link_to_dir"))?,
            PathBuf::from("subdir")
        );

        Ok(())
    }

    /// Test that file permissions are preserved during cloning.
    #[cfg(unix)]
    #[test]
    fn file_permissions_are_preserved() -> Result<()> {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = TempDir::new()?;
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        fs::create_dir_all(&src)?;

        // Create a file with specific permissions (executable)
        let executable = src.join("script.sh");
        write_file(&executable, "#!/bin/bash\necho hello");
        fs::set_permissions(&executable, fs::Permissions::from_mode(0o755))?;

        // Create a file with read-only permissions
        let readonly = src.join("readonly.txt");
        write_file(&readonly, "read only content");
        fs::set_permissions(&readonly, fs::Permissions::from_mode(0o444))?;

        // Create a file with default permissions for comparison
        let normal = src.join("normal.txt");
        write_file(&normal, "normal content");

        // Clone the tree
        let opts = Options::new().strategy(CloneStrategy::FullTraversal);
        clone_tree(&src, &dest, &opts)?;

        // Check executable permissions
        let dest_exec_perms = fs::metadata(dest.join("script.sh"))?.permissions().mode();
        let src_exec_perms = fs::metadata(&executable)?.permissions().mode();
        assert_eq!(
            dest_exec_perms & 0o777,
            src_exec_perms & 0o777,
            "executable permissions should be preserved"
        );

        // Check read-only permissions
        let dest_ro_perms = fs::metadata(dest.join("readonly.txt"))?.permissions().mode();
        let src_ro_perms = fs::metadata(&readonly)?.permissions().mode();
        assert_eq!(
            dest_ro_perms & 0o777,
            src_ro_perms & 0o777,
            "read-only permissions should be preserved"
        );

        Ok(())
    }

    /// Test that empty directories are preserved during cloning.
    #[test]
    fn empty_directories_are_preserved() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let src = temp_dir.path().join("src");
        let dest = temp_dir.path().join("dest");

        fs::create_dir_all(&src)?;

        // Create some empty directories
        fs::create_dir(src.join("empty1"))?;
        fs::create_dir(src.join("empty2"))?;
        fs::create_dir_all(src.join("nested/empty"))?;

        // Create a non-empty directory for comparison
        fs::create_dir(src.join("nonempty"))?;
        write_file(&src.join("nonempty/file.txt"), "content");

        // Clone the tree
        let opts = Options::new().strategy(CloneStrategy::FullTraversal);
        clone_tree(&src, &dest, &opts)?;

        // Check that empty directories exist
        assert!(
            dest.join("empty1").exists() && dest.join("empty1").is_dir(),
            "empty1 directory should exist"
        );
        assert!(
            dest.join("empty2").exists() && dest.join("empty2").is_dir(),
            "empty2 directory should exist"
        );
        assert!(
            dest.join("nested/empty").exists() && dest.join("nested/empty").is_dir(),
            "nested/empty directory should exist"
        );
        assert!(
            dest.join("nonempty/file.txt").exists(),
            "nonempty directory with file should exist"
        );

        Ok(())
    }

    #[test]
    fn clean_path_basic() {
        // Basic normalization
        assert_eq!(clean_path(Path::new("/foo/bar")), PathBuf::from("/foo/bar"));
        assert_eq!(clean_path(Path::new("/foo/../bar")), PathBuf::from("/bar"));
        assert_eq!(clean_path(Path::new("/foo/./bar")), PathBuf::from("/foo/bar"));
        assert_eq!(
            clean_path(Path::new("/foo/bar/../baz")),
            PathBuf::from("/foo/baz")
        );
    }

    #[test]
    fn clean_path_preserves_root() {
        // Cannot pop past root on absolute paths
        assert_eq!(clean_path(Path::new("/../foo")), PathBuf::from("/foo"));
        assert_eq!(clean_path(Path::new("/foo/../../bar")), PathBuf::from("/bar"));
        assert_eq!(
            clean_path(Path::new("/foo/../../../bar")),
            PathBuf::from("/bar")
        );
        // Edge case: just root with parent dirs
        assert_eq!(clean_path(Path::new("/..")), PathBuf::from("/"));
        assert_eq!(clean_path(Path::new("/../..")), PathBuf::from("/"));
    }

    #[test]
    fn clean_path_relative() {
        // Relative paths can accumulate .. components
        assert_eq!(clean_path(Path::new("foo/bar")), PathBuf::from("foo/bar"));
        assert_eq!(clean_path(Path::new("foo/../bar")), PathBuf::from("bar"));
        assert_eq!(clean_path(Path::new("foo/../../bar")), PathBuf::from("../bar"));
        assert_eq!(clean_path(Path::new("../foo")), PathBuf::from("../foo"));
        assert_eq!(clean_path(Path::new("../../foo")), PathBuf::from("../../foo"));
    }

    #[test]
    fn clean_path_empty_and_dot() {
        assert_eq!(clean_path(Path::new("")), PathBuf::from(""));
        assert_eq!(clean_path(Path::new(".")), PathBuf::from(""));
        assert_eq!(clean_path(Path::new("..")), PathBuf::from(".."));
        assert_eq!(clean_path(Path::new("./.")), PathBuf::from(""));
    }
}