fs-more 0.8.1

Convenient file and directory operations with progress reporting built on top of std::fs.
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
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
use std::{
    io::{self, ErrorKind},
    path::{Path, PathBuf},
};

use_enabled_fs_module!();


use super::{
    common::DestinationDirectoryRule,
    is_directory_empty_unchecked,
    BrokenSymlinkBehaviour,
    DirectoryCopyDepthLimit,
    SymlinkBehaviour,
};
use crate::{
    directory::common::join_relative_source_path_onto_destination,
    error::{
        CopyDirectoryPreparationError,
        DestinationDirectoryPathValidationError,
        DirectoryExecutionPlanError,
        SourceDirectoryPathValidationError,
    },
};


#[cfg(windows)]
#[derive(Clone, Copy, Debug)]
pub(crate) enum SymlinkType {
    File,
    Directory,
}


/// Represents a queued file copy, symlink, or directory creation operation.
///
/// For more details, see the [`build_directory_copy_queue`] function.
#[derive(Clone, Debug)]
pub(crate) enum QueuedOperation {
    /// Copy a file from `source_file_path` to `destination_file_path`.
    CopyFile {
        /// Where to copy a file from.
        source_file_path: PathBuf,

        /// Where to copy a file to.
        destination_file_path: PathBuf,

        /// Size of the `source_file_path` file in bytes.
        source_size_bytes: u64,
    },

    /// Create a directory at `destination_directory_path`.
    CreateDirectory {
        /// Directory to create.
        destination_directory_path: PathBuf,

        /// Whether to automatically create missing parent directories as well.
        ///
        /// This will use [`fs::create_dir_all`] instead of [`fs::create_dir`].
        create_parent_directories: bool,

        /// Size of the `destination_directory_path` directory in bytes.
        /// This is the size of the directory "file" itself on the filesystem,
        /// not a recursive size scan.
        source_size_bytes: u64,
    },

    /// Create a symbolic link at `symlink_path`.
    CreateSymlink {
        /// Where to create the symbolic link.
        ///
        /// This is a path under the destination directory, but this is not reflected in the
        /// field name to avoid mixups with meaning of "destination".
        symlink_path: PathBuf,

        /// This specifies whether the symlink destination is a file or a directory.
        ///
        /// This is present only on Windows targets, as we need to use a different API
        /// according to the symlink destination type.
        #[cfg(windows)]
        symlink_destination_type: SymlinkType,

        /// Where the symbolink link should point to.
        symlink_destination_path: PathBuf,

        /// Size of the symbolic link we're "copying".
        source_symlink_size_bytes: u64,
    },
}


/// Returns a boolean indicating whether the provided path exists.
///
/// Behaves similarly to [`fs::try_exists`],
/// but *does not follow symbolic links*.
///
/// If the `fs-err` feature flag is enabled, this function will automatically use it.
pub(crate) fn try_exists_without_follow(path: &Path) -> std::io::Result<bool> {
    match fs::symlink_metadata(path) {
        Ok(_) => Ok(true),
        Err(error) => match error.kind() {
            ErrorKind::NotFound => Ok(false),
            _ => Err(error),
        },
    }
}



/// Information about a validated source path (used in copying and moving directories).
#[derive(Clone, Debug)]
pub(crate) struct ValidatedSourceDirectory {
    pub(crate) directory_path: PathBuf,
    pub(crate) unfollowed_directory_path: PathBuf,
    pub(crate) original_path_was_symlink_to_directory: bool,
}

/// Ensures the given source directory path is valid.
///
/// This means that it exists, and that it is a directory.
/// Failing to find out whether it exists, or any similar read restriction,
/// will result in an error as well.
///
/// The returned [`ValidatedSourceDirectory`] contains the canonical path
/// of the provided `source_directory_path` which you should use in the future,
/// and, most importantly, for any path comparisons.
///
/// This also means that if `source_directory_path` is a symbolic link to a directory,
/// the validated version will have followed the link to its destination.
pub(super) fn validate_source_directory_path(
    source_directory_path: &Path,
) -> Result<ValidatedSourceDirectory, SourceDirectoryPathValidationError> {
    // Ensure the source directory path exists. We use `try_exists`
    // instead of `exists` to catch permission and other IO errors
    // as distinct from the `DirectoryError::NotFound` error.
    match try_exists_without_follow(source_directory_path) {
        Ok(exists) => {
            if !exists {
                return Err(SourceDirectoryPathValidationError::NotFound {
                    directory_path: source_directory_path.to_path_buf(),
                });
            }
        }
        Err(error) => {
            return Err(SourceDirectoryPathValidationError::UnableToAccess {
                directory_path: source_directory_path.to_path_buf(),
                error,
            });
        }
    }


    let is_symlink_to_directory = {
        let metadata_without_follow =
            fs::symlink_metadata(source_directory_path).map_err(|error| {
                SourceDirectoryPathValidationError::UnableToAccess {
                    directory_path: source_directory_path.to_path_buf(),
                    error,
                }
            })?;

        if metadata_without_follow.is_symlink() {
            let metadata_with_follow = fs::metadata(source_directory_path).map_err(|error| {
                SourceDirectoryPathValidationError::UnableToAccess {
                    directory_path: source_directory_path.to_path_buf(),
                    error,
                }
            })?;

            if !metadata_with_follow.is_dir() {
                return Err(SourceDirectoryPathValidationError::NotADirectory {
                    path: source_directory_path.to_path_buf(),
                });
            } else {
                true
            }
        } else if metadata_without_follow.is_dir() {
            false
        } else {
            return Err(SourceDirectoryPathValidationError::NotADirectory {
                path: source_directory_path.to_path_buf(),
            });
        }
    };


    let canonical_source_directory_path =
        fs::canonicalize(source_directory_path).map_err(|error| {
            SourceDirectoryPathValidationError::UnableToAccess {
                directory_path: source_directory_path.to_path_buf(),
                error,
            }
        })?;


    #[cfg(feature = "dunce")]
    {
        let de_unced_canonical_path =
            dunce::simplified(&canonical_source_directory_path).to_path_buf();

        Ok(ValidatedSourceDirectory {
            directory_path: de_unced_canonical_path,
            unfollowed_directory_path: source_directory_path.to_path_buf(),
            original_path_was_symlink_to_directory: is_symlink_to_directory,
        })
    }

    #[cfg(not(feature = "dunce"))]
    {
        Ok(ValidatedSourceDirectory {
            directory_path: canonical_source_directory_path,
            unfollowed_directory_path: source_directory_path.to_path_buf(),
            original_path_was_symlink_to_directory: is_symlink_to_directory,
        })
    }
}


#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum DestinationDirectoryState {
    /// Destination directory does not exist.
    DoesNotExist,

    /// Destination directory exists, but is empty.
    IsEmpty,

    /// Destination directory exists, and is not empty.
    IsNotEmpty,
}

impl DestinationDirectoryState {
    pub(crate) fn exists(&self) -> bool {
        !matches!(self, Self::DoesNotExist)
    }
}


/// Information about a validated target path (used in copying and moving directories).
///
/// "Valid" in this context means that it respects the user-provided `options`,
/// see [`validate_target_directory_path`].
#[derive(Clone, Debug)]
pub(crate) struct ValidatedDestinationDirectory {
    pub(crate) directory_path: PathBuf,
    pub(crate) state: DestinationDirectoryState,
}

/// Ensures the given destination directory path is valid.
///
/// This means that it respects the provided [`DestinationDirectoryRule`].
///
/// The returned [`ValidatedDestinationDirectory`] contains the canonical path
/// of the provided `destination_directory_path` which you should use in the future,
/// and, most importantly, for any path comparisons.
///
/// This also means that if `destination_directory_path` exists, and is a symbolic link to a directory,
/// the validated version will have followed the link to its target.
pub(super) fn validate_destination_directory_path(
    destination_directory_path: &Path,
    destination_directory_rule: DestinationDirectoryRule,
) -> Result<ValidatedDestinationDirectory, DestinationDirectoryPathValidationError> {
    let destination_directory_exists = try_exists_without_follow(destination_directory_path)
        .map_err(|error| DestinationDirectoryPathValidationError::UnableToAccess {
            directory_path: destination_directory_path.to_path_buf(),
            error,
        })?;

    // If `destination_directory_path` exists, but does not point to a directory,
    // we should abort.
    if destination_directory_exists && !destination_directory_path.is_dir() {
        return Err(DestinationDirectoryPathValidationError::NotADirectory {
            directory_path: destination_directory_path.to_path_buf(),
        });
    }


    let resolved_destination_directory_path = if destination_directory_exists {
        let canonical_destination_directory_path = fs::canonicalize(destination_directory_path)
            .map_err(|error| DestinationDirectoryPathValidationError::UnableToAccess {
                directory_path: destination_directory_path.to_path_buf(),
                error,
            })?;


        #[cfg(feature = "dunce")]
        {
            dunce::simplified(&canonical_destination_directory_path).to_path_buf()
        }

        #[cfg(not(feature = "dunce"))]
        {
            canonical_destination_directory_path
        }
    } else {
        destination_directory_path.to_path_buf()
    };


    let destination_directory_state = if destination_directory_exists {
        let is_empty = is_directory_empty_unchecked(&resolved_destination_directory_path).map_err(
            |error| DestinationDirectoryPathValidationError::UnableToAccess {
                directory_path: resolved_destination_directory_path.to_path_buf(),
                error,
            },
        )?;

        if is_empty {
            DestinationDirectoryState::IsEmpty
        } else {
            DestinationDirectoryState::IsNotEmpty
        }
    } else {
        DestinationDirectoryState::DoesNotExist
    };


    match destination_directory_rule {
        DestinationDirectoryRule::DisallowExisting => {
            if !matches!(destination_directory_state, DestinationDirectoryState::DoesNotExist) {
                return Err(DestinationDirectoryPathValidationError::AlreadyExists {
                    path: resolved_destination_directory_path,
                    destination_directory_rule,
                });
            }
        }
        DestinationDirectoryRule::AllowEmpty => {
            if !matches!(
                destination_directory_state,
                DestinationDirectoryState::DoesNotExist | DestinationDirectoryState::IsEmpty
            ) {
                return Err(DestinationDirectoryPathValidationError::NotEmpty {
                    directory_path: resolved_destination_directory_path,
                    destination_directory_rule,
                });
            }
        }
        DestinationDirectoryRule::AllowNonEmpty { .. } => {}
    }


    Ok(ValidatedDestinationDirectory {
        directory_path: resolved_destination_directory_path,
        state: destination_directory_state,
    })
}



/// Given a source and destination directory path, intended for copying or moving,
/// this function ensures the provided path *pair* is valid.
///
/// **Both paths MUST already be their canonical versions**,
/// for example, outputs of [`validate_source_directory_path`]
/// and [`validate_destination_directory_path`].
///
/// This fails, for example, when `source_directory_path` is a sub-path
/// of `destination_directory_path`.
pub(super) fn validate_source_destination_directory_pair(
    source_directory_path: &Path,
    destination_directory_path: &Path,
) -> Result<(), DestinationDirectoryPathValidationError> {
    // Ensure `destination_directory_path` isn't equal,
    // or a subdirectory of, `source_directory_path`Ë™.
    if destination_directory_path.starts_with(source_directory_path) {
        return Err(DestinationDirectoryPathValidationError::DescendantOfSourceDirectory {
            destination_directory_path: destination_directory_path.to_path_buf(),
            source_directory_path: source_directory_path.to_path_buf(),
        });
    }

    Ok(())
}


/// Given a source and destination directory as well as the maximum copy depth,
/// this function builds a list of [`QueuedOperation`]s that are needed to fully,
/// or up to the depth limit, copy the source directory to the destination directory.
///
/// The order of directory creation and file copying operations is such that
/// for any file in the list, the creation of its parent directory
/// appears before it in the queue.
///
/// Note, however, that **the queued operations do not include creation of
/// the `destination_directory_path` directory itself**,
/// even if that is necessary for a copy; it is up to the consumer to create
/// `destination_directory_path`, if need be, before executing the queue.
fn scan_and_plan_directory_copy(
    validated_source_directory: &ValidatedSourceDirectory,
    validated_destination_directory: &ValidatedDestinationDirectory,
    copy_depth_limit: DirectoryCopyDepthLimit,
    symlink_behaviour: SymlinkBehaviour,
    broken_symlink_behaviour: BrokenSymlinkBehaviour,
) -> Result<Vec<QueuedOperation>, DirectoryExecutionPlanError> {
    let mut operation_queue: Vec<QueuedOperation> = Vec::new();


    // Special case: if the source directory path was a symbolic link to a directory
    // and the symlink behaviour is set to keep, we should preserve that symlink on the destination.
    // This means we only need one operation.
    if symlink_behaviour == SymlinkBehaviour::Keep
        && validated_source_directory.original_path_was_symlink_to_directory
    {
        let source_symlink_size_bytes =
            fs::symlink_metadata(&validated_source_directory.directory_path)
                .map_err(|error| DirectoryExecutionPlanError::UnableToAccess {
                    path: validated_source_directory.directory_path.clone(),
                    error,
                })?
                .len();


        #[cfg(windows)]
        {
            operation_queue.push(QueuedOperation::CreateSymlink {
                symlink_path: validated_destination_directory.directory_path.to_path_buf(),
                symlink_destination_type: SymlinkType::Directory,
                source_symlink_size_bytes,
                symlink_destination_path: validated_source_directory.directory_path.to_path_buf(),
            });
        }

        #[cfg(not(windows))]
        {
            operation_queue.push(QueuedOperation::CreateSymlink {
                symlink_path: validated_destination_directory.directory_path.to_path_buf(),
                source_symlink_size_bytes,
                symlink_destination_path: validated_source_directory.directory_path.to_path_buf(),
            });
        }


        return Ok(operation_queue);
    }


    // Queue creating the base destination directory if needed.
    if !validated_destination_directory.state.exists() {
        let source_path_size_bytes =
            fs::symlink_metadata(&validated_source_directory.directory_path)
                .map_err(|error| DirectoryExecutionPlanError::UnableToAccess {
                    path: validated_source_directory.directory_path.to_path_buf(),
                    error,
                })?
                .len();

        operation_queue.push(QueuedOperation::CreateDirectory {
            source_size_bytes: source_path_size_bytes,
            destination_directory_path: validated_destination_directory
                .directory_path
                .to_path_buf(),
            create_parent_directories: true,
        });
    }


    // Scan the source directory and queue all copy and
    // directory creation operations that need to happen.
    struct PendingDirectoryScan {
        directory_path: PathBuf,
        directory_path_without_symlink_follows: PathBuf,
        depth: usize,
    }

    let mut directory_scan_queue = Vec::new();
    directory_scan_queue.push(PendingDirectoryScan {
        directory_path: validated_source_directory.directory_path.clone(),
        directory_path_without_symlink_follows: validated_source_directory.directory_path.clone(),
        depth: 0,
    });


    // TODO Refactor this giant loop into smaller functions.

    while let Some(next_directory) = directory_scan_queue.pop() {
        // Scan the directory for its files and directories.
        // Files are queued for copying, directories are queued for creation.
        let directory_iterator = fs::read_dir(&next_directory.directory_path).map_err(|error| {
            DirectoryExecutionPlanError::UnableToAccess {
                path: next_directory.directory_path.clone(),
                error,
            }
        })?;

        for directory_item in directory_iterator {
            let directory_item =
                directory_item.map_err(|error| DirectoryExecutionPlanError::UnableToAccess {
                    path: next_directory.directory_path.clone(),
                    error,
                })?;

            let directory_item_source_path = directory_item.path();
            let directory_item_name = directory_item_source_path.file_name().ok_or_else(|| {
                DirectoryExecutionPlanError::UnableToAccess {
                    path: directory_item_source_path.clone(),
                    error: io::Error::new(
                        ErrorKind::Other,
                        "ReadDir's iterator generated a path that terminates in \"..\"",
                    ),
                }
            })?;

            // We construct an updated `directory_path_without_symlink_follows` manually,
            // since following symlinks can make it hard to understand where under the
            // original source directory structure we are. But only if we have a sub-path of the
            // source directory can we correctly remap the relative sub-path inside the source
            // onto the destination directory.
            let new_directory_path_without_symlink_follows = next_directory
                .directory_path_without_symlink_follows
                .join(directory_item_name);


            // Remaps `new_directory_path_without_symlink_follows` (relative to `next_directory.source_directory_path`)
            // onto `destination_directory_path`, preserving directory structure.
            let directory_item_destination_path = join_relative_source_path_onto_destination(
                &validated_source_directory.directory_path,
                &new_directory_path_without_symlink_follows,
                &validated_destination_directory.directory_path,
            )
            .map_err(|error| {
                DirectoryExecutionPlanError::EntryEscapesSourceDirectory { path: error.path }
            })?;


            // For clarity: this call will not traverse symlinks.
            let item_type = directory_item.file_type().map_err(|error| {
                DirectoryExecutionPlanError::UnableToAccess {
                    path: directory_item_source_path.clone(),
                    error,
                }
            })?;


            if item_type.is_file() {
                let file_metadata = directory_item.metadata().map_err(|error| {
                    DirectoryExecutionPlanError::UnableToAccess {
                        path: directory_item_source_path.clone(),
                        error,
                    }
                })?;

                let file_size_in_bytes = file_metadata.len();


                operation_queue.push(QueuedOperation::CopyFile {
                    source_file_path: directory_item_source_path,
                    source_size_bytes: file_size_in_bytes,
                    destination_file_path: directory_item_destination_path,
                });
            } else if item_type.is_dir() {
                let directory_metadata = directory_item.metadata().map_err(|error| {
                    DirectoryExecutionPlanError::UnableToAccess {
                        path: directory_item_source_path.clone(),
                        error,
                    }
                })?;

                // Note that this is the size of the directory itself, not of its contents.
                let directory_size_in_bytes = directory_metadata.len();


                operation_queue.push(QueuedOperation::CreateDirectory {
                    source_size_bytes: directory_size_in_bytes,
                    destination_directory_path: directory_item_destination_path,
                    create_parent_directories: false,
                });


                // If we haven't reached the maximum depth yet, we queue the directory
                // to be scanned for further files and sub-directories.
                match copy_depth_limit {
                    DirectoryCopyDepthLimit::Limited { maximum_depth } => {
                        if next_directory.depth < maximum_depth {
                            directory_scan_queue.push(PendingDirectoryScan {
                                directory_path: directory_item_source_path.clone(),
                                directory_path_without_symlink_follows:
                                    new_directory_path_without_symlink_follows,
                                depth: next_directory.depth + 1,
                            });
                        }
                    }
                    DirectoryCopyDepthLimit::Unlimited => {
                        directory_scan_queue.push(PendingDirectoryScan {
                            directory_path: directory_item_source_path.clone(),
                            directory_path_without_symlink_follows:
                                new_directory_path_without_symlink_follows,
                            depth: next_directory.depth + 1,
                        });
                    }
                };
            } else if item_type.is_symlink() {
                // If the path is a symbolic link, we need to follow it and queue a copy
                // from the underlying file or directory.

                let resolved_symlink_path =
                    fs::read_link(&directory_item_source_path).map_err(|error| {
                        DirectoryExecutionPlanError::UnableToAccess {
                            path: directory_item_source_path.clone(),
                            error,
                        }
                    })?;

                // The absolute symlink destination path will only be resolved if the original path
                // as-is from fs::read_link is relative. This is because relative symlinks must be interpreted
                // relative to the directory they are in, not relative to the current directory.
                let resolved_absolute_symlink_pathbuf = if resolved_symlink_path.is_relative() {
                    let symlink_parent_directory_path = &next_directory.directory_path;

                    let resolved_absolute_symlink_path =
                        symlink_parent_directory_path.join(&resolved_symlink_path);

                    Some(resolved_absolute_symlink_path)
                } else {
                    None
                };


                let resolved_absolute_symlink_path = resolved_absolute_symlink_pathbuf
                    .as_ref()
                    .unwrap_or(&resolved_symlink_path);


                let resolved_symlink_path_exists =
                    try_exists_without_follow(resolved_absolute_symlink_path).map_err(|error| {
                        DirectoryExecutionPlanError::UnableToAccess {
                            path: resolved_absolute_symlink_path.to_path_buf(),
                            error,
                        }
                    })?;


                if !resolved_symlink_path_exists {
                    // This symbolic link is broken, we should look at the
                    // corresponding `broken_symlink_behaviour` option and act accordingly.

                    let unresolved_symlink_metadata =
                        fs::symlink_metadata(&directory_item_source_path).map_err(|error| {
                            DirectoryExecutionPlanError::UnableToAccess {
                                path: directory_item_source_path.clone(),
                                error,
                            }
                        })?;

                    let unresolved_symlink_file_size = unresolved_symlink_metadata.len();


                    #[cfg(windows)]
                    {
                        use std::os::windows::fs::FileTypeExt;

                        match broken_symlink_behaviour {
                            BrokenSymlinkBehaviour::Keep => {
                                let unresolved_symlink_file_type =
                                    unresolved_symlink_metadata.file_type();

                                let symbolic_link_type = if unresolved_symlink_file_type
                                    .is_symlink_file()
                                {
                                    SymlinkType::File
                                } else if unresolved_symlink_file_type.is_symlink_dir() {
                                    SymlinkType::Directory
                                } else {
                                    panic!("Unexpected symbolic link type: neither file nor directory.");
                                };


                                operation_queue.push(QueuedOperation::CreateSymlink {
                                    symlink_path: directory_item_destination_path,
                                    symlink_destination_type: symbolic_link_type,
                                    source_symlink_size_bytes: unresolved_symlink_file_size,
                                    symlink_destination_path: resolved_symlink_path,
                                });
                            }
                            BrokenSymlinkBehaviour::Abort => {
                                return Err(DirectoryExecutionPlanError::SymbolicLinkIsBroken {
                                    path: directory_item_source_path.clone(),
                                });
                            }
                        }
                    }

                    #[cfg(unix)]
                    {
                        match broken_symlink_behaviour {
                            BrokenSymlinkBehaviour::Keep => {
                                operation_queue.push(QueuedOperation::CreateSymlink {
                                    symlink_path: directory_item_destination_path,
                                    source_symlink_size_bytes: unresolved_symlink_file_size,
                                    symlink_destination_path: resolved_symlink_path,
                                });
                            }
                            BrokenSymlinkBehaviour::Abort => {
                                return Err(DirectoryExecutionPlanError::SymbolicLinkIsBroken {
                                    path: directory_item_source_path.clone(),
                                });
                            }
                        }
                    }

                    #[cfg(not(any(windows, unix)))]
                    {
                        compile_error!(
                            "fs-more supports only the following values of target_family: \
                            unix and windows (notably, wasm is unsupported)."
                        );
                    }

                    continue;
                }


                // Symbolic link is valid, we should look at the corresponding
                // `symlink_behaviour` option.

                let resolved_symlink_metadata = fs::metadata(resolved_absolute_symlink_path)
                    .map_err(|error| DirectoryExecutionPlanError::UnableToAccess {
                        path: resolved_symlink_path.clone(),
                        error,
                    })?;


                let resolved_symlink_file_type = resolved_symlink_metadata.file_type();
                let resolved_symlink_file_size = resolved_symlink_metadata.len();


                match symlink_behaviour {
                    SymlinkBehaviour::Keep => {
                        // Symbolic link should be preserved.
                        // Note that success is not guaranteed, e.g. in cases of
                        // trying to create symbolic links across mount points.

                        #[cfg(windows)]
                        {
                            let symlink_type = if resolved_symlink_file_type.is_file() {
                                SymlinkType::File
                            } else if resolved_symlink_file_type.is_dir() {
                                SymlinkType::Directory
                            } else if resolved_symlink_file_type.is_symlink() {
                                //       Context for future readers: this branch seems impossible to reach,
                                //       since we used fs::metadata which follows symbolic links.
                                unreachable!(
                                    "unexpected filesystem state: followed symbolic link(s), \
                                    but arrived at another symbolic link"
                                )
                            } else {
                                //       Context for future readers: this branch seems impossible to reach,
                                //       since we used fs::metadata. For this to happen, is_file, is_dir and is_symlink
                                //       all need to return `false`. If you encounter this panic, report it to the issue tracker.
                                unreachable!(
                                    "unexpected filesystem state: followed symbolic link(s), \
                                    but arrived at something that is none of: file, directory, symlink"
                                );
                            };


                            operation_queue.push(QueuedOperation::CreateSymlink {
                                symlink_path: directory_item_destination_path,
                                symlink_destination_type: symlink_type,
                                source_symlink_size_bytes: resolved_symlink_file_size,
                                symlink_destination_path: resolved_symlink_path,
                            });
                        }

                        #[cfg(unix)]
                        {
                            operation_queue.push(QueuedOperation::CreateSymlink {
                                symlink_path: directory_item_destination_path,
                                source_symlink_size_bytes: resolved_symlink_file_size,
                                symlink_destination_path: resolved_symlink_path,
                            });
                        }

                        #[cfg(not(any(windows, unix)))]
                        {
                            compile_error!(
                                "fs-more supports only the following values of target_family: \
                                unix and windows (notably, wasm is unsupported)."
                            );
                        }
                    }
                    SymlinkBehaviour::Follow => {
                        // Symbolic link should be resolved, and a copy of the
                        // symlink's destination to the copy destination should be queued.
                        if resolved_symlink_file_type.is_file() {
                            operation_queue.push(QueuedOperation::CopyFile {
                                source_file_path: resolved_absolute_symlink_path.to_path_buf(),
                                source_size_bytes: resolved_symlink_file_size,
                                destination_file_path: directory_item_destination_path,
                            });
                        } else if resolved_symlink_file_type.is_dir() {
                            operation_queue.push(QueuedOperation::CreateDirectory {
                                source_size_bytes: resolved_symlink_file_size,
                                destination_directory_path: directory_item_destination_path,
                                create_parent_directories: false,
                            });


                            // If we haven't reached the maximum depth yet,
                            // we queue the symlink-followed directory for scanning.
                            match copy_depth_limit {
                                DirectoryCopyDepthLimit::Limited { maximum_depth } => {
                                    if next_directory.depth < maximum_depth {
                                        directory_scan_queue.push(PendingDirectoryScan {
                                            directory_path: directory_item_source_path.clone(),
                                            directory_path_without_symlink_follows:
                                                new_directory_path_without_symlink_follows,
                                            depth: next_directory.depth + 1,
                                        });
                                    }
                                }
                                DirectoryCopyDepthLimit::Unlimited => {
                                    directory_scan_queue.push(PendingDirectoryScan {
                                        directory_path: directory_item_source_path,
                                        directory_path_without_symlink_follows:
                                            new_directory_path_without_symlink_follows,
                                        depth: next_directory.depth + 1,
                                    });
                                }
                            };
                        } else if resolved_symlink_file_type.is_symlink() {
                            //       Context for future readers: this branch seems impossible to reach,
                            //       since we used fs::metadata, which follows symbolic links.
                            unreachable!(
                                "unexpected filesystem state: followed symbolic link(s), \
                                but arrived at another symbolic link"
                            )
                        }
                    }
                }
            }
        }
    }

    Ok(operation_queue)
}


/// Given a list of references to [`QueuedOperation`]s, this function validates that
/// the files and directories this queue would process match the provided [`DestinationDirectoryRule`].
fn check_operation_queue_for_collisions(
    queue: &[QueuedOperation],
    destination_directory_rules: DestinationDirectoryRule,
) -> Result<(), DirectoryExecutionPlanError> {
    let overwriting_existing_destination_files_allowed =
        destination_directory_rules.allows_overwriting_existing_destination_files();

    let existing_destination_subdirectories_allowed =
        destination_directory_rules.allows_existing_destination_subdirectories();


    if overwriting_existing_destination_files_allowed && existing_destination_subdirectories_allowed
    {
        // There is nothing to check, as we can have any collisions we want
        // if we allow everything to be overwritten.
        return Ok(());
    }


    for queue_item in queue {
        match queue_item {
            QueuedOperation::CopyFile {
                destination_file_path,
                ..
            } => {
                if !overwriting_existing_destination_files_allowed {
                    let destination_file_exists = try_exists_without_follow(destination_file_path)
                        .map_err(|error| DirectoryExecutionPlanError::UnableToAccess {
                            path: destination_file_path.to_path_buf(),
                            error,
                        })?;

                    if destination_file_exists {
                        return Err(DirectoryExecutionPlanError::DestinationItemAlreadyExists {
                            path: destination_file_path.clone(),
                        });
                    }
                }
            }

            QueuedOperation::CreateDirectory {
                destination_directory_path,
                ..
            } => {
                if !existing_destination_subdirectories_allowed {
                    let destination_directory_exists =
                        try_exists_without_follow(destination_directory_path).map_err(|error| {
                            DirectoryExecutionPlanError::UnableToAccess {
                                path: destination_directory_path.to_path_buf(),
                                error,
                            }
                        })?;

                    if destination_directory_exists {
                        return Err(DirectoryExecutionPlanError::DestinationItemAlreadyExists {
                            path: destination_directory_path.clone(),
                        });
                    }
                }
            }

            QueuedOperation::CreateSymlink { symlink_path, .. } => {
                if !overwriting_existing_destination_files_allowed {
                    let symlink_path_exists =
                        try_exists_without_follow(symlink_path).map_err(|error| {
                            DirectoryExecutionPlanError::UnableToAccess {
                                path: symlink_path.to_path_buf(),
                                error,
                            }
                        })?;

                    if symlink_path_exists {
                        return Err(DirectoryExecutionPlanError::DestinationItemAlreadyExists {
                            path: symlink_path.to_path_buf(),
                        });
                    }
                }
            }
        }
    }

    Ok(())
}



/// An auxiliary struct that contains a set of operations required for a directory copy.
///
/// It can be initialized by calling [`Self::prepare`] or [`Self::prepare_with_validated`].
pub(crate) struct DirectoryCopyPrepared {
    /// An array of ordered file copy and directory creation operations
    /// that togeher form a requested directory copy.
    pub(crate) operation_queue: Vec<QueuedOperation>,

    /// How many bytes will need to be copied (i.e. the source directory size).
    pub(crate) total_bytes: u64,
}


impl DirectoryCopyPrepared {
    /// Prepare for a new directory copy.
    ///
    /// This includes validating both the source and destination directory paths
    /// as well as preparing the operation queue.
    pub fn prepare(
        source_directory_path: &Path,
        destination_directory_path: &Path,
        destination_directory_rule: DestinationDirectoryRule,
        copy_depth_limit: DirectoryCopyDepthLimit,
        symlink_behaviour: SymlinkBehaviour,
        broken_symlink_behaviour: BrokenSymlinkBehaviour,
    ) -> Result<Self, CopyDirectoryPreparationError> {
        let (canonical_source_directory_path, validated_destination) =
            Self::validate_source_and_destination(
                source_directory_path,
                destination_directory_path,
                destination_directory_rule,
            )?;

        Self::prepare_with_validated(
            canonical_source_directory_path,
            validated_destination,
            destination_directory_rule,
            copy_depth_limit,
            symlink_behaviour,
            broken_symlink_behaviour,
        )
        .map_err(CopyDirectoryPreparationError::CopyPlanningError)
    }

    /// Prepare for a new directory copy with already-validated source and destination.
    ///
    /// This preparation therefore only includes preparing the operation queue.
    pub fn prepare_with_validated(
        validated_source_directory: ValidatedSourceDirectory,
        validated_destination_directory: ValidatedDestinationDirectory,
        destination_directory_rule: DestinationDirectoryRule,
        copy_depth_limit: DirectoryCopyDepthLimit,
        symlink_behaviour: SymlinkBehaviour,
        broken_symlink_behaviour: BrokenSymlinkBehaviour,
    ) -> Result<Self, DirectoryExecutionPlanError> {
        let operations = Self::prepare_directory_operations(
            &validated_source_directory,
            &validated_destination_directory,
            destination_directory_rule,
            copy_depth_limit,
            symlink_behaviour,
            broken_symlink_behaviour,
        )?;

        let bytes_total = Self::calculate_total_bytes_to_be_copied(&operations);


        Ok(Self {
            operation_queue: operations,
            total_bytes: bytes_total,
        })
    }

    fn calculate_total_bytes_to_be_copied(queued_operations: &[QueuedOperation]) -> u64 {
        queued_operations
            .iter()
            .map(|item| match item {
                QueuedOperation::CopyFile {
                    source_size_bytes, ..
                } => *source_size_bytes,
                QueuedOperation::CreateDirectory {
                    source_size_bytes, ..
                } => *source_size_bytes,
                QueuedOperation::CreateSymlink {
                    source_symlink_size_bytes: source_size_bytes,
                    ..
                } => *source_size_bytes,
            })
            .sum::<u64>()
    }

    fn validate_source_and_destination(
        source_directory_path: &Path,
        destination_directory_path: &Path,
        destination_directory_rule: DestinationDirectoryRule,
    ) -> Result<
        (ValidatedSourceDirectory, ValidatedDestinationDirectory),
        CopyDirectoryPreparationError,
    > {
        let validated_source_directory = validate_source_directory_path(source_directory_path)?;
        let validated_target_directory = validate_destination_directory_path(
            destination_directory_path,
            destination_directory_rule,
        )?;

        validate_source_destination_directory_pair(
            &validated_source_directory.directory_path,
            &validated_target_directory.directory_path,
        )?;

        Ok((validated_source_directory, validated_target_directory))
    }

    /// Scans the source directory and prepares a plan (a set of operations)
    /// to copy the source directory to the destination directory, as configured.
    ///
    /// <br>
    ///
    /// We also do a destination directory collision check in the hopes of catching existing mismatches
    /// of the provided `destination_directory_rule` early, before we actually copy any file at all.
    /// This way the target directory stays intact if there is any collision,
    /// instead of returning an error after having copied some files already,
    /// which would leave the destination directory in an unpredictable state.
    ///
    /// It's of course still possible that the destination directory ends up in an unpredictable state,
    /// since a [time-of-check time-of-use](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use)
    /// race condition is still possible.
    /// However, those cases should be very rare and are essentially unsolvable,
    /// unless there was a robust rollback mechanism (but this would require platform-specific implementation).
    /// For example: Windows
    /// [cautions against using transactional NTFS](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-findfirstfiletransacteda)).
    fn prepare_directory_operations(
        validated_source_directory: &ValidatedSourceDirectory,
        validated_destination_directory: &ValidatedDestinationDirectory,
        destination_directory_rule: DestinationDirectoryRule,
        copy_depth_limit: DirectoryCopyDepthLimit,
        symlink_behaviour: SymlinkBehaviour,
        broken_symlink_behaviour: BrokenSymlinkBehaviour,
    ) -> Result<Vec<QueuedOperation>, DirectoryExecutionPlanError> {
        // Initialize a queue of file copy or directory create operations.
        let copy_queue = scan_and_plan_directory_copy(
            validated_source_directory,
            validated_destination_directory,
            copy_depth_limit,
            symlink_behaviour,
            broken_symlink_behaviour,
        )?;

        check_operation_queue_for_collisions(&copy_queue, destination_directory_rule)?;

        Ok(copy_queue)
    }
}