composer-install 0.6.1

Install a resolved composer.lock into a project: download + verify + extract dists in parallel, materialize path packages, apply patches, run the declarative install plugins, dump the autoloader, and link vendor/bin — without running PHP. The pubgrub solver is out of scope; this is the install-from-lock half.
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
//! Composer-compatible `vendor/bin/` proxy script generation.
//!
//! Matches Composer 2.8's `BinaryInstaller` behavior: PHP binaries get a PHP
//! proxy that sets `$GLOBALS['_composer_bin_dir']` and
//! `$GLOBALS['_composer_autoload_path']`; non-PHP binaries get a shell proxy
//! that resolves paths and sets `COMPOSER_RUNTIME_BIN_DIR`.

use std::path::Path;

use composer_manifest::lockfile::LockPackage;

#[derive(Debug, Clone, Default)]
pub(crate) struct BinSummary {
    pub(crate) bins_installed: u32,
    pub(crate) warnings: Vec<String>,
}

pub(crate) fn install_bin_proxies(project_root: &Path, packages: &[&LockPackage]) -> BinSummary {
    let bin_dir = project_root.join("vendor/bin");
    let mut summary = BinSummary::default();

    for pkg in packages {
        if pkg.bin.is_empty() {
            continue;
        }
        for bin in &pkg.bin {
            let target = project_root.join("vendor").join(&pkg.name).join(bin);
            let Some(base) = Path::new(bin).file_name() else {
                summary.warnings.push(format!(
                    "skipped bin `{bin}` for {}: invalid path",
                    pkg.name
                ));
                continue;
            };
            let link_name = base.to_string_lossy().into_owned();

            if !target.exists() {
                summary.warnings.push(format!(
                    "skipped installation of bin `{bin}` for package {}: \
                     file not found in package",
                    pkg.name,
                ));
                continue;
            }
            if target.is_dir() {
                summary.warnings.push(format!(
                    "skipped installation of bin `{bin}` for package {}: \
                     found a directory at that path",
                    pkg.name,
                ));
                continue;
            }

            let link_path = bin_dir.join(&link_name);
            if link_path.exists() && !is_composer_proxy(&link_path) {
                summary.warnings.push(format!(
                    "skipped installation of bin `{bin}` for package {}: \
                     name conflicts with an existing file",
                    pkg.name,
                ));
                continue;
            }

            if let Err(e) = std::fs::create_dir_all(&bin_dir) {
                summary.warnings.push(format!(
                    "skipped bin `{bin}` for {}: cannot create vendor/bin: {e}",
                    pkg.name,
                ));
                continue;
            }

            let bin_type = detect_bin_type(&target);
            let is_phpunit = pkg.name == "phpunit/phpunit" && bin == "phpunit";
            let proxy_content = match bin_type {
                BinType::PhpPlain => generate_php_proxy(&pkg.name, bin, false, is_phpunit),
                BinType::PhpShebang => generate_php_proxy(&pkg.name, bin, true, is_phpunit),
                BinType::Other => generate_shell_proxy(&pkg.name, bin),
            };

            if let Err(e) = std::fs::write(&link_path, proxy_content) {
                summary
                    .warnings
                    .push(format!("failed to write bin proxy for {}: {e}", pkg.name));
                continue;
            }

            set_executable(&link_path);
            set_executable(&target);
            summary.bins_installed += 1;
        }
    }
    summary
}

#[allow(dead_code)]
pub(crate) fn remove_bin_proxies(project_root: &Path, packages: &[&LockPackage]) {
    let bin_dir = project_root.join("vendor/bin");
    if !bin_dir.is_dir() {
        return;
    }
    for pkg in packages {
        for bin in &pkg.bin {
            let Some(name) = Path::new(bin).file_name() else {
                continue;
            };
            let link = bin_dir.join(name);
            if link.exists() || link.symlink_metadata().is_ok() {
                let _ = std::fs::remove_file(&link);
            }
            let bat = bin_dir.join(format!("{}.bat", name.to_string_lossy()));
            if bat.exists() {
                let _ = std::fs::remove_file(&bat);
            }
        }
    }
    if bin_dir.is_dir() && is_dir_empty(&bin_dir) {
        let _ = std::fs::remove_dir(&bin_dir);
    }
}

fn is_dir_empty(path: &Path) -> bool {
    path.read_dir().is_ok_and(|mut d| d.next().is_none())
}

// --- Binary type detection ---

enum BinType {
    PhpPlain,
    PhpShebang,
    Other,
}

fn detect_bin_type(path: &Path) -> BinType {
    let Ok(content) = read_head(path, 500) else {
        return BinType::PhpPlain;
    };
    let s = String::from_utf8_lossy(&content);
    let has_shebang = s.starts_with("#!");
    if has_shebang {
        let after_shebang = s.find('\n').map_or("", |pos| &s[pos + 1..]);
        let is_php = after_shebang
            .trim_start_matches(['\r', '\n', '\t', ' '])
            .starts_with("<?php");
        if is_php {
            return BinType::PhpShebang;
        }
        return BinType::Other;
    }
    let trimmed = s.trim_start_matches(['\r', '\n', '\t', ' ']);
    if trimmed.starts_with("<?php") {
        BinType::PhpPlain
    } else {
        BinType::Other
    }
}

fn read_head(path: &Path, max_bytes: usize) -> std::io::Result<Vec<u8>> {
    use std::io::Read;
    let mut f = std::fs::File::open(path)?;
    let mut buf = vec![0u8; max_bytes];
    let n = f.read(&mut buf)?;
    buf.truncate(n);
    Ok(buf)
}

// --- Proxy script generation ---

fn generate_php_proxy(
    package_name: &str,
    bin_path: &str,
    has_shebang: bool,
    is_phpunit: bool,
) -> String {
    let rel = format!("/{package_name}/{bin_path}");
    let bin_path_comment = format!("../{package_name}/{bin_path}");

    let mut lines: Vec<String> = Vec::new();
    lines.push("#!/usr/bin/env php".into());
    lines.push("<?php".into());
    lines.push(String::new());
    lines.push("/**".into());
    lines.push(" * Proxy PHP file generated by Composer".into());
    lines.push(" *".into());
    if has_shebang {
        lines.push(format!(
            " * This file includes the referenced bin path ({bin_path_comment})"
        ));
        lines.push(
            " * using a stream wrapper to prevent the shebang from being output on PHP<8".into(),
        );
    } else {
        lines.push(format!(
            " * This file includes the referenced bin path ({bin_path_comment})"
        ));
    }
    lines.push(" *".into());
    lines.push(" * @generated".into());
    lines.push(" */".into());
    lines.push(String::new());
    lines.push("namespace Composer;".into());
    lines.push(String::new());
    lines.push("$GLOBALS['_composer_bin_dir'] = __DIR__;".into());
    lines.push("$GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php';".into());

    if is_phpunit {
        lines.push(format!(
            "$GLOBALS['__PHPUNIT_ISOLATION_EXCLUDE_LIST'] = \
             $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'] = \
             array(realpath(__DIR__ . '/..'.'{rel}'));"
        ));
    }

    if has_shebang {
        lines.push(String::new());
        lines.push("if (PHP_VERSION_ID < 80000) {".into());
        lines.push("    if (!class_exists('Composer\\BinProxyWrapper')) {".into());
        lines.push(BIN_PROXY_WRAPPER_CLASS.into());
        lines.push("    }".into());
        lines.push(String::new());
        lines.push("    if (".into());
        lines.push("        (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true))".into());
        lines.push("        || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\\BinProxyWrapper'))".into());
        lines.push("    ) {".into());
        lines.push(format!(
            "        return include(\"phpvfscomposer://\" . __DIR__ . '/..'.'{rel}');"
        ));
        lines.push("    }".into());
        lines.push("}".into());
    }

    lines.push(String::new());
    lines.push(format!("return include __DIR__ . '/..'.'{rel}';"));
    lines.push(String::new());

    lines.join("\n")
}

const BIN_PROXY_WRAPPER_CLASS: &str = r"        /**
         * @internal
         */
        final class BinProxyWrapper
        {
            private $handle;
            private $position;
            private $realpath;

            public function stream_open($path, $mode, $options, &$opened_path)
            {
                // get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
                $opened_path = substr($path, 17);
                $this->realpath = realpath($opened_path) ?: $opened_path;
                $opened_path = 'phpvfscomposer://'.$this->realpath;
                $this->handle = fopen($this->realpath, $mode);
                $this->position = 0;

                return (bool) $this->handle;
            }

            public function stream_read($count)
            {
                $data = fread($this->handle, $count);

                if ($this->position === 0) {
                    $data = preg_replace('{^#!.*\r?\n}', '', $data);
                }
                $data = str_replace('__DIR__', var_export(dirname($this->realpath), true), $data);
                $data = str_replace('__FILE__', var_export($this->realpath, true), $data);

                $this->position += strlen($data);

                return $data;
            }

            public function stream_cast($castAs)
            {
                return $this->handle;
            }

            public function stream_close()
            {
                fclose($this->handle);
            }

            public function stream_lock($operation)
            {
                return $operation ? flock($this->handle, $operation) : true;
            }

            public function stream_seek($offset, $whence)
            {
                if (0 === fseek($this->handle, $offset, $whence)) {
                    $this->position = ftell($this->handle);
                    return true;
                }

                return false;
            }

            public function stream_tell()
            {
                return $this->position;
            }

            public function stream_eof()
            {
                return feof($this->handle);
            }

            public function stream_stat()
            {
                return array();
            }

            public function stream_set_option($option, $arg1, $arg2)
            {
                return true;
            }

            public function url_stat($path, $flags)
            {
                $path = substr($path, 17);
                if (file_exists($path)) {
                    return stat($path);
                }

                return false;
            }
        }";

fn generate_shell_proxy(package_name: &str, bin_path: &str) -> String {
    let bin_file = Path::new(bin_path)
        .file_name()
        .unwrap_or_default()
        .to_string_lossy();
    let bin_dir_rel = Path::new(bin_path)
        .parent()
        .filter(|p| *p != Path::new(""))
        .map(|p| format!("'../{package_name}/{}'", p.display()))
        .unwrap_or_else(|| format!("'../{package_name}'"));

    format!(
        r#"#!/usr/bin/env sh

# Support bash to support `source` with fallback on $0 if this does not run with bash
# https://stackoverflow.com/a/35006505/6512
selfArg="$BASH_SOURCE"
if [ -z "$selfArg" ]; then
    selfArg="$0"
fi

self=$(realpath "$selfArg" 2> /dev/null)
if [ -z "$self" ]; then
    self="$selfArg"
fi

dir=$(cd "${{self%[/\\]*}}" > /dev/null; cd {bin_dir_rel} && pwd)

if [ -d /proc/cygdrive ]; then
    case $(which php) in
        $(readlink -n /proc/cygdrive)/*)
            # We are in Cygwin using Windows php, so the path must be translated
            dir=$(cygpath -m "$dir");
            ;;
    esac
fi

export COMPOSER_RUNTIME_BIN_DIR="$(cd "${{self%[/\\]*}}" > /dev/null; pwd)"

# If bash is sourcing this file, we have to source the target as well
bashSource="$BASH_SOURCE"
if [ -n "$bashSource" ]; then
    if [ "$bashSource" != "$0" ]; then
        source "${{dir}}/{bin_file}" "$@"
        return
    fi
fi

exec "${{dir}}/{bin_file}" "$@"
"#
    )
}

fn is_composer_proxy(path: &Path) -> bool {
    let Ok(content) = read_head(path, 200) else {
        return false;
    };
    let s = String::from_utf8_lossy(&content);
    s.contains("Proxy PHP file generated by Composer")
        || s.contains("COMPOSER_RUNTIME_BIN_DIR")
        || path
            .symlink_metadata()
            .is_ok_and(|m| m.file_type().is_symlink())
}

#[cfg(unix)]
fn set_executable(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    if let Ok(meta) = path.metadata() {
        let mode = meta.permissions().mode() | 0o111;
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
    }
}

#[cfg(not(unix))]
fn set_executable(_path: &Path) {}

#[cfg(test)]
mod tests;