vivacity-core 0.22.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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! 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: where one of them would give Composer a
//! version ([`foreign_vcs_version`]), the command goes to Composer.
//!
//! `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,
    }
}

/// What git answered during a run, per (directory, arguments): every call
/// here only reads the repository, and a run reads it several times (the
/// root-version warning, the version itself, installed.php). Kept only
/// between [`remember_git_answers`] and [`forget_git_answers`], which
/// `vivacity::run` calls around each run — the repository may change
/// between two runs of a program that embeds vivacity, and outside a run
/// (a test that commits between two guesses) git always runs.
type GitAnswers = std::collections::HashMap<(std::path::PathBuf, Vec<String>), Option<String>>;
static GIT_ANSWERS: std::sync::Mutex<Option<GitAnswers>> = std::sync::Mutex::new(None);

/// Starts keeping git's answers ([`git`]), empty, until the returned guard
/// is dropped (panics included).
#[must_use = "git's answers are forgotten when the guard is dropped"]
pub fn remember_git_answers() -> GitAnswersScope {
    if let Ok(mut answers) = GIT_ANSWERS.lock() {
        *answers = Some(GitAnswers::new());
    }
    GitAnswersScope(())
}

/// Keeps git's answers while alive ([`remember_git_answers`]).
pub struct GitAnswersScope(());

impl Drop for GitAnswersScope {
    fn drop(&mut self) {
        forget_git_answers();
    }
}

/// Forgets git's answers and stops keeping them.
pub fn forget_git_answers() {
    if let Ok(mut answers) = GIT_ANSWERS.lock() {
        *answers = None;
    }
}

/// 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. Asked
/// twice the same thing in one run, git runs once ([`remember_git_answers`]).
pub fn git(dir: &Path, args: &[&str]) -> Option<String> {
    let key = (
        dir.to_path_buf(),
        args.iter().map(|a| (*a).to_owned()).collect::<Vec<_>>(),
    );
    if let Ok(answers) = GIT_ANSWERS.lock() {
        if let Some(answer) = answers.as_ref().and_then(|a| a.get(&key)) {
            return answer.clone();
        }
    }
    let answer = run_git(dir, args);
    if let Ok(mut answers) = GIT_ANSWERS.lock() {
        if let Some(answers) = answers.as_mut() {
            answers.insert(key, answer.clone());
        }
    }
    answer
}

fn run_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())
}

/// `git branch -a --no-color --no-abbrev -v`, as `guessGitVersion` runs it.
const BRANCH_ARGS: &[&str] = &["branch", "-a", "--no-color", "--no-abbrev", "-v"];

/// The current line of `git branch -v` (`* <name> <sha> …`) as
/// `guessGitVersion`'s regex reads it: its name and sha. `(no branch)`,
/// `(detached from X)` and `(HEAD detached at X)` are the only parenthesised
/// forms it knows; any other (`(HEAD detached from X)`) matches nothing. None
/// for any other line. Slightly wider than the regex on input git never
/// prints (uppercase hex, a sha ending the line).
fn current_branch(line: &str) -> Option<(&str, &str)> {
    let rest = line.strip_prefix("* ")?.trim_start();
    let (name, tail) = if rest.starts_with('(') {
        let i = rest.find(')')?;
        (&rest[..=i], rest[i + 1..].trim_start())
    } else {
        let i = rest.find(' ')?;
        (&rest[..i], rest[i..].trim_start())
    };
    let sha = tail.split_whitespace().next().unwrap_or("");
    if sha.is_empty() || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    if name.starts_with('(')
        && !(name == "(no branch)"
            || name.starts_with("(detached from ")
            || name.starts_with("(HEAD detached at "))
    {
        return None;
    }
    Some((name, sha))
}

/// Whether [`guess_version`] finds a version, with as few git calls as it
/// takes to know: one when HEAD is on a branch or detached at a commit, a
/// second (`describe`) otherwise. `RootPackageLoader::load` warns when it
/// does not (`vivacity_resolver::root::undetected_version_warning`); the
/// version itself is guessed later, by the command.
pub fn version_guessable(project: &Path) -> bool {
    let Some(output) = git(project, BRANCH_ARGS) else {
        return false;
    };
    if output.lines().any(|l| current_branch(l).is_some()) {
        return true;
    }
    git(project, &["describe", "--exact-match", "--tags"])
        .is_some_and(|tag| normalize_pretty(tag.trim()).is_ok())
}

/// `VersionGuesser::guessVersion` (git only) + `postprocess`.
pub fn guess_version(manifest: &Value, project: &Path) -> Option<GuessedVersion> {
    let output = git(project, BRANCH_ARGS)?;
    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 line.starts_with("* ") {
            // A current line the regex does not take (`(HEAD detached from
            // X)`) leaves the version unknown (tag lookup, then the
            // caller's default), and is no candidate either.
            let Some((name, sha)) = current_branch(line) else {
                continue;
            };
            if name.starts_with('(') {
                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::guessVersion` after git (VersionGuesser.php:84-104):
/// `hg branch`, then `fossil branch list` / `fossil tag list`, then `svn info
/// --xml`, each run in `dir` — a zero exit gives Composer a version (always
/// for hg; for fossil and svn, nearly always). vivacity reads none of them:
/// `Some(what)` when one of them would answer, so that the caller hands the
/// command to Composer; `None` otherwise — and then without running anything
/// unless a working copy is found walking up from `dir` (`.hg`, `_FOSSIL_` /
/// `.fslckout`, `.svn`), where each tool looks for it. A missing binary
/// fails as it does for Composer, which then defaults like vivacity.
/// Called only once git has given no version.
pub fn foreign_vcs_version(dir: &Path) -> Option<&'static str> {
    let mut hg = false;
    let mut fossil = false;
    let mut svn = false;
    for d in dir.ancestors() {
        hg |= d.join(".hg").is_dir();
        fossil |= d.join("_FOSSIL_").is_file() || d.join(".fslckout").is_file();
        svn |= d.join(".svn").is_dir();
    }
    let answers = |program: &str, args: &[&str]| {
        Command::new(program)
            .args(args)
            .current_dir(dir)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
    };
    if hg && answers("hg", &["branch"]) {
        return Some("Mercurial (`hg branch`)");
    }
    if fossil && (answers("fossil", &["branch", "list"]) || answers("fossil", &["tag", "list"])) {
        return Some("Fossil (`fossil branch list`)");
    }
    if svn && answers("svn", &["info", "--xml"]) {
        return Some("Subversion (`svn info --xml`)");
    }
    None
}

/// `RootPackageLoader::load` guesses the root's version — no `version` in
/// composer.json, no `COMPOSER_ROOT_VERSION` — and git gives none, but
/// hg, fossil or svn would ([`foreign_vcs_version`]): the reason to hand the
/// command to Composer. Free when no working copy of those is found above
/// the project: git runs only when one is.
pub fn root_version_from_foreign_vcs(manifest: &Value, project: &Path) -> Option<&'static str> {
    if manifest.get("version").is_some_and(|v| !v.is_null()) || root_version_from_env().is_some() {
        return None;
    }
    if !foreign_vcs_marked(project) || version_guessable(project) {
        return None;
    }
    foreign_vcs_version(project)
}

/// A working copy of hg, fossil or svn above `dir` (`stat`s only): the
/// condition for [`foreign_vcs_version`] to run anything.
pub fn foreign_vcs_marked(dir: &Path) -> bool {
    dir.ancestors().any(|d| {
        d.join(".hg").is_dir()
            || d.join(".svn").is_dir()
            || d.join("_FOSSIL_").is_file()
            || d.join(".fslckout").is_file()
    })
}

/// `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);
    }
}