git-cow 0.7.0

Git worktrees that share files with a template through copy-on-write clones (APFS, XFS, btrfs, ReFS)
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
//! Windows block cloning via `FSCTL_DUPLICATE_EXTENTS_TO_FILE`

mod win32;

use std::fs::{self, File, OpenOptions};
use std::io;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::fs::{MetadataExt, OpenOptionsExt, symlink_dir, symlink_file};
use std::path::{Path, PathBuf};

use win32::{
    FILE_ATTRIBUTE_ARCHIVE, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_HIDDEN,
    FILE_ATTRIBUTE_NOT_CONTENT_INDEXED, FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_REPARSE_POINT,
    FILE_ATTRIBUTE_SPARSE_FILE, FILE_ATTRIBUTE_SYSTEM, FILE_FLAG_BACKUP_SEMANTICS,
    FILE_FLAG_OPEN_REPARSE_POINT, IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK,
    IntegrityInformation,
};

const CLONE_LIMIT: u64 = 1 << 32;
const BASIC_ATTRIBUTES: u32 = FILE_ATTRIBUTE_READONLY
    | FILE_ATTRIBUTE_HIDDEN
    | FILE_ATTRIBUTE_SYSTEM
    | FILE_ATTRIBUTE_ARCHIVE
    | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;

// Where a cloned tree lands. A junction holds an absolute path, so a copy of it would lead back
// into the source, and a tool that writes or deletes through it would change the source. A
// junction is cloned only when it resolves inside `from`, and then points at its place under `to`.
// The clone carries over only `carried`, part of `from`, so a junction that resolves elsewhere in
// `from` must also resolve inside `to` where `to` already is
struct Links {
    from: PathBuf,
    carried: PathBuf,
    to: PathBuf,
}

fn outside() -> io::Error {
    io::Error::new(
        io::ErrorKind::Unsupported,
        "junction leads out of the cloned folder",
    )
}

impl Links {
    // Where the junction at `src` points in the copy. Resolving every link on the way checks the
    // folder the junction really reaches, and a dangling junction fails
    fn retarget(&self, src: &Path) -> io::Result<PathBuf> {
        let real = fs::canonicalize(src).map_err(|_| outside())?;
        let inner = real.strip_prefix(&self.from).map_err(|_| outside())?;
        // Joining an empty path would add a trailing backslash
        let target = if inner.as_os_str().is_empty() {
            self.to.clone()
        } else {
            self.to.join(inner)
        };
        if !real.starts_with(&self.carried) {
            let there = fs::canonicalize(&target).map_err(|_| outside())?;
            let to = fs::canonicalize(&self.to).map_err(|_| outside())?;
            if !there.starts_with(to) {
                return Err(outside());
            }
        }
        Ok(target)
    }
}

/**
 * Clone `src` to `dst_dir/<its name>`, where `dst_dir` takes the place of `src`'s folder. A
 * junction that resolves inside that folder points at the same place under `dst_dir`, which the
 * caller fills with the rest of the folder
 **/
pub(super) fn clone_into(src: &Path, dst_dir: &Path) -> io::Result<()> {
    clone_with(src, dst_dir, || {
        let parent = src
            .parent()
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "source has no parent"))?;
        let from = fs::canonicalize(parent)?;
        Ok(Links {
            carried: from.clone(),
            from,
            to: std::path::absolute(dst_dir)?,
        })
    })
}

/**
 * Clone `src` to `dst_dir/<its name>`, for a tree that then moves to its place under `to`, which
 * already takes the place of `from`. A junction that resolves inside `src` points at the same place
 * in the moved copy. One that resolves elsewhere in `from` points at its place under `to`, which
 * must exist and stay inside `to`. Any other junction fails the clone
 **/
pub(super) fn clone_moved(src: &Path, dst_dir: &Path, from: &Path, to: &Path) -> io::Result<()> {
    clone_with(src, dst_dir, || {
        // Where `src` itself is, not where it leads when it is a junction
        let (Some(parent), Some(name)) = (src.parent(), src.file_name()) else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "source has no parent",
            ));
        };
        Ok(Links {
            from: fs::canonicalize(from)?,
            carried: fs::canonicalize(parent)?.join(name),
            to: std::path::absolute(to)?,
        })
    })
}

fn clone_with(
    src: &Path,
    dst_dir: &Path,
    links: impl FnOnce() -> io::Result<Links>,
) -> io::Result<()> {
    let name = src
        .file_name()
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "source has no name"))?;
    links()
        .and_then(|links| clone_entry(src, &dst_dir.join(name), &links))
        .map_err(|e| io::Error::new(e.kind(), format!("block clone {}: {e}", src.display())))
}

fn cluster_size(info: &IntegrityInformation) -> io::Result<u64> {
    // Alignment is in filesystem clusters, not integrity checksum chunks
    let size = u64::from(info.cluster_size);
    if !size.is_power_of_two() || size >= CLONE_LIMIT {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "invalid cluster size",
        ));
    }
    Ok(size)
}

fn clone_entry(src: &Path, dst: &Path, links: &Links) -> io::Result<()> {
    let meta = fs::symlink_metadata(src)?;
    if meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
        return clone_reparse_point(src, dst, &meta, links);
    }
    if meta.is_dir() {
        fs::create_dir(dst)?;
        for entry in fs::read_dir(src)? {
            let entry = entry?;
            clone_entry(&entry.path(), &dst.join(entry.file_name()), links)?;
        }
        return Ok(());
    }
    clone_file(src, dst)
}

fn reparse_options() -> OpenOptions {
    let mut options = File::options();
    options.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
    options
}

fn read_reparse_data(path: &Path) -> io::Result<Vec<u8>> {
    // GET_REPARSE_POINT only needs a handle, not permission to list the directory
    win32::reparse_data(&reparse_options().access_mode(0).open(path)?)
}

fn reparse_tag(data: &[u8]) -> u32 {
    u32::from_le_bytes(*data.first_chunk().expect("validated reparse header"))
}

// The junction record for `target`, a folder on a drive letter, as `C:\dir` or `\\?\C:\dir`
fn junction_record(target: &Path) -> io::Result<Vec<u8>> {
    // `\\?\`
    const VERBATIM: [u16; 4] = [0x5c, 0x5c, 0x3f, 0x5c];
    // A junction names a full path with backslashes only
    let wide: Vec<u16> = std::path::absolute(target)?
        .as_os_str()
        .encode_wide()
        .collect();
    let dos = wide.strip_prefix(VERBATIM.as_slice()).unwrap_or(&wide);
    let drive = |letter: u16| u8::try_from(letter).is_ok_and(|l| l.is_ascii_alphabetic());
    if !matches!(dos, [letter, 0x3a, 0x5c, ..] if drive(*letter)) {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "junction target is not on a drive letter",
        ));
    }
    win32::mount_point_record(dos)
}

fn clone_reparse_point(
    src: &Path,
    dst: &Path,
    meta: &fs::Metadata,
    links: &Links,
) -> io::Result<()> {
    let data = read_reparse_data(src)?;
    match reparse_tag(&data) {
        IO_REPARSE_TAG_MOUNT_POINT if !win32::is_volume_mount(&data)? => {
            // A junction is not a directory symlink, and its absolute target would lead the copy
            // back into the source. A new record points at the target's place in the copy
            let record = junction_record(&links.retarget(src)?)?;
            fs::create_dir(dst)?;
            let result = reparse_options()
                .write(true)
                .open(dst)
                .and_then(|file| win32::set_reparse_data(&file, &record));
            if result.is_err() {
                let _ = fs::remove_dir(dst);
            }
            result
        }
        IO_REPARSE_TAG_SYMLINK if meta.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 => {
            symlink_dir(fs::read_link(src)?, dst)
        }
        IO_REPARSE_TAG_SYMLINK => symlink_file(fs::read_link(src)?, dst),
        _ => Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "unsupported reparse point",
        )),
    }
}

fn clone_file(src: &Path, dst: &Path) -> io::Result<()> {
    let src = File::options()
        .read(true)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
        .open(src)?;
    let meta = src.metadata()?;
    if !meta.is_file() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "not a regular file",
        ));
    }
    let info = win32::integrity(&src)?;
    let cluster = cluster_size(&info)?;
    let file = File::create_new(dst)?;
    let result = clone_file_data(&src, &file, &meta, &info, cluster);
    drop(file);
    if result.is_err() {
        let _ = fs::remove_file(dst);
    }
    result
}

fn clone_file_data(
    src: &File,
    dst: &File,
    meta: &fs::Metadata,
    info: &IntegrityInformation,
    cluster: u64,
) -> io::Result<()> {
    // The destination may have inherited a different integrity setting from its parent,
    // so set it while the destination is still empty, including for zero-length files
    win32::set_integrity(dst, info.algorithm, info.flags)?;
    let attributes = meta.file_attributes();
    if attributes & FILE_ATTRIBUTE_SPARSE_FILE != 0 {
        win32::set_sparse(dst)?;
    }
    let len = meta.len();
    if len != 0 {
        // Include the cluster containing EOF. The destination must span the whole range before
        // cloning, and truncating back to the original size can make the last cluster private
        let aligned = len.next_multiple_of(cluster);
        dst.set_len(aligned)?;
        duplicate_extents(src, dst, aligned, cluster)?;
        if len != aligned {
            dst.set_len(len)?;
        }
    }
    dst.set_modified(meta.modified()?)?;
    win32::set_attributes(dst, attributes & BASIC_ATTRIBUTES)
}

fn duplicate_extents(src: &File, dst: &File, len: u64, cluster: u64) -> io::Result<()> {
    // Each request must be cluster-aligned and strictly smaller than 4 GiB
    let max_chunk = (CLONE_LIMIT - 1) / cluster * cluster;
    let offset = |n| i64::try_from(n).map_err(io::Error::other);
    let mut start = 0;
    while start < len {
        let size = (len - start).min(max_chunk);
        win32::duplicate_extents(src, dst, offset(start)?, offset(size)?)?;
        start += size;
    }
    Ok(())
}

#[cfg(test)]
#[expect(
    clippy::panic_in_result_fn,
    reason = "tests propagate I/O errors and assert clone invariants"
)]
mod tests {
    use super::*;
    use crate::{can_clone, remove_any};
    use std::env;
    use std::io::{Read, Seek, SeekFrom, Write};
    use std::process::Command;
    use tempfile::{TempDir, tempdir};

    fn clone_scratch() -> io::Result<Option<TempDir>> {
        let temp = tempdir()?;
        let supported = can_clone(temp.path(), temp.path());
        if env::var("GIT_COW_EXPECT_CLONE").as_deref() == Ok("1") && !supported {
            return Err(io::Error::other(format!(
                "GIT_COW_EXPECT_CLONE=1 but block cloning is unavailable in {}",
                temp.path().display()
            )));
        }
        Ok(supported.then_some(temp))
    }

    #[test]
    fn aligns_to_clusters_not_checksum_chunks() -> io::Result<()> {
        let info = IntegrityInformation {
            checksum_chunk_size: 4096,
            cluster_size: 65_536,
            ..IntegrityInformation::default()
        };
        assert_eq!(cluster_size(&info)?, 65_536);
        Ok(())
    }

    #[test]
    fn clones_nested_files_and_isolates_writes() -> io::Result<()> {
        let Some(temp) = clone_scratch()? else {
            return Ok(());
        };
        let src = temp.path().join("src");
        let dst = temp.path().join("dst");
        fs::create_dir_all(src.join("nested"))?;
        fs::create_dir(&dst)?;
        let probe = File::create_new(temp.path().join("probe"))?;
        let info = win32::integrity(&probe)?;
        let cluster = usize::try_from(cluster_size(&info)?).map_err(io::Error::other)?;
        for len in [0, 1, cluster, cluster + 31] {
            fs::write(src.join("nested").join(len.to_string()), vec![7; len])?;
        }
        clone_into(&src, &dst)?;
        for len in [0, 1, cluster, cluster + 31] {
            let src = src.join("nested").join(len.to_string());
            let dst = dst.join("src/nested").join(len.to_string());
            assert_eq!(fs::read(&dst)?, vec![7; len]);
            assert_eq!(
                fs::metadata(&src)?.modified()?,
                fs::metadata(&dst)?.modified()?
            );
            File::options().write(true).open(dst)?.write_all(b"x")?;
            assert_eq!(fs::read(src)?, vec![7; len]);
        }
        Ok(())
    }

    #[test]
    fn clones_sparse_files_larger_than_one_request() -> io::Result<()> {
        let Some(temp) = clone_scratch()? else {
            return Ok(());
        };
        let src = temp.path().join("sparse");
        let dst = temp.path().join("dst");
        fs::create_dir(&dst)?;
        let mut file = File::create_new(&src)?;
        win32::set_sparse(&file)?;
        file.write_all(b"abc")?;
        file.seek(SeekFrom::Start(CLONE_LIMIT))?;
        file.write_all(b"xyz")?;
        drop(file);

        clone_into(&src, &dst)?;
        let mut cloned = File::open(dst.join("sparse"))?;
        let meta = cloned.metadata()?;
        assert_eq!(meta.len(), CLONE_LIMIT + 3);
        assert_ne!(meta.file_attributes() & FILE_ATTRIBUTE_SPARSE_FILE, 0);
        let mut buf = [0; 3];
        for (offset, expected) in [
            (0, b"abc"),
            (CLONE_LIMIT / 2, b"\0\0\0"),
            (CLONE_LIMIT, b"xyz"),
        ] {
            cloned.seek(SeekFrom::Start(offset))?;
            cloned.read_exact(&mut buf)?;
            assert_eq!(&buf, expected);
        }
        Ok(())
    }

    #[test]
    fn preserves_integrity_when_parent_defaults_differ() -> io::Result<()> {
        const NONE: u16 = 0;
        const CRC64: u16 = 2;
        const ENFORCEMENT_OFF: u32 = 1;
        let Some(temp) = clone_scratch()? else {
            return Ok(());
        };
        for (source, inherited, flags) in [
            (NONE, CRC64, 0),
            (CRC64, NONE, 0),
            (CRC64, NONE, ENFORCEMENT_OFF),
        ] {
            let dst = temp.path().join(format!("dst-{inherited}-{flags}"));
            fs::create_dir(&dst)?;
            let dir = reparse_options().read(true).write(true).open(&dst)?;
            win32::set_integrity(&dir, inherited, 0).expect("set destination directory default");
            drop(dir);
            let check = File::create_new(dst.join("inherits"))?;
            assert_eq!(win32::integrity(&check)?.algorithm != 0, inherited != NONE);
            drop(check);
            for payload in [b"data".as_slice(), b"".as_slice()] {
                let name = format!("source-{source}-{flags}-{}", payload.len());
                let src = temp.path().join(&name);
                let mut f = File::create_new(&src)?;
                win32::set_integrity(&f, source, flags).expect("set source file integrity");
                if !payload.is_empty() {
                    f.write_all(payload)?;
                }
                drop(f);
                let expected = win32::integrity(&File::open(&src)?)?;
                assert_eq!(expected.algorithm != 0, source != NONE);
                assert_eq!(expected.flags & ENFORCEMENT_OFF, flags);
                clone_into(&src, &dst)?;
                let actual = win32::integrity(&File::open(dst.join(&name))?)?;
                assert_eq!(
                    (actual.algorithm, actual.flags),
                    (expected.algorithm, expected.flags)
                );
                assert_eq!(fs::read(dst.join(&name))?, payload);
            }
        }
        Ok(())
    }

    #[test]
    fn preserves_basic_attributes_and_allows_cleanup() -> io::Result<()> {
        let Some(temp) = clone_scratch()? else {
            return Ok(());
        };
        let dst = temp.path().join("dst");
        fs::create_dir(&dst)?;
        for attrs in [0, BASIC_ATTRIBUTES] {
            let name = format!("source-{attrs}");
            let src = temp.path().join(&name);
            let mut file = File::create_new(&src)?;
            file.write_all(b"contents")?;
            win32::set_attributes(&file, attrs)?;
            drop(file);
            assert_eq!(
                fs::metadata(&src)?.file_attributes() & BASIC_ATTRIBUTES,
                attrs
            );
            clone_into(&src, &dst)?;
            let cloned = dst.join(&name);
            assert_eq!(
                fs::metadata(&cloned)?.file_attributes() & BASIC_ATTRIBUTES,
                attrs
            );
            assert_eq!(fs::read(cloned)?, b"contents");
        }
        temp.close()
    }

    // mklink is independent of our implementation and needs no symlink privilege for /J
    fn junction(link: &Path, target: &Path) -> io::Result<()> {
        let result = Command::new("cmd.exe")
            .args(["/D", "/C", "mklink", "/J"])
            .args([std::path::absolute(link)?, std::path::absolute(target)?])
            .output()?;
        assert!(
            result.status.success(),
            "mklink failed: {}",
            String::from_utf8_lossy(&result.stderr)
        );
        Ok(())
    }

    #[test]
    fn writes_the_junction_record_mklink_writes() -> io::Result<()> {
        let temp = tempdir()?;
        let target = temp.path().join("target");
        let link = temp.path().join("link");
        fs::create_dir(&target)?;
        junction(&link, &target)?;
        assert_eq!(read_reparse_data(&link)?, junction_record(&target)?);
        assert_eq!(
            junction_record(Path::new(r"\\?\C:\dir"))?,
            junction_record(Path::new(r"C:\dir"))?
        );
        assert_eq!(
            junction_record(Path::new("C:/a/b"))?,
            junction_record(Path::new(r"C:\a\b"))?
        );
        let unc = junction_record(Path::new(r"\\server\share\dir"))
            .expect_err("a junction cannot point at a share");
        assert_eq!(unc.kind(), io::ErrorKind::Unsupported);
        temp.close()
    }

    #[test]
    fn retargets_junctions_inside_the_clone() -> io::Result<()> {
        let temp = tempdir()?;
        let src = temp.path().join("src");
        let dst = temp.path().join("dst");
        fs::create_dir_all(src.join("store/pkg"))?;
        fs::create_dir(src.join("deps"))?;
        fs::create_dir(&dst)?;
        // pnpm links each package to its folder in the store with an absolute junction
        junction(&src.join("deps/pkg"), &src.join("store/pkg"))?;
        junction(&src.join("deps/root"), &src)?;
        clone_into(&src, &dst)?;
        let copy = dst.join("src");
        for (link, target) in [
            ("deps/pkg", copy.join("store/pkg")),
            ("deps/root", copy.clone()),
        ] {
            let cloned = copy.join(link);
            assert_eq!(read_reparse_data(&cloned)?, junction_record(&target)?);
            assert_eq!(fs::canonicalize(&cloned)?, fs::canonicalize(&target)?);
        }

        // A tree cloned aside points at the place it moves to, not at the staging folder. Inside
        // what moves, the target need not be there yet, elsewhere it must
        fs::create_dir(src.join("deps/inner"))?;
        junction(&src.join("deps/own"), &src.join("deps/inner"))?;
        let staging = temp.path().join("staging");
        let moved = temp.path().join("moved");
        fs::create_dir(&staging)?;
        fs::create_dir_all(moved.join("store/pkg"))?;
        clone_moved(&src.join("deps"), &staging, &src, &moved)?;
        for (link, target) in [
            ("deps/pkg", moved.join("store/pkg")),
            ("deps/root", moved.clone()),
            ("deps/own", moved.join("deps/inner")),
        ] {
            assert_eq!(
                read_reparse_data(&staging.join(link))?,
                junction_record(&target)?
            );
        }

        remove_any(&dst);
        remove_any(&staging);
        assert!(!dst.exists() && !staging.exists());
        assert!(src.join("store/pkg").is_dir());
        temp.close()
    }

    #[test]
    fn refuses_junctions_out_of_the_clone() -> io::Result<()> {
        let temp = tempdir()?;
        let outside = temp.path().join("outside");
        fs::create_dir(&outside)?;
        fs::write(outside.join("keep"), b"outside the cloned tree")?;
        let out = temp.path().join("out");
        fs::create_dir(&out)?;
        junction(&out.join("link"), &outside)?;
        // Inside by name, but the folder it names leads out through another junction
        let hop = temp.path().join("hop");
        fs::create_dir(&hop)?;
        junction(&hop.join("a"), &outside)?;
        junction(&hop.join("b"), &hop.join("a"))?;
        // Inside, but gone, so where it would lead cannot be checked
        let dangling = temp.path().join("dangling");
        fs::create_dir_all(dangling.join("gone"))?;
        junction(&dangling.join("link"), &dangling.join("gone"))?;
        fs::remove_dir(dangling.join("gone"))?;

        for (src, from) in [(&out, &out), (&hop.join("b"), &hop), (&dangling, &dangling)] {
            let dst = temp.path().join("dst");
            fs::create_dir(&dst)?;
            let err = clone_moved(src, &dst, from, &dst).expect_err("junction leads outside");
            assert_eq!(err.kind(), io::ErrorKind::Unsupported, "{err}");
            remove_any(&dst);
            assert!(!dst.exists());
        }

        // A tree cloned aside that links elsewhere in its source needs that place in the
        // destination to exist and to stay inside it
        let src = temp.path().join("src");
        fs::create_dir_all(src.join("store/pkg"))?;
        fs::create_dir(src.join("deps"))?;
        junction(&src.join("deps/pkg"), &src.join("store/pkg"))?;
        fs::create_dir(outside.join("pkg"))?;
        let missing = temp.path().join("missing");
        let escaping = temp.path().join("escaping");
        fs::create_dir(&missing)?;
        fs::create_dir(&escaping)?;
        junction(&escaping.join("store"), &outside)?;
        for to in [&missing, &escaping] {
            let staging = temp.path().join("staging");
            fs::create_dir(&staging)?;
            let err = clone_moved(&src.join("deps"), &staging, &src, to)
                .expect_err("junction target is not safely in the destination");
            assert_eq!(err.kind(), io::ErrorKind::Unsupported, "{err}");
            remove_any(&staging);
        }
        assert_eq!(fs::read(outside.join("keep"))?, b"outside the cloned tree");
        temp.close()
    }

    #[test]
    fn distinguishes_mounted_volumes_from_junctions() -> io::Result<()> {
        let root = r"\??\Volume{26a21bda-a627-11d7-9931-806e6f6e6963}\";
        for (name, mounted) in [(root.to_owned(), true), (format!("{root}dir"), false)] {
            let name: Vec<u8> = name.encode_utf16().flat_map(u16::to_le_bytes).collect();
            let mut record = vec![0; 16];
            let len = u16::try_from(name.len()).expect("short substitute name");
            record[10..12].copy_from_slice(&len.to_le_bytes());
            record.extend(name);
            assert_eq!(win32::is_volume_mount(&record)?, mounted);
        }
        Ok(())
    }

    #[test]
    fn recreates_relative_dangling_symlinks() -> io::Result<()> {
        const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;
        let temp = tempdir()?;
        let dst = temp.path().join("dst");
        fs::create_dir(&dst)?;
        let target = Path::new("missing");
        for (name, directory) in [("file", false), ("dir", true)] {
            let src = temp.path().join(name);
            let created = if directory {
                symlink_dir(target, &src)
            } else {
                symlink_file(target, &src)
            };
            match created {
                Err(e) if e.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD) => return Ok(()),
                result => result?,
            }
            clone_into(&src, &dst)?;
            let cloned = dst.join(name);
            assert_eq!(
                reparse_tag(&read_reparse_data(&cloned)?),
                IO_REPARSE_TAG_SYMLINK
            );
            assert_eq!(fs::read_link(&cloned)?, target);
            remove_any(&cloned);
            assert_eq!(
                cloned
                    .symlink_metadata()
                    .expect_err("dangling link is gone")
                    .kind(),
                io::ErrorKind::NotFound
            );
        }
        temp.close()
    }
}