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
use super::*;
use crate::cmd::CmdLineRunner;
use std::process::Command;

#[test]
fn sha_detection() {
    assert!(looks_like_sha("0123456789abcdef0123456789abcdef01234567"));
    assert!(looks_like_sha(
        "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
    ));
    assert!(!looks_like_sha("main"));
    assert!(!looks_like_sha("v1.2.3"));
    assert!(!looks_like_sha("abcdef1")); // short SHA not supported
    assert!(!looks_like_sha(""));
    assert!(!looks_like_sha("g123456789abcdef0123456789abcdef01234567")); // non-hex
}

#[test]
fn abbreviated_sha_detection() {
    assert!(super::looks_like_abbreviated_sha("1f22e02"));
    assert!(super::looks_like_abbreviated_sha(
        "1f22e025e8c0d77ee3176102"
    ));
    assert!(!super::looks_like_abbreviated_sha("cafe")); // too short to be a git abbreviation
    assert!(!super::looks_like_abbreviated_sha("main"));
    assert!(!super::looks_like_abbreviated_sha("v1.2.3"));
    assert!(!super::looks_like_abbreviated_sha(
        "1f22e025e8c0d77ee3176102c26a3fd6fd770cb5"
    ));
}

#[test]
fn remote_ref_parser_prefers_branches_over_tags() {
    let output = "\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\trefs/heads/release
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\trefs/tags/release
";
    assert_eq!(
        super::remote_ref_kind(output, "refs/heads/release", "refs/tags/release"),
        Some(super::RemoteRefKind::Branch)
    );
    assert_eq!(
        super::remote_ref_kind(output, "refs/heads/missing", "refs/tags/release"),
        Some(super::RemoteRefKind::Tag)
    );
    assert_eq!(
        super::remote_ref_kind(output, "refs/heads/missing", "refs/tags/missing"),
        None
    );
}

#[test]
fn reads_files_from_the_merge_base_and_head() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    let git = |args: &[&str]| {
        let output = Command::new("git")
            .args(args)
            .current_dir(root)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8(output.stdout).unwrap().trim().to_string()
    };
    git(&["-c", "init.defaultBranch=main", "init", "-q"]);
    git(&["config", "user.email", "test@example.com"]);
    git(&["config", "user.name", "Test"]);
    std::fs::write(root.join("lockfile"), "before\n").unwrap();
    git(&["add", "lockfile"]);
    git(&["commit", "-q", "-m", "before"]);
    let base = git(&["rev-parse", "HEAD"]);
    std::fs::write(root.join("lockfile"), "after\n").unwrap();
    git(&["commit", "-q", "-am", "after"]);
    let head = git(&["rev-parse", "HEAD"]);

    let repo = Git::new(root);
    assert_eq!(repo.merge_base(&base, &head).unwrap(), base);
    assert_eq!(
        repo.file_at_revision(&base, std::path::Path::new("lockfile"))
            .unwrap()
            .as_deref(),
        Some("before\n")
    );
    assert_eq!(
        repo.file_at_revision(&head, std::path::Path::new("lockfile"))
            .unwrap()
            .as_deref(),
        Some("after\n")
    );
    assert_eq!(
        repo.file_at_revision(&head, std::path::Path::new("missing"))
            .unwrap(),
        None
    );
}

#[test]
fn update_resolves_short_branches_and_tags() {
    let tmp = tempfile::tempdir().unwrap();
    let origin = tmp.path().join("origin");
    std::fs::create_dir_all(&origin).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)
        );
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    };
    git_in(&origin, &["-c", "init.defaultBranch=main", "init", "-q"]);
    git_in(&origin, &["config", "user.email", "test@example.com"]);
    git_in(&origin, &["config", "user.name", "Test"]);
    // A global tag.gpgsign would turn the lightweight tag below into one that needs a message.
    git_in(&origin, &["config", "tag.gpgsign", "false"]);

    std::fs::write(origin.join("version"), "release\n").unwrap();
    git_in(&origin, &["add", "version"]);
    git_in(&origin, &["commit", "-q", "-m", "release"]);
    let release_sha = git_in(&origin, &["rev-parse", "HEAD"]);
    git_in(&origin, &["branch", "release-branch"]);
    git_in(&origin, &["branch", "collision"]);
    git_in(&origin, &["tag", "lightweight-v1"]);
    git_in(
        &origin,
        &["tag", "-a", "annotated-v1", "-m", "annotated-v1"],
    );

    std::fs::write(origin.join("version"), "tag-collision\n").unwrap();
    git_in(&origin, &["commit", "-q", "-am", "tag collision"]);
    let tag_collision_sha = git_in(&origin, &["rev-parse", "HEAD"]);
    git_in(&origin, &["tag", "-a", "collision", "-m", "collision"]);

    std::fs::write(origin.join("version"), "main\n").unwrap();
    git_in(&origin, &["commit", "-q", "-am", "main"]);

    let cases = [
        ("release-branch", release_sha.as_str()),
        ("lightweight-v1", release_sha.as_str()),
        ("annotated-v1", release_sha.as_str()),
        ("refs/tags/annotated-v1", release_sha.as_str()),
        (release_sha.as_str(), release_sha.as_str()),
        ("collision", release_sha.as_str()),
        ("refs/tags/collision", tag_collision_sha.as_str()),
    ];
    let url = format!("file://{}", origin.display());
    for (index, (selector, expected_sha)) in cases.into_iter().enumerate() {
        let clone = tmp.path().join(format!("clone-{index}"));
        git_in(tmp.path(), &["clone", "-q", &url, clone.to_str().unwrap()]);
        if selector == "annotated-v1" {
            // A stale local branch must not override a remote tag after the
            // remote branch has disappeared.
            git_in(&clone, &["branch", "annotated-v1"]);
        }

        Git::new(&clone)
            .update(Some(selector.to_string()))
            .unwrap_or_else(|err| panic!("update {selector} failed: {err:#}"));
        assert_eq!(
            git_in(&clone, &["rev-parse", "HEAD"]),
            expected_sha,
            "selector {selector} checked out the wrong commit"
        );
    }

    let clone = tmp.path().join("clone-update-tag-full-ref");
    git_in(tmp.path(), &["clone", "-q", &url, clone.to_str().unwrap()]);
    Git::new(&clone)
        .update_tag("refs/tags/annotated-v1".to_string())
        .unwrap_or_else(|err| panic!("update_tag with full ref failed: {err:#}"));
    assert_eq!(git_in(&clone, &["rev-parse", "HEAD"]), release_sha);

    // 64 hex digits look like a commit SHA, but here they can only name a ref.
    let sha256_like = "0123456789abcdef".repeat(4);
    git_in(&origin, &["branch", &sha256_like]);
    let clone = tmp.path().join("clone-sha256-like");
    git_in(tmp.path(), &["clone", "-q", &url, clone.to_str().unwrap()]);
    let err = Git::new(&clone)
        .update(Some(sha256_like))
        .expect_err("a branch must not pass for a commit SHA");
    assert!(format!("{err:#}").contains("is not a commit in"));
}

#[test]
fn works_when_the_remote_is_not_named_origin() {
    let tmp = tempfile::tempdir().unwrap();
    let source = tmp.path().join("source");
    std::fs::create_dir_all(&source).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)
        );
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    };
    git_in(&source, &["-c", "init.defaultBranch=main", "init", "-q"]);
    git_in(&source, &["config", "user.email", "test@example.com"]);
    git_in(&source, &["config", "user.name", "Test"]);
    git_in(&source, &["config", "commit.gpgsign", "false"]);
    std::fs::write(source.join("version"), "one\n").unwrap();
    git_in(&source, &["add", "version"]);
    git_in(&source, &["commit", "-q", "-m", "one"]);
    git_in(&source, &["branch", "other"]);

    let url = format!("file://{}", source.display());
    let clone = tmp.path().join("clone");
    git_in(
        tmp.path(),
        &[
            "clone",
            "-q",
            "-o",
            "upstream",
            &url,
            clone.to_str().unwrap(),
        ],
    );
    git_in(&clone, &["config", "user.email", "test@example.com"]);
    git_in(&clone, &["config", "user.name", "Test"]);

    std::fs::write(source.join("version"), "two\n").unwrap();
    git_in(&source, &["commit", "-q", "-am", "two"]);
    let new_sha = git_in(&source, &["rev-parse", "HEAD"]);

    let git = Git::new(&clone);
    assert_eq!(git.get_remote_url().as_deref(), Some(url.as_str()));
    assert_eq!(
        git.remote_sha("main").unwrap().as_deref(),
        Some(new_sha.as_str())
    );
    git.update(None).unwrap();
    assert_eq!(git_in(&clone, &["rev-parse", "HEAD"]), new_sha);
    git.update(Some("other".to_string())).unwrap();
    assert_eq!(
        git_in(&clone, &["rev-parse", "--abbrev-ref", "HEAD"]),
        "other"
    );
}

#[cfg(unix)]
#[test]
fn git_errors_that_are_not_utf8_are_reported() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(&repo).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)
        );
    };
    git_in(&repo, &["-c", "init.defaultBranch=main", "init", "-q"]);

    // git repeats the URL of a remote or submodule it cannot reach byte for
    // byte in its error message, and nothing requires that URL to be UTF-8.
    let mut url = tmp.path().to_str().unwrap().as_bytes().to_vec();
    url.extend(b"/\xff\xfe\xfd.git\n");
    let mut config = std::fs::read(repo.join(".git/config")).unwrap();
    config.extend(b"[remote \"origin\"]\n\turl = ");
    config.extend(&url);
    std::fs::write(repo.join(".git/config"), config).unwrap();
    let mut gitmodules = b"[submodule \"dep\"]\n\tpath = dep\n\turl = ".to_vec();
    gitmodules.extend(&url);
    std::fs::write(repo.join(".gitmodules"), gitmodules).unwrap();
    let gitlink = format!("160000,{},dep", "1".repeat(40));
    git_in(&repo, &["update-index", "--add", "--cacheinfo", &gitlink]);

    let git = Git::new(&repo);
    let err = git.update_tag("v1".to_string()).unwrap_err();
    assert!(format!("{err:#}").contains("\u{fffd}.git"), "{err:#}");
    let err = git.update_submodules().unwrap_err();
    assert!(format!("{err:#}").contains("\u{fffd}.git"), "{err:#}");
}

#[test]
fn ls_remote_args_end_options_before_the_remote() {
    assert_eq!(
        ls_remote_args(&["--tags", "--refs"], "--upload-pack=touch x", &["go*"]),
        [
            "ls-remote",
            "--tags",
            "--refs",
            "--",
            "--upload-pack=touch x",
            "go*"
        ]
    );
}

#[cfg(unix)]
#[tokio::test]
async fn ls_remote_ignores_the_repository_it_is_run_in() {
    struct RestoreCwd(std::path::PathBuf);
    impl Drop for RestoreCwd {
        fn drop(&mut self) {
            std::env::set_current_dir(&self.0).unwrap();
        }
    }

    let tmp = tempfile::tempdir().unwrap();
    let marker = tmp.path().join("marker");
    // Files anyone can commit: to git, a directory that holds them is a bare repository.
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(repo.join("objects")).unwrap();
    std::fs::create_dir_all(repo.join("refs")).unwrap();
    std::fs::write(repo.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(
        repo.join("config"),
        format!(
            "[core]\n\tbare = true\n\tsshCommand = \"touch '{}'; false\"\n",
            marker.display()
        ),
    )
    .unwrap();
    // Stands in for ssh, so the test stays off the network.
    let global = tmp.path().join("gitconfig");
    std::fs::write(&global, "[core]\n\tsshCommand = false\n").unwrap();
    let mut env = crate::testing::EnvVarGuard::new();
    env.set("GIT_CONFIG_GLOBAL", &global);
    env.set("GIT_CONFIG_NOSYSTEM", "1");
    let remote = "ssh://git@example.invalid/x/y.git";

    let _cwd = RestoreCwd(std::env::current_dir().unwrap());
    std::env::set_current_dir(&repo).unwrap();
    assert!(ls_remote(&[], remote, &["HEAD"]).await.is_err());
    assert!(
        !marker.exists(),
        "ran the sshCommand of the current directory"
    );

    env.set("GIT_DIR", &repo);
    assert!(ls_remote(&[], remote, &["HEAD"]).await.is_err());
    assert!(!marker.exists(), "ran the sshCommand of $GIT_DIR");

    // A remote that looks like an option stays a remote.
    let upload_pack = format!("--upload-pack=touch '{}'", marker.display());
    assert!(ls_remote(&[], &upload_pack, &["HEAD"]).await.is_err());
    assert!(!marker.exists(), "read the remote as --upload-pack");
}

#[cfg(unix)]
#[test]
fn git_credential_fill_ignores_the_repository_it_is_run_in() {
    let tmp = tempfile::tempdir().unwrap();
    let marker = tmp.path().join("marker");
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(repo.join("objects")).unwrap();
    std::fs::create_dir_all(repo.join("refs")).unwrap();
    std::fs::write(repo.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    std::fs::write(
        repo.join("config"),
        format!(
            "[core]\n\tbare = true\n[credential]\n\thelper = \"!touch '{}'; false\"\n",
            marker.display()
        ),
    )
    .unwrap();
    let global = tmp.path().join("gitconfig");
    std::fs::write(&global, "").unwrap();
    let mut env = crate::testing::EnvVarGuard::new();
    env.set("GIT_CONFIG_GLOBAL", &global);
    env.set("GIT_CONFIG_NOSYSTEM", "1");

    struct RestoreCwd(std::path::PathBuf);
    impl Drop for RestoreCwd {
        fn drop(&mut self) {
            std::env::set_current_dir(&self.0).unwrap();
        }
    }
    let _cwd = RestoreCwd(std::env::current_dir().unwrap());
    std::env::set_current_dir(&repo).unwrap();
    // Each call is cached per provider and host, so use names no other test asks for.
    crate::tokens::get_git_credential_token("cwd-test", "cwd.example.invalid");
    assert!(
        !marker.exists(),
        "ran the credential.helper of the current directory"
    );

    env.set("GIT_DIR", &repo);
    crate::tokens::get_git_credential_token("git-dir-test", "git-dir.example.invalid");
    assert!(!marker.exists(), "ran the credential.helper of $GIT_DIR");
}

mod worktree;

#[test]
fn test_pick_remote_name() {
    assert_eq!(pick_remote_name(""), "origin");
    assert_eq!(pick_remote_name("origin\n"), "origin");
    assert_eq!(pick_remote_name("upstream\n"), "upstream");
    assert_eq!(pick_remote_name("fork\norigin\n"), "origin");
    assert_eq!(pick_remote_name("upstream\nfork\n"), "upstream");
}

#[test]
fn head_helpers_do_not_panic_on_an_empty_repo() {
    let tmp = tempfile::tempdir().unwrap();
    let status = Command::new("git")
        .args(["-c", "init.defaultBranch=main", "init", "-q"])
        .current_dir(tmp.path())
        // Other tests here set these in the process environment.
        .env_remove("GIT_DIR")
        .env_remove("GIT_WORK_TREE")
        .status()
        .unwrap();
    assert!(status.success());
    let git = Git::new(tmp.path());
    // Exercise the gix path, not the git CLI fallback.
    assert!(git.repo().is_ok());
    assert!(git.current_sha().is_err());
    assert!(git.current_sha_short().is_err());
    assert_eq!(git.current_branch().unwrap(), "main");
    assert!(git.current_abbrev_ref().is_ok());
}