vivacity-core 0.15.0

Manifests, content hash, platform checks, dist fetching, content-addressed store and installation for vivacity
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
//! Root package version: port of `RootPackageLoader::load` +
//! `VersionGuesser::guessGitVersion` (docs/reference/RootPackageLoader.php,
//! VersionGuesser.php, Composer 2.10.3). Order: `version` from composer.json,
//! else `COMPOSER_ROOT_VERSION`, else git (current branch; detached HEAD ->
//! `dev-<sha>` then exact tag; feature branch -> closest parent branch by
//! `git rev-list`), else `1.0.0+no-version-set`.
//! hg/fossil/svn are not ported (fallback to the default, as without a VCS).
//!
//! `guess_version` is the `VersionGuesser::guessVersion` used for the root
//! and for the packages of a `path` repository: git is run in the directory
//! with no `GIT_DIR` pin, so it walks up to the enclosing repository exactly
//! as Composer's `git branch` does (a package without a repository of its
//! own takes the project's branch).

use crate::version::{normalize_pretty, UnsupportedVersion};
use serde_json::Value;
use std::path::Path;
use std::process::Command;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RootVersion {
    pub pretty_version: String,
    /// Normalised version (Composer's `version_normalized`).
    pub version: String,
    pub reference: Option<String>,
}

/// `VersionGuesser::guessVersion` result after `postprocess`: the version
/// (the parent branch when HEAD is on a feature branch) and, on a feature
/// branch, the feature branch itself (`feature_version`,
/// `feature_pretty_version`) — a `path` repository loads both as packages.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GuessedVersion {
    pub version: String,
    pub pretty_version: String,
    pub commit: Option<String>,
    pub feature_version: Option<String>,
    pub feature_pretty_version: Option<String>,
}

pub const DEFAULT_PRETTY_VERSION: &str = "1.0.0+no-version-set";

fn normalize_or_raw(v: &str) -> String {
    normalize_pretty(v).unwrap_or_else(|_| v.to_owned())
}

/// `VersionParser::normalizeBranch` (composer/semver): `1.2` -> numeric
/// `1.2.x.x-dev` (x -> 9999999), else `dev-<name>`.
pub fn normalize_branch(name: &str) -> String {
    let name = name.trim();
    let stripped = name
        .strip_prefix('v')
        .or_else(|| name.strip_prefix('V'))
        .unwrap_or(name);
    let parts: Vec<&str> = stripped.split('.').collect();
    let numeric_or_x = |s: &str| {
        !s.is_empty() && (s.bytes().all(|b| b.is_ascii_digit()) || matches!(s, "x" | "X" | "*"))
    };
    if (1..=4).contains(&parts.len())
        && parts[0].bytes().all(|b| b.is_ascii_digit())
        && !parts[0].is_empty()
        && parts[1..].iter().all(|p| numeric_or_x(p))
    {
        let mut out: Vec<String> = parts
            .iter()
            .map(|p| {
                if matches!(*p, "x" | "X" | "*") {
                    "9999999".to_owned()
                } else {
                    (*p).to_owned()
                }
            })
            .collect();
        while out.len() < 4 {
            out.push("9999999".to_owned());
        }
        return format!("{}-dev", out.join("."));
    }
    format!("dev-{name}")
}

/// `VersionGuesser::isFeatureBranch`: the `non-feature-branches` entries
/// are regex alternatives (`release-.*`), joined in front of the built-in
/// names and the numeric `\d+\..+` form.
fn is_feature_branch(manifest: &Value, branch: &str) -> bool {
    let custom: Vec<&str> = manifest
        .get("non-feature-branches")
        .and_then(Value::as_array)
        .map(|a| a.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    let mut pattern = String::from("^(");
    if !custom.is_empty() {
        pattern.push_str(&custom.join("|"));
    }
    pattern
        .push_str("|master|main|latest|next|current|support|tip|trunk|default|develop|\\d+\\..+)$");
    match pcre2::bytes::RegexBuilder::new().build(&pattern) {
        Ok(re) => !re.is_match(branch.as_bytes()).unwrap_or(false),
        // An invalid custom pattern: Composer's preg_match warns and
        // returns false -> every branch is a feature branch.
        Err(_) => true,
    }
}

/// Runs git in `dir` like `ProcessExecutor` after `GitUtil::cleanEnv`: no
/// `GIT_DIR`/`GIT_WORK_TREE` (git finds the repository by walking up),
/// English output, never an interactive prompt. None when git fails.
pub fn git(dir: &Path, args: &[&str]) -> Option<String> {
    let out = Command::new("git")
        .args(args)
        .current_dir(dir)
        .env_remove("GIT_DIR")
        .env_remove("GIT_WORK_TREE")
        .env_remove("GIT_INDEX_FILE")
        .env("LANGUAGE", "C")
        .env("LC_ALL", "C")
        .env("GIT_TERMINAL_PROMPT", "0")
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// `VersionGuesser::guessVersion` (git only) + `postprocess`.
pub fn guess_version(manifest: &Value, project: &Path) -> Option<GuessedVersion> {
    let output = git(
        project,
        &["branch", "-a", "--no-color", "--no-abbrev", "-v"],
    )?;
    let mut version: Option<String> = None;
    let mut pretty: Option<String> = None;
    let mut commit: Option<String> = None;
    let mut is_feature = false;
    let mut is_detached = false;
    let mut branches: Vec<String> = Vec::new();
    let is_hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());

    for line in output.lines() {
        if line.is_empty() {
            continue;
        }
        // Current line: `* <name|(no branch)|(HEAD detached at X)> <sha> ...`
        if let Some(rest) = line.strip_prefix("* ") {
            let rest = rest.trim_start();
            let (name, tail) = if rest.starts_with('(') {
                match rest.find(')') {
                    Some(i) => (&rest[..=i], rest[i + 1..].trim_start()),
                    None => continue,
                }
            } else {
                match rest.find(' ') {
                    Some(i) => (&rest[..i], rest[i..].trim_start()),
                    None => continue,
                }
            };
            let sha = tail.split_whitespace().next().unwrap_or("");
            if !is_hex(sha) {
                continue;
            }
            if name.starts_with('(') {
                // The regex only knows `(no branch)`, `(detached from X)` and
                // `(HEAD detached at X)`: any other parenthesised form (`(HEAD
                // detached from X)`) matches nothing, and the version stays
                // unknown (tag lookup, then the caller's default).
                if !(name == "(no branch)"
                    || name.starts_with("(detached from ")
                    || name.starts_with("(HEAD detached at "))
                {
                    continue;
                }
                version = Some(format!("dev-{sha}"));
                pretty = version.clone();
                is_feature = true;
                is_detached = true;
            } else {
                version = Some(normalize_branch(name));
                pretty = Some(format!("dev-{name}"));
                is_feature = is_feature_branch(manifest, name);
            }
            commit = Some(sha.to_owned());
        }
        // Candidates: `[* ] <name|remotes/origin/name> <sha>` (name without `/`), excluding `*/HEAD`.
        let trimmed = line.trim_start_matches("* ").trim_start();
        let mut parts = trimmed.split_whitespace();
        let (Some(name), Some(sha)) = (parts.next(), parts.next()) else {
            continue;
        };
        if name.ends_with("/HEAD") || !is_hex(sha) {
            continue;
        }
        let bare = name
            .strip_prefix("remotes/origin/")
            .or_else(|| name.strip_prefix("remotes/upstream/"))
            .unwrap_or(name);
        if bare.contains('/') {
            continue;
        }
        branches.push(name.to_owned());
    }

    let mut feature: Option<(String, String)> = None;
    if is_feature {
        if let (Some(v), Some(p)) = (&version, &pretty) {
            feature = Some((v.clone(), p.clone()));
            let (nv, np) = guess_feature_version(manifest, v, &branches, project);
            version = Some(nv);
            pretty = Some(np);
        }
    }
    if version.is_none() || is_detached {
        if let Some(tag) = git(project, &["describe", "--exact-match", "--tags"]) {
            let tag = tag.trim();
            if let Ok(norm) = normalize_pretty(tag) {
                version = Some(norm);
                pretty = Some(tag.to_owned());
                feature = None;
            }
        }
    }
    if commit.is_none() {
        if let Some(out) = git(project, &["rev-list", "--format=%H", "-n1", "HEAD"]) {
            commit = out
                .lines()
                .find(|l| !l.starts_with("commit "))
                .map(|l| l.trim().to_owned())
                .filter(|s| !s.is_empty());
        }
    }
    let version = version?;
    let pretty = pretty?;
    // postprocess: a feature branch equal to its guess is dropped;
    // `X.9999999...-dev` displays as `X.x-dev`.
    let feature = feature.filter(|(fv, fp)| !(fv == &version && fp == &pretty));
    let collapse = |version: &str, pretty: String| {
        if version.ends_with("-dev") && version.contains(".9999999") {
            collapse_nines(version)
        } else {
            pretty
        }
    };
    let pretty = collapse(&version, pretty);
    let (feature_version, feature_pretty_version) = match feature {
        Some((fv, fp)) => {
            let fp = collapse(&fv, fp);
            (Some(fv), Some(fp))
        }
        None => (None, None),
    };
    Some(GuessedVersion {
        version,
        pretty_version: pretty,
        commit,
        feature_version,
        feature_pretty_version,
    })
}

/// `guessGitVersion` for the root package.
fn guess_git(manifest: &Value, project: &Path) -> Option<RootVersion> {
    let g = guess_version(manifest, project)?;
    Some(RootVersion {
        pretty_version: g.pretty_version,
        version: g.version,
        reference: g.commit,
    })
}

fn collapse_nines(version: &str) -> String {
    let mut out = version.replace(".9999999", "\u{0}");
    while out.contains("\u{0}\u{0}") {
        out = out.replace("\u{0}\u{0}", "\u{0}");
    }
    out.replace('\u{0}', ".x")
}

/// `guessFeatureVersion` with `git rev-list %candidate%..%branch%`: the
/// non-feature parent branch with the shortest delta wins.
fn guess_feature_version(
    manifest: &Value,
    version: &str,
    branches: &[String],
    project: &Path,
) -> (String, String) {
    let has_alias = manifest
        .get("extra")
        .and_then(|e| e.get("branch-alias"))
        .and_then(|b| b.get(version))
        .is_some();
    let has_self_version = manifest.to_string().contains("\"self.version\"");
    if has_alias && !has_self_version {
        return (version.to_owned(), version.to_owned());
    }
    let branch = version.strip_prefix("dev-").unwrap_or(version).to_owned();
    if !is_feature_branch(manifest, &branch) {
        return (version.to_owned(), version.to_owned());
    }
    let mut sorted: Vec<String> = branches.to_vec();
    sorted.sort_by(|a, b| {
        let (ar, br) = (a.starts_with("remotes/"), b.starts_with("remotes/"));
        if ar != br {
            return if ar {
                std::cmp::Ordering::Greater
            } else {
                std::cmp::Ordering::Less
            };
        }
        strnatcasecmp(b, a)
    });
    let mut best_len = usize::MAX;
    let mut result = (version.to_owned(), version.to_owned());
    for candidate in &sorted {
        let candidate_version = candidate
            .strip_prefix("remotes/")
            .and_then(|r| r.split_once('/').map(|x| x.1))
            .unwrap_or(candidate);
        if candidate == &branch || is_feature_branch(manifest, candidate_version) {
            continue;
        }
        let Some(out) = git(project, &["rev-list", &format!("{candidate}..{branch}")]) else {
            continue;
        };
        // At equal length, a candidate later in the order replaces the previous one.
        if out.len() <= best_len {
            best_len = out.len();
            result = (
                normalize_branch(candidate_version),
                format!("dev-{candidate_version}"),
            );
            if best_len == 0 {
                break;
            }
        }
    }
    result
}

/// Minimal strnatcasecmp (same rules as vivacity-autoload::natsort, duplicated
/// to avoid a cross dependency); enough to sort branch names.
fn strnatcasecmp(a: &str, b: &str) -> std::cmp::Ordering {
    let (a, b) = (a.to_ascii_lowercase(), b.to_ascii_lowercase());
    let (ab, bb) = (a.as_bytes(), b.as_bytes());
    let (mut i, mut j) = (0, 0);
    while i < ab.len() && j < bb.len() {
        if ab[i].is_ascii_digit() && bb[j].is_ascii_digit() {
            let si = i;
            while i < ab.len() && ab[i].is_ascii_digit() {
                i += 1;
            }
            let sj = j;
            while j < bb.len() && bb[j].is_ascii_digit() {
                j += 1;
            }
            let na: u128 = a[si..i].parse().unwrap_or(0);
            let nb: u128 = b[sj..j].parse().unwrap_or(0);
            if na != nb {
                return na.cmp(&nb);
            }
        } else {
            if ab[i] != bb[j] {
                return ab[i].cmp(&bb[j]);
            }
            i += 1;
            j += 1;
        }
    }
    (ab.len() - i).cmp(&(bb.len() - j))
}

/// `VersionGuesser::getRootVersionFromEnv`: `COMPOSER_ROOT_VERSION` when
/// set and non-empty, `1.2-dev` spelled `1.2.x-dev`.
pub fn root_version_from_env() -> Option<String> {
    let env = std::env::var("COMPOSER_ROOT_VERSION").ok()?;
    // `if (Platform::getEnv(...))`: `0` is as falsy as an empty string.
    if env.is_empty() || env == "0" {
        return None;
    }
    let lower = env.to_ascii_lowercase();
    Some(match lower.strip_suffix("-dev") {
        Some(num)
            if !num.is_empty()
                && num
                    .split('.')
                    .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) =>
        {
            format!("{}.x-dev", &env[..num.len()])
        }
        _ => env.clone(),
    })
}

/// Determines the root version like RootPackageLoader.
pub fn detect(manifest: &Value, project: &Path) -> RootVersion {
    if let Some(v) = manifest.get("version").and_then(Value::as_str) {
        return RootVersion {
            pretty_version: v.to_owned(),
            version: normalize_or_raw(v),
            reference: None,
        };
    }
    if let Some(v) = root_version_from_env() {
        return RootVersion {
            pretty_version: v.clone(),
            version: normalize_or_raw(&v),
            reference: None,
        };
    }
    if let Some(g) = guess_git(manifest, project) {
        return g;
    }
    RootVersion {
        pretty_version: DEFAULT_PRETTY_VERSION.to_owned(),
        version: "1.0.0.0".to_owned(),
        reference: None,
    }
}

/// `VersionParser::DEFAULT_BRANCH_ALIAS`.
pub const DEFAULT_BRANCH_ALIAS: &str = "9999999-dev";

/// `VersionParser::parseNumericAliasPrefix` (composer/semver): `1.2.x-dev` and
/// `1.2-dev` -> `1.2.`, else None. Case-insensitive like the PCRE pattern.
pub fn parse_numeric_alias_prefix(branch: &str) -> Option<String> {
    let n = branch.len();
    if n < 4 || !branch.is_char_boundary(n - 4) || !branch[n - 4..].eq_ignore_ascii_case("-dev") {
        return None;
    }
    let mut rest = &branch[..n - 4];
    if let Some(r) = rest.strip_suffix(".x").or_else(|| rest.strip_suffix(".X")) {
        rest = r;
    }
    let numeric = !rest.is_empty()
        && rest
            .split('.')
            .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()));
    numeric.then(|| format!("{rest}."))
}

/// Pretty version of a normalised alias, like ArrayLoader:
/// `preg_replace('{(\.9{7})+}', '.x', ...)`.
fn pretty_alias(normalized: &str) -> String {
    const X: &str = ".9999999";
    let mut out = String::with_capacity(normalized.len());
    let mut rest = normalized;
    while let Some(i) = rest.find(X) {
        out.push_str(&rest[..i]);
        out.push_str(".x");
        rest = &rest[i + X.len()..];
        while let Some(r) = rest.strip_prefix(X) {
            rest = r;
        }
    }
    out.push_str(rest);
    out
}

/// `ArrayLoader::getBranchAlias` (Composer 2.10.3): the alias Composer
/// attaches to a package (root or locked) whose version is a branch (`dev-*`
/// or `*-dev`). `extra.branch-alias` takes priority (`-dev` target,
/// normalised by normalizeBranch, source equal to the version ignoring case,
/// compatible numeric prefix), else `9999999-dev` if `default-branch` is
/// true and the version has no numeric prefix.
/// Returns (normalised alias, pretty alias); the pretty one is installed.php's.
pub fn branch_alias_of(
    version: &str,
    extra: Option<&Value>,
    default_branch: bool,
) -> Option<(String, String)> {
    if !(version.starts_with("dev-") || version.ends_with("-dev")) {
        return None;
    }
    if let Some(map) = extra
        .and_then(|e| e.get("branch-alias"))
        .and_then(Value::as_object)
    {
        for (source, target) in map {
            let Some(target) = target.as_str() else {
                continue;
            };
            let Some(target_base) = target.strip_suffix("-dev") else {
                continue;
            };
            let validated = if target == DEFAULT_BRANCH_ALIAS {
                target.to_owned()
            } else {
                normalize_branch(target_base)
            };
            if !validated.ends_with("-dev") {
                continue;
            }
            if version.to_lowercase() != source.to_lowercase() {
                continue;
            }
            if let (Some(sp), Some(tp)) = (
                parse_numeric_alias_prefix(source),
                parse_numeric_alias_prefix(target),
            ) {
                if !tp.to_lowercase().starts_with(&sp.to_lowercase()) {
                    continue;
                }
            }
            let pretty = pretty_alias(&validated);
            return Some((validated, pretty));
        }
    }
    if default_branch {
        let v = version.strip_prefix('v').unwrap_or(version);
        if parse_numeric_alias_prefix(v).is_none() {
            return Some((
                DEFAULT_BRANCH_ALIAS.to_owned(),
                DEFAULT_BRANCH_ALIAS.to_owned(),
            ));
        }
    }
    None
}

/// Branch alias of the root: getBranchAlias on the composer.json, the version
/// being the pretty version retained by RootPackageLoader.
pub fn branch_alias(manifest: &Value, root: &RootVersion) -> Option<(String, String)> {
    let default_branch = manifest
        .get("default-branch")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    branch_alias_of(&root.pretty_version, manifest.get("extra"), default_branch)
}

impl std::fmt::Display for UnsupportedVersionAlias {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}
#[derive(Debug)]
pub struct UnsupportedVersionAlias(pub UnsupportedVersion);

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn normalize_branch_matches_semver() {
        assert_eq!(normalize_branch("main"), "dev-main");
        assert_eq!(normalize_branch("2.2"), "2.2.9999999.9999999-dev");
        assert_eq!(normalize_branch("1.x"), "1.9999999.9999999.9999999-dev");
        assert_eq!(normalize_branch("v3"), "3.9999999.9999999.9999999-dev");
        assert_eq!(normalize_branch("feature/x"), "dev-feature/x");
    }

    #[test]
    fn feature_branches() {
        let m = json!({});
        assert!(!is_feature_branch(&m, "main"));
        assert!(!is_feature_branch(&m, "develop"));
        assert!(!is_feature_branch(&m, "2.2"));
        assert!(is_feature_branch(&m, "feature-x"));
        let m = json!({"non-feature-branches": ["release-.*"]});
        assert!(!is_feature_branch(&m, "release-1"));
        assert!(is_feature_branch(&m, "feature-1"));
    }

    #[test]
    fn collapse() {
        assert_eq!(collapse_nines("2.2.9999999.9999999-dev"), "2.2.x-dev");
        assert_eq!(collapse_nines("1.9999999.9999999.9999999-dev"), "1.x-dev");
    }

    #[test]
    fn detect_in_git_repo() {
        let tmp = tempfile::tempdir().expect("tmp");
        let p = tmp.path();
        let run = |args: &[&str]| {
            let st = Command::new("git")
                .args(args)
                .current_dir(p)
                .env("GIT_AUTHOR_NAME", "t")
                .env("GIT_AUTHOR_EMAIL", "t@t")
                .env("GIT_COMMITTER_NAME", "t")
                .env("GIT_COMMITTER_EMAIL", "t@t")
                .status()
                .expect("git");
            assert!(st.success(), "git {args:?}");
        };
        run(&["init", "-q", "-b", "main"]);
        std::fs::write(p.join("a.txt"), "a").expect("write");
        run(&["add", "."]);
        run(&["commit", "-q", "-m", "init"]);
        let r = detect(&json!({}), p);
        assert_eq!(r.pretty_version, "dev-main");
        assert_eq!(r.version, "dev-main");
        assert_eq!(r.reference.as_deref().map(str::len), Some(40));

        // Feature branch: the parent (main) is retained.
        run(&["checkout", "-q", "-b", "feature-x"]);
        std::fs::write(p.join("b.txt"), "b").expect("write");
        run(&["add", "."]);
        run(&["commit", "-q", "-m", "feat"]);
        let r = detect(&json!({}), p);
        assert_eq!(r.pretty_version, "dev-main");
        let g = guess_version(&json!({}), p).expect("guess");
        assert_eq!(g.feature_pretty_version.as_deref(), Some("dev-feature-x"));
        assert_eq!(g.feature_version.as_deref(), Some("dev-feature-x"));
        // A sub-directory without a repository of its own: git walks up.
        std::fs::create_dir_all(p.join("packages/x")).expect("mkdir");
        let g = guess_version(&json!({}), &p.join("packages/x")).expect("guess");
        assert_eq!(g.pretty_version, "dev-main");
        assert_eq!(g.commit.as_deref().map(str::len), Some(40));

        // Numeric branch + alias.
        run(&["checkout", "-q", "-b", "2.2"]);
        let m = json!({"extra": {"branch-alias": {"dev-2.2": "2.2.x-dev"}}});
        let r = detect(&m, p);
        assert_eq!(r.version, "2.2.9999999.9999999-dev");
        assert_eq!(r.pretty_version, "2.2.x-dev");
        assert_eq!(
            branch_alias(&m, &r),
            None,
            "the alias is indexed by dev-2.2, not by the pretty version x-dev"
        );

        // Exact tag on detached HEAD.
        run(&["tag", "v1.2.3"]);
        run(&["checkout", "-q", "--detach", "HEAD"]);
        let r = detect(&json!({}), p);
        assert_eq!(r.pretty_version, "v1.2.3");
        assert_eq!(r.version, "1.2.3.0");

        // A commit on the detached HEAD: `* (HEAD detached from v1.2.3)`
        // matches none of the forms Composer's regex knows, no tag matches
        // either: no version (the callers fall back to their default).
        std::fs::write(p.join("c.txt"), "c").expect("write");
        run(&["add", "."]);
        run(&["commit", "-q", "-m", "detached"]);
        assert!(guess_version(&json!({}), p).is_none());
        assert_eq!(detect(&json!({}), p).pretty_version, DEFAULT_PRETTY_VERSION);
    }
}