mise-util 2026.11.14

Environment, directory, and filesystem helpers shared by mise's crates
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
use super::*;

#[test]
fn in_linked_worktree_requires_real_worktree_metadata() {
    let tmp = tempfile::tempdir().unwrap();
    let base = tmp.path().canonicalize().unwrap();

    // A real linked worktree, and a nested path inside it.
    let main = base.join("main");
    let wt = base.join("wt");
    std::fs::create_dir_all(main.join(".git/worktrees/wt")).unwrap();
    std::fs::create_dir_all(wt.join("packages/api")).unwrap();
    std::fs::write(main.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(main.join(".git/worktrees/wt/commondir"), "../..\n").unwrap();
    // git writes HEAD into the private dir as well, which is what a
    // submodule inside this worktree is anchored against below.
    std::fs::write(
        main.join(".git/worktrees/wt/HEAD"),
        "ref: refs/heads/main\n",
    )
    .unwrap();
    std::fs::write(
        wt.join(".git"),
        format!("gitdir: {}\n", main.join(".git/worktrees/wt").display()),
    )
    .unwrap();
    assert!(super::in_linked_worktree(&wt));
    assert!(super::in_linked_worktree(&wt.join("packages/api")));
    assert!(!super::in_linked_worktree(&main));
    assert!(!super::in_linked_worktree(&base));

    // A worktree of a bare repository still counts: it has no main checkout
    // to map onto, but it is a separate working copy.
    let bare = base.join("bare.git");
    let bare_wt = base.join("bare-wt");
    std::fs::create_dir_all(bare.join("worktrees/bare-wt")).unwrap();
    std::fs::create_dir_all(&bare_wt).unwrap();
    std::fs::write(bare.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(bare.join("worktrees/bare-wt/commondir"), "../..\n").unwrap();
    std::fs::write(
        bare_wt.join(".git"),
        format!("gitdir: {}\n", bare.join("worktrees/bare-wt").display()),
    )
    .unwrap();
    assert!(super::in_linked_worktree(&bare_wt));

    // `git clone --separate-git-dir` whose git dir happens to sit directly
    // under a directory named `worktrees`. The directory exists and is a
    // real git dir, so only the absence of `commondir` distinguishes it;
    // misreading it would move a single checkout off its base port.
    let sep = base.join("sep-checkout");
    let sep_git = base.join("worktrees/sep.git");
    std::fs::create_dir_all(sep_git.join("refs")).unwrap();
    std::fs::create_dir_all(&sep).unwrap();
    std::fs::write(sep_git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(sep_git.join("config"), "[core]\n").unwrap();
    std::fs::write(sep.join(".git"), format!("gitdir: {}\n", sep_git.display())).unwrap();
    assert!(!super::in_linked_worktree(&sep));

    // A hand-made private dir under `worktrees/` whose `commondir` names
    // nothing real. The file exists, so only resolving it rejects this.
    let forged = base.join("forged");
    let forged_git = base.join("fake/worktrees/forged");
    std::fs::create_dir_all(&forged_git).unwrap();
    std::fs::create_dir_all(&forged).unwrap();
    std::fs::write(forged_git.join("commondir"), "../../nonexistent\n").unwrap();
    std::fs::write(
        forged.join(".git"),
        format!("gitdir: {}\n", forged_git.display()),
    )
    .unwrap();
    assert!(!super::in_linked_worktree(&forged));

    // Pointing it at a real repository elsewhere is still not a worktree:
    // the pointer must lead back to the dir the private dir sits under, so
    // borrowing an unrelated repo's metadata confers nothing.
    std::fs::create_dir_all(base.join("fake/other-repo")).unwrap();
    std::fs::write(base.join("fake/other-repo/HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(forged_git.join("commondir"), "../../other-repo\n").unwrap();
    assert!(!super::in_linked_worktree(&forged));

    // Correct target, but no git metadata there yet.
    std::fs::write(forged_git.join("commondir"), "../..\n").unwrap();
    assert!(!super::in_linked_worktree(&forged));

    // Both conditions met is what finally makes it a worktree.
    std::fs::write(base.join("fake/HEAD"), "ref: refs/heads/main\n").unwrap();
    assert!(super::in_linked_worktree(&forged));

    // A submodule points under `modules/`, and a pruned worktree marker
    // names a directory that no longer exists.
    let sub = base.join("sub");
    std::fs::create_dir_all(&sub).unwrap();
    std::fs::write(
        sub.join(".git"),
        format!("gitdir: {}\n", main.join(".git/modules/sub").display()),
    )
    .unwrap();
    assert!(!super::in_linked_worktree(&sub));
    let pruned = base.join("pruned");
    std::fs::create_dir_all(&pruned).unwrap();
    std::fs::write(
        pruned.join(".git"),
        format!("gitdir: {}\n", main.join(".git/worktrees/gone").display()),
    )
    .unwrap();
    assert!(!super::in_linked_worktree(&pruned));

    // A submodule inside a linked worktree is still inside it. The same
    // submodule in two worktrees is two working copies, so the walk must
    // continue past its marker rather than calling it a primary checkout.
    let wt_sub = wt.join("sub");
    std::fs::create_dir_all(&wt_sub).unwrap();
    std::fs::write(
        wt_sub.join(".git"),
        format!(
            "gitdir: {}\n",
            main.join(".git/worktrees/wt/modules/sub").display()
        ),
    )
    .unwrap();
    // The marker names a git dir that does not exist yet, which says
    // nothing about what encloses this directory.
    assert!(!super::in_linked_worktree(&wt_sub));
    std::fs::create_dir_all(main.join(".git/worktrees/wt/modules/sub")).unwrap();
    assert!(super::in_linked_worktree(&wt_sub));

    // A submodule whose own path is `modules/foo` nests the component:
    // git stores it at `<enclosing>/modules/modules/foo`. The container
    // `.git/modules` has no HEAD, so only looking past it finds the real
    // enclosing git dir.
    let nested_name = wt.join("modules/foo");
    std::fs::create_dir_all(&nested_name).unwrap();
    std::fs::create_dir_all(main.join(".git/worktrees/wt/modules/modules/foo")).unwrap();
    std::fs::write(
        nested_name.join(".git"),
        format!(
            "gitdir: {}\n",
            main.join(".git/worktrees/wt/modules/modules/foo").display()
        ),
    )
    .unwrap();
    assert!(super::in_linked_worktree(&nested_name));

    // An unrelated repository whose git dir merely sits under a directory
    // named `modules` is not a submodule: the path before `modules` is not
    // a git dir, so it must not inherit the worktree's offset.
    let lookalike = wt.join("lookalike");
    let lookalike_git = base.join("plain/modules/repo");
    std::fs::create_dir_all(&lookalike_git).unwrap();
    std::fs::create_dir_all(&lookalike).unwrap();
    std::fs::write(lookalike_git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(
        lookalike.join(".git"),
        format!("gitdir: {}\n", lookalike_git.display()),
    )
    .unwrap();
    assert!(!super::in_linked_worktree(&lookalike));

    // Give the path before `modules` git metadata and it becomes a real
    // submodule layout, which does follow its worktree.
    std::fs::write(base.join("plain/HEAD"), "ref: refs/heads/main\n").unwrap();
    assert!(super::in_linked_worktree(&lookalike));

    // An independent repository nested in a worktree is its own single
    // copy, so it stops the walk like a nested `.git` directory would.
    let nested = wt.join("vendored");
    let nested_git = base.join("vendored-git");
    std::fs::create_dir_all(&nested).unwrap();
    std::fs::create_dir_all(&nested_git).unwrap();
    std::fs::write(nested_git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(
        nested.join(".git"),
        format!("gitdir: {}\n", nested_git.display()),
    )
    .unwrap();
    assert!(!super::in_linked_worktree(&nested));
}

#[test]
fn worktree_main_checkout_equivalent() {
    let tmp = tempfile::tempdir().unwrap();
    let base = tmp.path().canonicalize().unwrap();
    let main = base.join("main");
    let wt = base.join("wt");
    std::fs::create_dir_all(main.join(".git/worktrees/wt")).unwrap();
    std::fs::create_dir_all(wt.join("sub")).unwrap();
    std::fs::write(main.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(main.join(".git/worktrees/wt/commondir"), "../..\n").unwrap();
    std::fs::write(
        main.join(".git/worktrees/wt/gitdir"),
        format!("{}\n", wt.join(".git").display()),
    )
    .unwrap();
    std::fs::write(
        wt.join(".git"),
        format!("gitdir: {}\n", main.join(".git/worktrees/wt").display()),
    )
    .unwrap();

    // worktree root and nested paths map to the main checkout
    assert_eq!(super::main_checkout_equivalent(&wt), Some(main.clone()));
    assert_eq!(
        super::main_checkout_equivalent(&wt.join("sub/mise.toml")),
        Some(main.join("sub/mise.toml"))
    );

    // a directory that merely names the same entry is not that worktree: the
    // entry points back at `wt`, so neither an unrelated directory nor one
    // nested in the main checkout inherits anything
    for claimed in [base.join("claimed"), main.join("vendor/claimed")] {
        std::fs::create_dir_all(&claimed).unwrap();
        std::fs::write(
            claimed.join(".git"),
            format!("gitdir: {}\n", main.join(".git/worktrees/wt").display()),
        )
        .unwrap();
        assert_eq!(super::main_checkout_equivalent(&claimed), None);
    }
    // nor is one whose `.git` is a symlink to the real worktree's
    #[cfg(unix)]
    {
        let linked = base.join("linked");
        std::fs::create_dir_all(&linked).unwrap();
        std::os::unix::fs::symlink(wt.join(".git"), linked.join(".git")).unwrap();
        assert_eq!(super::main_checkout_equivalent(&linked), None);
    }

    // `worktree.useRelativePaths` writes both pointers relative to their files
    let rel = base.join("rel");
    std::fs::create_dir_all(main.join(".git/worktrees/rel")).unwrap();
    std::fs::create_dir_all(&rel).unwrap();
    std::fs::write(main.join(".git/worktrees/rel/commondir"), "../..\n").unwrap();
    std::fs::write(
        main.join(".git/worktrees/rel/gitdir"),
        "../../../../rel/.git\n",
    )
    .unwrap();
    std::fs::write(rel.join(".git"), "gitdir: ../main/.git/worktrees/rel\n").unwrap();
    assert_eq!(super::main_checkout_equivalent(&rel), Some(main.clone()));

    // main checkout and non-repo paths do not map
    assert_eq!(super::main_checkout_equivalent(&main), None);
    assert_eq!(super::main_checkout_equivalent(&base), None);

    // worktree of a bare repo does not map
    let bare = base.join("bare.git");
    let bare_wt = base.join("bare-wt");
    std::fs::create_dir_all(bare.join("worktrees/bare-wt")).unwrap();
    std::fs::create_dir_all(&bare_wt).unwrap();
    std::fs::write(bare.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(bare.join("worktrees/bare-wt/commondir"), "../..\n").unwrap();
    std::fs::write(
        bare_wt.join(".git"),
        format!("gitdir: {}\n", bare.join("worktrees/bare-wt").display()),
    )
    .unwrap();
    assert_eq!(super::main_checkout_equivalent(&bare_wt), None);

    // a submodule also uses a `.git` file but is not a linked worktree:
    // its configs must not inherit the parent checkout's trust
    let subm = main.join("subm");
    std::fs::create_dir_all(main.join(".git/modules/subm")).unwrap();
    std::fs::create_dir_all(&subm).unwrap();
    std::fs::write(
        subm.join(".git"),
        format!("gitdir: {}\n", main.join(".git/modules/subm").display()),
    )
    .unwrap();
    assert_eq!(super::main_checkout_equivalent(&subm), None);
    assert_eq!(
        super::main_checkout_equivalent(&subm.join("mise.toml")),
        None
    );

    // a submodule checked out inside a linked worktree maps through the
    // outer worktree to the same submodule path in the main checkout
    let wt_subm = wt.join("subm");
    std::fs::create_dir_all(&wt_subm).unwrap();
    std::fs::write(
        wt_subm.join(".git"),
        format!("gitdir: {}\n", main.join(".git/modules/subm").display()),
    )
    .unwrap();
    assert_eq!(
        super::main_checkout_equivalent(&wt_subm.join("mise.toml")),
        Some(subm.join("mise.toml"))
    );
}

#[cfg(unix)]
#[test]
fn worktree_main_checkout_equivalent_rejects_symlinks() {
    let tmp = tempfile::tempdir().unwrap();
    let base = tmp.path().canonicalize().unwrap();
    let main = base.join("main");
    let wt = base.join("wt");
    let elsewhere = base.join("elsewhere");
    std::fs::create_dir_all(main.join(".git/worktrees/wt")).unwrap();
    std::fs::create_dir_all(wt.join("sub")).unwrap();
    std::fs::create_dir_all(&elsewhere).unwrap();
    std::fs::write(main.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(main.join(".git/worktrees/wt/commondir"), "../..\n").unwrap();
    // the forged checkout is the attacker's own, so it registers the worktree
    std::fs::write(
        main.join(".git/worktrees/wt/gitdir"),
        format!("{}\n", wt.join(".git").display()),
    )
    .unwrap();
    std::fs::write(
        wt.join(".git"),
        format!("gitdir: {}\n", main.join(".git/worktrees/wt").display()),
    )
    .unwrap();
    std::fs::write(elsewhere.join("mise.toml"), "").unwrap();
    std::fs::write(wt.join("mise.toml"), "").unwrap();

    // the main checkout's counterpart is a link to a file outside it
    std::os::unix::fs::symlink(elsewhere.join("mise.toml"), main.join("mise.toml")).unwrap();
    assert_eq!(super::main_checkout_equivalent(&wt.join("mise.toml")), None);

    // so is a directory on the way to it
    std::os::unix::fs::symlink(&elsewhere, main.join("sub")).unwrap();
    assert_eq!(
        super::main_checkout_equivalent(&wt.join("sub/mise.toml")),
        None
    );

    // a link back to the worktree's own file must not map onto itself
    std::fs::remove_file(main.join("mise.toml")).unwrap();
    std::os::unix::fs::symlink(wt.join("mise.toml"), main.join("mise.toml")).unwrap();
    assert_eq!(super::main_checkout_equivalent(&wt.join("mise.toml")), None);

    // a regular file in the main checkout still maps
    std::fs::remove_file(main.join("mise.toml")).unwrap();
    std::fs::write(main.join("mise.toml"), "").unwrap();
    assert_eq!(
        super::main_checkout_equivalent(&wt.join("mise.toml")),
        Some(main.join("mise.toml"))
    );
}

#[test]
fn git_commands_ignore_inherited_work_tree() {
    let tmp = tempfile::tempdir().unwrap();
    let src = tmp.path().join("src");
    let cache = tmp.path().join("cache");
    let work_tree = tmp.path().join("work-tree");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::create_dir_all(&work_tree).unwrap();

    let git_in = |dir: &std::path::Path, args: &[&str]| {
        let out = Command::new("git")
            .args(args)
            .current_dir(dir)
            .output()
            .expect("spawn git");
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        out
    };
    git_in(&src, &["-c", "init.defaultBranch=main", "init", "-q"]);
    std::fs::write(src.join("file.txt"), "hello\n").unwrap();
    git_in(&src, &["add", "file.txt"]);
    git_in(
        &src,
        &[
            "-c",
            "user.email=t@t",
            "-c",
            "user.name=t",
            "commit",
            "-q",
            "-m",
            "main",
        ],
    );
    let url = format!("file://{}", src.display());
    let clone = Command::new("git")
        .args(["clone", "-q", &url])
        .arg(&cache)
        .output()
        .expect("spawn git clone");
    assert!(
        clone.status.success(),
        "git clone failed: {}",
        String::from_utf8_lossy(&clone.stderr)
    );
    std::fs::remove_file(cache.join("file.txt")).unwrap();

    let output = sanitize_git_env(
        git_cmd!(&cache, "checkout", "--force", "HEAD")
            .env("GIT_WORK_TREE", &work_tree)
            .env("GIT_INDEX_FILE", work_tree.join("index")),
    )
    .stderr_to_stdout()
    .stdout_capture()
    .unchecked()
    .run()
    .expect("run git checkout");
    assert!(
        output.status.success(),
        "git checkout failed: {}",
        String::from_utf8_lossy(&output.stdout)
    );

    assert!(cache.join("file.txt").exists());
    assert!(!work_tree.join("file.txt").exists());
    assert!(!work_tree.join("index").exists());

    let clone_cache = tmp.path().join("clone-cache");
    sanitize_git_cmd_runner(
        CmdLineRunner::new("git")
            .arg("clone")
            .arg("-q")
            .arg(&url)
            .arg(&clone_cache)
            .env("GIT_WORK_TREE", &work_tree),
    )
    .execute()
    .expect("git clone should ignore inherited GIT_WORK_TREE");

    assert!(clone_cache.join("file.txt").exists());
    assert!(!work_tree.join("file.txt").exists());
}

/// A `.git` pointer file in an unpacked archive can lead to a `commondir`
/// that is a pipe, which an unbounded read would wait on forever.
#[cfg(unix)]
#[test]
fn worktree_detection_skips_a_commondir_that_is_a_pipe() {
    let tmp = tempfile::tempdir().unwrap();
    let base = tmp.path().canonicalize().unwrap();
    let checkout = base.join("proj");
    let private = checkout.join("g/worktrees/x");
    std::fs::create_dir_all(&private).unwrap();
    std::fs::write(checkout.join(".git"), "gitdir: g/worktrees/x\n").unwrap();
    nix::unistd::mkfifo(
        &private.join("commondir"),
        nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
    )
    .unwrap();

    let (tx, rx) = std::sync::mpsc::channel();
    let probe = checkout.clone();
    std::thread::spawn(move || {
        let _ = tx.send(super::in_linked_worktree(&probe));
    });
    let linked = rx
        .recv_timeout(std::time::Duration::from_secs(10))
        .expect("worktree detection blocked on a commondir pipe");
    assert!(!linked);
}

/// The worktree entry's `gitdir` pointer is read while trust is resolved, and
/// a pipe there must not block it.
#[cfg(unix)]
#[test]
fn main_checkout_equivalent_skips_a_gitdir_pointer_that_is_a_pipe() {
    let tmp = tempfile::tempdir().unwrap();
    let base = tmp.path().canonicalize().unwrap();
    let main = base.join("main");
    let wt = base.join("wt");
    std::fs::create_dir_all(main.join(".git/worktrees/wt")).unwrap();
    std::fs::create_dir_all(&wt).unwrap();
    std::fs::write(main.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(main.join(".git/worktrees/wt/commondir"), "../..\n").unwrap();
    nix::unistd::mkfifo(
        &main.join(".git/worktrees/wt/gitdir"),
        nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
    )
    .unwrap();
    std::fs::write(
        wt.join(".git"),
        format!("gitdir: {}\n", main.join(".git/worktrees/wt").display()),
    )
    .unwrap();

    let (tx, rx) = std::sync::mpsc::channel();
    let probe = wt.clone();
    std::thread::spawn(move || {
        let _ = tx.send(super::main_checkout_equivalent(&probe));
    });
    let equivalent = rx
        .recv_timeout(std::time::Duration::from_millis(500))
        .expect("worktree trust blocked on a gitdir pipe");
    assert_eq!(equivalent, None);
}