vivacity 0.26.0

Fast, Composer-compatible installer for PHP projects: install, update, require, remove, dump-autoload
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
//! Emulation of `phpstan/extension-installer` (1.4.3) and its fork
//! `rector/extension-installer` (0.11.2) — docs/reference/plugins/, MIT.
//! Each writes `src/GeneratedConfig.php` inside its own package: a
//! `var_export` of the installed extensions (`phpstan-extension` /
//! `rector-extension` packages, or any package with `extra.phpstan` /
//! `extra.rector`), keyed by name (`ksort`), with the absolute install path
//! (Composer's `getInstallPath`: the physical project directory + the
//! vendor path), the path relative to the generated file's directory
//! (`findShortestPath(..., directories: true)`), the `extra` block and
//! `getFullPrettyVersion()`. phpstan's adds the packages named `*phpstan*`
//! that are not extensions (`NOT_INSTALLED`) and the compacted
//! `phpstan/phpstan` constraint of the extensions
//! (`Intervals::compactConstraint`, printed `>=a, <b`). Both plugins
//! listen to `POST_INSTALL_CMD` and `POST_UPDATE_CMD` and write on stdout
//! (`$io->write`, normal level): phpstan's "Extensions installed" every
//! time (`Plugin::process`, Plugin.php:198), then, when the file changed
//! (`md5` of the old file against the new contents, :200-214), one line per
//! installed, unsupported and ignored package; rector's
//! "rector/rector-installer: Extensions installed" and one line per
//! installed package only when the file changed
//! (`PluginInstaller::install`, PluginInstaller.php:95-104).
//! docs/plans/plugin-lines.md.
//!
//! `infection/extension-installer` 0.1.2 (docs/reference/plugins/
//! infection-extension-installer/, BSD-3-Clause; docs/plans/
//! remaining-fallbacks.md) writes `src/GeneratedExtensionsConfig.php` the
//! same way from the `infection-extension` packages — install path,
//! `extra.infection`, version; no relative path — but on every run (no
//! `md5` comparison), and prints its lines every time: "No extensions
//! found", or "Extensions installed" and one line per extension, then the
//! invalid ones (no `extra.infection.class`), in the local repository's
//! order.

use anyhow::Result;
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::Path;
use vivacity_core::layout::{plugin_allowed, Layout, PluginVerdict};
use vivacity_core::lock::{Lock, LockPackage};
use vivacity_core::pathutil::{find_shortest_path, normalize_path};
use vivacity_core::runtime_stub::php_var_export;
use vivacity_resolver::constraint::{parse_constraints, Bound, Constraint};

pub const PHPSTAN: &str = "phpstan/extension-installer";
pub const RECTOR: &str = "rector/extension-installer";
pub const INFECTION: &str = "infection/extension-installer";

const PHPSTAN_TEMPLATE: &str = "<?php declare(strict_types = 1);\n\nnamespace PHPStan\\ExtensionInstaller;\n\n/**\n * This class is generated by phpstan/extension-installer.\n * @internal\n */\nfinal class GeneratedConfig\n{\n\n\tpublic const EXTENSIONS = %s;\n\n\tpublic const NOT_INSTALLED = %s;\n\n\t/** @var string|null */\n\tpublic const PHPSTAN_VERSION_CONSTRAINT = %s;\n\n\tprivate function __construct()\n\t{\n\t}\n\n}\n";

const RECTOR_TEMPLATE: &str = "<?php\n\ndeclare(strict_types = 1);\n\nnamespace Rector\\RectorInstaller;\n\n/**\n * This class is generated by rector/extension-installer.\n * @internal\n */\nfinal class GeneratedConfig\n{\n    public const EXTENSIONS = %s;\n\n    private function __construct()\n    {\n    }\n}\n";

const INFECTION_TEMPLATE: &str = "<?php\ndeclare(strict_types=1);\n\nnamespace Infection\\ExtensionInstaller;\n\n/**\n * This class is generated by infection/extension-installer\n */\nfinal class GeneratedExtensionsConfig\n{\n    public const EXTENSIONS = %s;\n\n    private function __construct()\n    {\n    }\n}";

/// `BasePackage::getFullPrettyVersion()` on a lock entry: a dev version
/// shows its source reference (git/hg) or, without a source, its dist
/// reference, truncated to 7 characters when 40 long.
fn full_pretty_version(p: &LockPackage) -> String {
    let pretty = p.version().to_owned();
    let normalized = vivacity_core::version::normalize_pretty(&pretty).unwrap_or_default();
    let is_dev = normalized.starts_with("dev-") || normalized.ends_with("-dev");
    let source_type = p
        .raw
        .get("source")
        .and_then(|s| s.get("type"))
        .and_then(Value::as_str)
        .unwrap_or("");
    let source_ref = p
        .raw
        .get("source")
        .and_then(|s| s.get("reference"))
        .and_then(Value::as_str)
        .unwrap_or("");
    let dist_ref = p.dist_reference().unwrap_or("");
    if !is_dev
        || (!matches!(source_type, "git" | "hg")
            && (!source_type.is_empty() || dist_ref.is_empty()))
    {
        return pretty;
    }
    let reference = if !source_ref.is_empty() {
        source_ref
    } else {
        dist_ref
    };
    if reference.is_empty() {
        return pretty;
    }
    if reference.len() == 40 && source_type != "svn" {
        return format!("{pretty} {}", &reference[..7]);
    }
    format!("{pretty} {reference}")
}

/// `getInstallPath($package)` as an absolute path: `LibraryInstaller`
/// holds `realpath(vendor-dir)` as the OS spells it (`/private/tmp/…` on
/// macOS, `C:\\…\\vendor` on Windows, no `\\?\\` prefix) and appends
/// `/<name>` with forward slashes — joined verbatim, never normalised as a
/// whole.
fn absolute_install_path(layout: &Layout, name: &str) -> Option<String> {
    let abs = layout.abs(name)?;
    let vendor = layout.vendor_dir();
    let rel = abs.strip_prefix(&vendor).ok()?;
    let real = std::fs::canonicalize(&vendor).unwrap_or(vendor);
    let real = real.to_string_lossy();
    let real = real.strip_prefix("\\\\?\\").unwrap_or(&real);
    let rel = rel.to_string_lossy().replace('\\', "/");
    Some(format!("{}/{}", real.trim_end_matches(['/', '\\']), rel))
}

fn constraint_into_string(c: &Constraint) -> String {
    let (lo, hi) = (c.lower_bound(), c.upper_bound());
    format!(
        "{}{}, {}{}",
        if lo.inclusive { ">=" } else { ">" },
        lo.version,
        if hi.inclusive { "<=" } else { "<" },
        hi.version
    )
}

/// The file lives inside a package cloned from the store — on Linux a
/// hardlink: written through a temporary file and a rename (a new inode),
/// never in place, or the store entry would carry one project's paths
/// into the next (the rector fixture's file surfaced in sylius's warm run).
/// Returns whether the contents changed — the plugins compare the old
/// file's `md5` with the new contents (no file: changed).
fn write_if_changed(path: &Path, contents: &str) -> Result<bool> {
    if std::fs::read(path).ok().as_deref() == Some(contents.as_bytes()) {
        return Ok(false);
    }
    let tmp = path.with_extension("php.vivacity-tmp");
    std::fs::write(&tmp, contents)?;
    std::fs::rename(&tmp, path)?;
    Ok(true)
}

/// How many times `$package` sits in the local repository at
/// `POST_*_CMD`: once, plus its branch alias (`ArrayLoader::getBranchAlias`,
/// a default branch included) and each inline alias of the lock
/// (`MarkAliasInstalled` adds them on every run: installed.json keeps
/// none). phpstan lists an ignored package once per entry.
fn local_repository_entries(p: &LockPackage, lock_aliases: &[Value]) -> usize {
    let branch = usize::from(vivacity_resolver::loader::branch_alias(&p.raw).is_some());
    // `Locker::getLockedRepository` attaches a lock alias by name.
    let inline = lock_aliases
        .iter()
        .filter(|a| a.get("package").and_then(Value::as_str) == Some(p.name()))
        .count();
    1 + branch + inline
}

/// `sprintf($template, ...)` with `%s` only.
fn fill(template: &str, args: &[String]) -> String {
    let mut out = String::new();
    let mut parts = template.split("%s");
    if let Some(first) = parts.next() {
        out.push_str(first);
    }
    for (part, arg) in parts.zip(args) {
        out.push_str(arg);
        out.push_str(part);
    }
    out
}

/// phpstan's `Plugin::process` (`POST_INSTALL_CMD` / `POST_UPDATE_CMD`),
/// its lines included. `lock_aliases`: the lock's inline aliases.
pub fn phpstan(
    layout: &Layout,
    local: &Lock,
    lock_aliases: &[Value],
    manifest: &Value,
    with_dev: bool,
    plugins_enabled: bool,
) -> Result<()> {
    let packages: Vec<&LockPackage> = local.wanted_packages(with_dev).collect();
    if !plugins_enabled
        || !packages.iter().any(|p| p.name() == PHPSTAN)
        || !matches!(plugin_allowed(manifest, PHPSTAN), PluginVerdict::Allowed)
    {
        return Ok(());
    }
    let Some(own) = layout.abs(PHPSTAN) else {
        return Ok(());
    };
    let src_dir = own.join("src");
    if !src_dir.is_dir() {
        return Ok(());
    }
    let generated_dir = normalize_path(
        &absolute_install_path(layout, PHPSTAN)
            .map(|p| format!("{p}/src"))
            .unwrap_or_default(),
    );
    let ignore: Vec<&str> = manifest
        .get("extra")
        .and_then(|e| e.get(PHPSTAN))
        .and_then(|e| e.get("ignore"))
        .and_then(Value::as_array)
        .map(|a| a.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    let mut data: BTreeMap<String, Value> = BTreeMap::new();
    let mut not_installed: BTreeMap<String, Value> = BTreeMap::new();
    let mut ignored: Vec<&str> = Vec::new();
    let mut constraints: Vec<Constraint> = Vec::new();
    for p in &packages {
        let extra_phpstan = p.raw.get("extra").and_then(|e| e.get("phpstan"));
        if p.package_type() != "phpstan-extension" && extra_phpstan.is_none() {
            if p.name().contains("phpstan")
                && ![
                    "phpstan/phpstan",
                    "phpstan/phpstan-shim",
                    "phpstan/phpdoc-parser",
                    PHPSTAN,
                ]
                .contains(&p.name())
            {
                not_installed.insert(p.name().to_owned(), Value::String(full_pretty_version(p)));
            }
            continue;
        }
        if ignore.contains(&p.name()) {
            for _ in 0..local_repository_entries(p, lock_aliases) {
                ignored.push(p.name());
            }
            continue;
        }
        let Some(install_path) = absolute_install_path(layout, p.name()) else {
            continue;
        };
        let mut phpstan_constraint: Option<Constraint> = None;
        if let Some(text) = p
            .raw
            .get("require")
            .and_then(|r| r.get("phpstan/phpstan"))
            .and_then(Value::as_str)
        {
            if let Ok(parsed) = parse_constraints(text) {
                let c = parsed.constraint;
                if c.lower_bound() == Bound::zero() || c.upper_bound() == Bound::positive_infinity()
                {
                    continue;
                }
                constraints.push(c.clone());
                phpstan_constraint = Some(c);
            }
        }
        let mut entry = serde_json::Map::new();
        entry.insert("install_path".into(), Value::String(install_path.clone()));
        entry.insert(
            "relative_install_path".into(),
            Value::String(find_shortest_path(&generated_dir, &install_path, true)),
        );
        entry.insert(
            "extra".into(),
            extra_phpstan.cloned().unwrap_or(Value::Null),
        );
        entry.insert("version".into(), Value::String(full_pretty_version(p)));
        entry.insert(
            "phpstanVersionConstraint".into(),
            phpstan_constraint
                .as_ref()
                .map(|c| Value::String(constraint_into_string(c)))
                .unwrap_or(Value::Null),
        );
        data.insert(p.name().to_owned(), Value::Object(entry));
    }
    let overall = if constraints.is_empty() {
        Value::Null
    } else {
        let multi = if constraints.len() == 1 {
            constraints.remove(0)
        } else {
            Constraint::Multi {
                constraints,
                conjunctive: true,
            }
        };
        Value::String(constraint_into_string(
            &vivacity_resolver::intervals::compact_constraint(&multi),
        ))
    };
    let installed_names: Vec<String> = data.keys().cloned().collect();
    let unsupported_names: Vec<String> = not_installed.keys().cloned().collect();
    let as_object = |m: BTreeMap<String, Value>| {
        let mut o = serde_json::Map::new();
        for (k, v) in m {
            o.insert(k, v);
        }
        Value::Object(o)
    };
    let contents = fill(
        PHPSTAN_TEMPLATE,
        &[
            php_var_export(&as_object(data), 0),
            php_var_export(&as_object(not_installed), 0),
            php_var_export(&overall, 0),
        ],
    );
    let changed = write_if_changed(&src_dir.join("GeneratedConfig.php"), &contents)?;
    // `ksort($installedPackages)`, `ksort($notInstalledPackages)`,
    // `sort($ignoredPackages)`: byte order for package names.
    vivacity_core::out!("phpstan/extension-installer: Extensions installed");
    if changed {
        for name in installed_names {
            vivacity_core::out!("> {name}: installed");
        }
        for name in unsupported_names {
            vivacity_core::out!("> {name}: not supported");
        }
        ignored.sort_unstable();
        for name in ignored {
            vivacity_core::out!("> {name}: ignored");
        }
    }
    Ok(())
}

/// rector's `PluginInstaller::install` (`POST_INSTALL_CMD` /
/// `POST_UPDATE_CMD`), its lines included.
pub fn rector(
    layout: &Layout,
    local: &Lock,
    manifest: &Value,
    with_dev: bool,
    plugins_enabled: bool,
) -> Result<()> {
    let packages: Vec<&LockPackage> = local.wanted_packages(with_dev).collect();
    if !plugins_enabled
        || !packages.iter().any(|p| p.name() == RECTOR)
        || !matches!(plugin_allowed(manifest, RECTOR), PluginVerdict::Allowed)
    {
        return Ok(());
    }
    let Some(own) = layout.abs(RECTOR) else {
        return Ok(());
    };
    let src_dir = own.join("src");
    if !src_dir.is_dir() {
        return Ok(());
    }
    let generated_dir = normalize_path(
        &absolute_install_path(layout, RECTOR)
            .map(|p| format!("{p}/src"))
            .unwrap_or_default(),
    );
    let mut data: BTreeMap<String, Value> = BTreeMap::new();
    for p in &packages {
        let extra_rector = p.raw.get("extra").and_then(|e| e.get("rector"));
        if p.package_type() != "rector-extension" && extra_rector.is_none() {
            continue;
        }
        let Some(install_path) = absolute_install_path(layout, p.name()) else {
            continue;
        };
        let mut entry = serde_json::Map::new();
        entry.insert("install_path".into(), Value::String(install_path.clone()));
        entry.insert(
            "relative_install_path".into(),
            Value::String(find_shortest_path(&generated_dir, &install_path, true)),
        );
        entry.insert("extra".into(), extra_rector.cloned().unwrap_or(Value::Null));
        entry.insert("version".into(), Value::String(full_pretty_version(p)));
        data.insert(p.name().to_owned(), Value::Object(entry));
    }
    let installed_names: Vec<String> = data.keys().cloned().collect();
    let mut o = serde_json::Map::new();
    for (k, v) in data {
        o.insert(k, v);
    }
    let contents = fill(RECTOR_TEMPLATE, &[php_var_export(&Value::Object(o), 0)]);
    if write_if_changed(&src_dir.join("GeneratedConfig.php"), &contents)? {
        vivacity_core::out!("rector/rector-installer: Extensions installed");
        for name in installed_names {
            vivacity_core::out!("> {name}: installed");
        }
    }
    Ok(())
}

/// `packages` in the local repository's `order` (names it does not hold
/// last, in their own order). After a fresh install Composer's own order
/// is that of its parallel extractions: vivacity writes the operations'.
pub fn in_order<'a>(mut packages: Vec<&'a LockPackage>, order: &[&str]) -> Vec<&'a LockPackage> {
    packages.sort_by_key(|p| {
        order
            .iter()
            .position(|n| *n == p.name())
            .unwrap_or(usize::MAX)
    });
    packages
}

/// infection's `Plugin::process` (`POST_INSTALL_CMD` / `POST_UPDATE_CMD`),
/// its lines included. An extension listed twice in the local repository
/// (an alias) was handed over by `scope` (`aliased_listing_issue`).
pub fn infection(
    layout: &Layout,
    local: &Lock,
    order: &[&str],
    manifest: &Value,
    with_dev: bool,
    plugins_enabled: bool,
) -> Result<()> {
    let packages = in_order(local.wanted_packages(with_dev).collect(), order);
    if !plugins_enabled
        || !packages.iter().any(|p| p.name() == INFECTION)
        || !matches!(plugin_allowed(manifest, INFECTION), PluginVerdict::Allowed)
    {
        return Ok(());
    }
    let Some(own) = layout.abs(INFECTION) else {
        return Ok(());
    };
    let src_dir = own.join("src");
    if !src_dir.is_dir() {
        return Ok(());
    }
    let mut data: BTreeMap<String, Value> = BTreeMap::new();
    // `$invalidInfectionExtensions[$name] = …`: keyed by name, in the
    // local repository's order (no sort).
    let mut invalid: Vec<&str> = Vec::new();
    for p in &packages {
        if p.package_type() != "infection-extension" {
            continue;
        }
        let extra = p.raw.get("extra").and_then(|e| e.get("infection"));
        // `$package->getExtra()['infection']['class'] ?? null`: absent,
        // `null`, or `extra.infection` not an array (a string offset that
        // `isset` refuses) — all null.
        let class = extra
            .filter(|e| e.is_object())
            .and_then(|e| e.get("class"))
            .filter(|c| !c.is_null());
        if class.is_none() {
            if !invalid.contains(&p.name()) {
                invalid.push(p.name());
            }
            continue;
        }
        let Some(install_path) = absolute_install_path(layout, p.name()) else {
            continue;
        };
        let mut entry = serde_json::Map::new();
        entry.insert("install_path".into(), Value::String(install_path));
        entry.insert("extra".into(), extra.cloned().unwrap_or(Value::Null));
        entry.insert("version".into(), Value::String(full_pretty_version(p)));
        data.insert(p.name().to_owned(), Value::Object(entry));
    }
    let installed_names: Vec<String> = data.keys().cloned().collect();
    let mut o = serde_json::Map::new();
    for (k, v) in data {
        o.insert(k, v);
    }
    let contents = fill(INFECTION_TEMPLATE, &[php_var_export(&Value::Object(o), 0)]);
    // `file_put_contents` every time; a byte-identical file is left as it
    // is (same contents, and the mtime is not compared).
    write_if_changed(&src_dir.join("GeneratedExtensionsConfig.php"), &contents)?;
    if installed_names.is_empty() && invalid.is_empty() {
        vivacity_core::out!("infection/extension-installer: No extensions found");
    }
    if !installed_names.is_empty() {
        vivacity_core::out!("infection/extension-installer: Extensions installed");
        for name in &installed_names {
            vivacity_core::out!("> {name}: installed");
        }
    }
    if !invalid.is_empty() {
        vivacity_core::out!("infection/extension-installer: Invalid extensions:");
        for name in invalid {
            vivacity_core::out!("> {name}. (`class` is not specified under `extra.infection` key)");
        }
    }
    Ok(())
}

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

    #[test]
    fn constraint_string_like_the_plugin() {
        let c = parse_constraints("^1.10").unwrap().constraint;
        assert_eq!(constraint_into_string(&c), ">=1.10.0.0-dev, <2.0.0.0-dev");
        let multi = Constraint::Multi {
            constraints: vec![
                parse_constraints("^1.10").unwrap().constraint,
                parse_constraints("^1.11.5").unwrap().constraint,
            ],
            conjunctive: true,
        };
        assert_eq!(
            constraint_into_string(&vivacity_resolver::intervals::compact_constraint(&multi)),
            ">=1.11.5.0-dev, <2.0.0.0-dev"
        );
    }

    #[test]
    fn an_ignored_package_is_listed_once_per_repository_entry() {
        let lock = Lock::parse(
            &serde_json::json!({"packages": [
                {"name": "a/plain", "version": "1.0.0", "type": "phpstan-extension"},
                {"name": "a/branch", "version": "dev-main", "type": "phpstan-extension",
                 "extra": {"branch-alias": {"dev-main": "1.0.x-dev"}}},
                {"name": "a/inline", "version": "1.0.0", "type": "phpstan-extension"},
            ], "packages-dev": [], "aliases": [
                {"package": "a/inline", "version": "1.0.0.0", "alias": "1.0.99", "alias_normalized": "1.0.99.0"},
            ]})
            .to_string(),
        )
        .unwrap();
        let count = |name: &str| {
            let p = lock.packages.iter().find(|p| p.name() == name).unwrap();
            local_repository_entries(p, &lock.aliases)
        };
        assert_eq!(count("a/plain"), 1);
        assert_eq!(count("a/branch"), 2);
        assert_eq!(count("a/inline"), 2);
    }

    #[test]
    fn sprintf_fill() {
        assert_eq!(fill("a %s b %s c", &["1".into(), "2".into()]), "a 1 b 2 c");
    }
}