vivacity-core 0.11.1

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
//! vendor/bin proxies: byte-for-byte port of
//! `BinaryInstaller::generateUnixyProxyCode` (docs/reference/BinaryInstaller.php).
//! Three shapes: PHP target with shebang (anti-shebang stream wrapper for
//! PHP<8, special phpunit hack), bare PHP target, non-PHP target (sh proxy).
//! Parity is held by the differential test against the proxies generated by
//! Composer in the Laravel fixture (tests/fixtures_binproxy.rs).

use crate::error::{Error, Result};
use crate::pathutil::{find_shortest_path, find_shortest_path_code, normalize_path};
use std::path::Path;

/// Generates the content of the proxy `link` (vendor/bin/<name>) to the binary
/// `bin` (absolute, inside vendor/ or outside it with composer/installers),
/// reading the target's header. Relative paths are those of
/// `BinaryInstaller::installUnixyProxyBinaries` (findShortestPath from the
/// proxy file).
pub fn proxy_content(vendor_dir: &Path, link: &Path, bin: &Path) -> Result<String> {
    let mut head = [0u8; 500];
    let n = {
        use std::io::Read as _;
        let mut f = std::fs::File::open(bin).map_err(Error::io(bin))?;
        f.read(&mut head).map_err(Error::io(bin))?
    };
    let head = String::from_utf8_lossy(&head[..n]);

    let link_s = link.to_string_lossy();
    let bin_s = bin.to_string_lossy();
    let vendor_s = vendor_dir.to_string_lossy();
    let bin_path = find_shortest_path(&link_s, &bin_s, false);
    let bin_exported = find_shortest_path_code(&link_s, &bin_s, false, true);
    let autoload_exported =
        find_shortest_path_code(&link_s, &format!("{vendor_s}/autoload.php"), false, true);

    match php_header(&head) {
        Some(PhpHeader { shebang }) => {
            let proxy_code = shebang
                .clone()
                .unwrap_or_else(|| "#!/usr/bin/env php".to_owned());
            let is_phpunit = normalize_path(&bin_s)
                == normalize_path(&format!("{vendor_s}/phpunit/phpunit/phpunit"));
            let mut globals = String::from("$GLOBALS['_composer_bin_dir'] = __DIR__;\n");
            globals.push_str(&format!(
                "$GLOBALS['_composer_autoload_path'] = {autoload_exported};\n"
            ));
            if is_phpunit {
                globals.push_str(&format!(
                    "$GLOBALS['__PHPUNIT_ISOLATION_EXCLUDE_LIST'] = $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'] = array(realpath({bin_exported}));\n"
                ));
            }
            // Stream wrapper only if the target does not start directly
            // with `<?php` (shebang or whitespace in front).
            let needs_stream = shebang.is_some() || !head.starts_with("<?php");
            let (stream_hint, stream_code) = if needs_stream {
                (
                    " using a stream wrapper to prevent the shebang from being output on PHP<8\n *"
                        .to_owned(),
                    stream_proxy_code(&bin_exported, is_phpunit),
                )
            } else {
                (String::new(), String::new())
            };
            Ok(format!(
                "{proxy_code}\n<?php\n\n/**\n * Proxy PHP file generated by Composer\n *\n * This file includes the referenced bin path ({bin_path})\n *{stream_hint}\n * @generated\n */\n\nnamespace Composer;\n\n{globals}\n{stream_code}\nreturn include {bin_exported};\n"
            ))
        }
        None => Ok(sh_proxy(&bin_path)),
    }
}

struct PhpHeader {
    shebang: Option<String>,
}

/// Composer's regex: `^(#!.*\r?\n)?[\r\n\t ]*<\?php`.
fn php_header(head: &str) -> Option<PhpHeader> {
    let (shebang, rest) = if head.starts_with("#!") {
        let end = head.find('\n')?;
        (
            Some(head[..end].trim_end_matches('\r').to_owned()),
            &head[end + 1..],
        )
    } else {
        (None, head)
    };
    let trimmed = rest.trim_start_matches(['\r', '\n', '\t', ' ']);
    trimmed
        .starts_with("<?php")
        .then_some(PhpHeader { shebang })
}

fn stream_proxy_code(bin_exported: &str, is_phpunit: bool) -> String {
    let hack1 = if is_phpunit {
        "'phpvfscomposer://'."
    } else {
        ""
    };
    let hack2 = if is_phpunit {
        "\n                $data = str_replace('__DIR__', var_export(dirname($this->realpath), true), $data);\n                $data = str_replace('__FILE__', var_export($this->realpath, true), $data);"
    } else {
        ""
    };
    format!(
        r#"if (PHP_VERSION_ID < 80000) {{
    if (!class_exists('Composer\BinProxyWrapper')) {{
        /**
         * @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 = {hack1}$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);
                }}{hack2}

                $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;
            }}
        }}
    }}

    if (
        (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true))
        || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper'))
    ) {{
        return include("phpvfscomposer://" . {bin_exported});
    }}
}}
"#
    )
}

fn sh_proxy(bin_path: &str) -> String {
    let dir = bin_path.rsplit_once('/').map(|(d, _)| d).unwrap_or(".");
    let file = bin_path
        .rsplit_once('/')
        .map(|(_, f)| f)
        .unwrap_or(bin_path);
    // ProcessExecutor::escape on a simple path = single quotes.
    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 '{dir}' && 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}}/{file}" "$@"
        return
    fi
fi

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

/// `BinaryInstaller::generateWindowsProxyCode`: a `.bat` whose target, for a
/// `php` caller, is the NEIGHBOURING unixy proxy (`%~dp0/<name>` =
/// `basename($link, '.bat')`) — the one that sets the
/// `$GLOBALS['_composer_*']` and includes the real binary. Any other caller
/// (`call` for a real `.bat`/`.exe` target, a non-php shebang such as `sh`,
/// or a shebang carrying arguments such as `php -dfoo`) targets the real
/// binary via `findShortestPath`. Composer wraps that path in
/// `trim(ProcessExecutor::escape(...), '"\'')`, which is the bare path again
/// for any path without embedded quotes — the simplification kept here.
/// Verified byte-for-byte against native Composer 2.10.3 on the psr/log +
/// monolog + nikic/php-parser fixture, and by real execution under a
/// Windows PHP (tests/fixtures_binproxy.rs).
pub fn windows_proxy_content(link_bat: &Path, link_name: &str, bin: &Path) -> Result<String> {
    let caller = windows_binary_caller(bin)?;
    let target = if caller == "php" {
        link_name.to_owned()
    } else {
        let link_s = link_bat.to_string_lossy();
        let bin_s = bin.to_string_lossy();
        find_shortest_path(&link_s, &bin_s, false)
    };
    Ok(format!(
        "@ECHO OFF\r\n\
         setlocal DISABLEDELAYEDEXPANSION\r\n\
         SET BIN_TARGET=%~dp0/{target}\r\n\
         SET COMPOSER_RUNTIME_BIN_DIR=%~dp0\r\n\
         {caller} \"%BIN_TARGET%\" %*\r\n"
    ))
}

/// `BinaryInstaller::determineBinaryCaller`: `call` for a `.bat` or `.exe`
/// target (`substr($bin, -4)` — case-sensitive, and NOT `.cmd`); otherwise
/// the shebang interpreter — everything after the last path segment,
/// arguments included (`#!/usr/bin/env php -dfoo` → `php -dfoo`); otherwise
/// `php`.
pub fn windows_binary_caller(bin: &Path) -> Result<String> {
    let bin_s = bin.to_string_lossy();
    if bin_s.ends_with(".bat") || bin_s.ends_with(".exe") {
        return Ok("call".to_owned());
    }
    // fgets($handle): the first line, unbounded, as bytes.
    let mut line = Vec::new();
    {
        use std::io::BufRead as _;
        let f = std::fs::File::open(bin).map_err(Error::io(bin))?;
        let mut reader = std::io::BufReader::new(f);
        reader
            .read_until(b'\n', &mut line)
            .map_err(Error::io(bin))?;
    }
    let line = String::from_utf8_lossy(&line);
    Ok(shebang_caller(&line).unwrap_or_else(|| "php".to_owned()))
}

/// The regex `{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m` of
/// `determineBinaryCaller`, applied to the first line: everything after the
/// last `/` is kept — arguments included — then `trim()`ed. Two details of
/// the reference are preserved: the shebang must start with `#!/` (a bare
/// `#!php` falls through to the `php` default), and the capture must be
/// non-empty, so on a line ending in `/` the backtracked capture keeps its
/// final `<segment>/`.
fn shebang_caller(line: &str) -> Option<String> {
    // `$` with the `m` flag matches before a final `\n`; a `\r` stays in the
    // capture and is removed by trim() below.
    let line = line.strip_suffix('\n').unwrap_or(line);
    let rest = line.strip_prefix("#!/")?;
    let rest = rest.strip_prefix("usr/bin/env ").unwrap_or(rest);
    // `(?:[^/]+/)*(.+)`: drop leading `<segment>/` pairs while a non-empty
    // capture remains — greedy with backtracking, like PCRE.
    let mut capture = rest;
    loop {
        match capture.find('/') {
            Some(i) if i > 0 && i + 1 < capture.len() => capture = &capture[i + 1..],
            _ => break,
        }
    }
    if capture.is_empty() {
        return None; // `(.+)` cannot match: no shebang interpreter
    }
    // PHP trim() default character set.
    Some(
        capture
            .trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B'])
            .to_owned(),
    )
}

/// The resolved `bin-compat`: `Full` writes the `.bat` proxy in addition to
/// the unixy proxy (`BinaryInstaller::installFullBinaries`), `Proxy` writes
/// the unixy proxy alone (`installUnixyProxyBinaries`) — which is what
/// Composer produces on plain Linux/macOS.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinCompat {
    Full,
    Proxy,
}

/// `Config::get('bin-compat')` + the resolution in
/// `BinaryInstaller::installBinaries` (2.10.3): the value comes from
/// `COMPOSER_BIN_COMPAT` (`?:` in `Config::get`, so `""` and `"0"` fall
/// through) else `config.bin-compat` of the root composer.json else the
/// global `COMPOSER_HOME/config.json` (`Config::merge` layers) else
/// `"auto"`, and resolves to `Full` iff it is `"full"`, or `"auto"` on
/// Windows or WSL (`Platform::isWindows() ||
/// Platform::isWindowsSubsystemForLinux()`).
pub fn resolve_bin_compat(root_manifest: &serde_json::Value) -> Result<BinCompat> {
    let env = std::env::var("COMPOSER_BIN_COMPAT").ok();
    let global = crate::layout::global_config_value("bin-compat");
    resolve_bin_compat_with(
        env.as_deref(),
        root_manifest,
        global.as_ref(),
        cfg!(windows) || is_windows_subsystem_for_linux(),
    )
}

/// Pure core of [`resolve_bin_compat`], for tests: `env` is the
/// `COMPOSER_BIN_COMPAT` override, `global` the `config.bin-compat` of
/// the global config.json, `windows_or_wsl` the platform predicate.
/// An unknown value is refused with Composer's own message; the deprecated
/// `"symlink"` is accepted and behaves like `"proxy"` (Composer deprecation-
/// warns then takes the non-full branch — vivacity never symlinks anyway).
pub fn resolve_bin_compat_with(
    env: Option<&str>,
    root_manifest: &serde_json::Value,
    global: Option<&serde_json::Value>,
    windows_or_wsl: bool,
) -> Result<BinCompat> {
    // PHP `?:`: an empty string and "0" are falsy.
    let env = env.filter(|v| !v.is_empty() && *v != "0");
    let config = root_manifest
        .get("config")
        .and_then(|c| c.get("bin-compat"))
        .and_then(serde_json::Value::as_str)
        .or_else(|| global.and_then(serde_json::Value::as_str));
    let value = env.or(config).unwrap_or("auto");
    match value {
        "full" => Ok(BinCompat::Full),
        "auto" if windows_or_wsl => Ok(BinCompat::Full),
        "auto" | "proxy" | "symlink" => Ok(BinCompat::Proxy),
        other => Err(Error::Unsupported(format!(
            "Invalid value for 'bin-compat': {other}. Expected auto, full or proxy"
        ))),
    }
}

/// `Platform::isWindowsSubsystemForLinux` (2.10.3): never on Windows itself;
/// otherwise `/proc/version` readable and containing "microsoft"
/// (case-insensitive), and not inside a container — Docker/Podman running
/// inside WSL must not count as WSL. The reference also bails out under
/// PHP's `open_basedir`, which has no analog here.
fn is_windows_subsystem_for_linux() -> bool {
    if cfg!(windows) {
        return false;
    }
    let Ok(version) = std::fs::read_to_string("/proc/version") else {
        return false;
    };
    version.to_ascii_lowercase().contains("microsoft") && !is_docker()
}

/// `Platform::isDocker` (2.10.3): the container marker files, then the
/// cgroup/mountinfo markers.
fn is_docker() -> bool {
    if [
        "/.dockerenv",
        "/run/.containerenv",
        "/var/run/.containerenv",
    ]
    .iter()
    .any(|p| Path::new(p).exists())
    {
        return true;
    }
    ["/proc/self/mountinfo", "/proc/1/cgroup"].iter().any(|p| {
        std::fs::read_to_string(p).is_ok_and(|data| {
            data.contains("/var/lib/docker/") || data.contains("/io.containerd.snapshotter")
        })
    })
}

/// Installs a package's proxies (laid out in `package_dir`) into the bin
/// directory (`config.bin-dir`, 0755), following the resolved [`BinCompat`]
/// exactly as `BinaryInstaller::installBinaries` does: `Full` (bin-compat
/// `"full"`, or `"auto"` on Windows/WSL) goes through
/// [`install_full_binaries`]; `Proxy` writes the unixy proxy alone.
/// vivacity always writes proxies (never symlinks), which is Composer's own
/// proxy mode. An existing regular file at the link's place is kept (a
/// project-owned `bin/console`, say): Composer skips that bin with
/// `Skipped installation of bin <bin> for package <name>: name conflicts
/// with an existing file` — printed on an install or update
/// (`warnOnOverwrite`), silent on the `ensureBinariesPresence` pass. The
/// messages are returned for the caller to print.
pub fn install_binaries(
    vendor_dir: &Path,
    bin_dir: &Path,
    package: &str,
    package_dir: &Path,
    bins: &[&str],
    compat: BinCompat,
    warn_on_overwrite: bool,
) -> Result<Vec<String>> {
    std::fs::create_dir_all(bin_dir).map_err(Error::io(bin_dir))?;
    let mut skipped = Vec::new();
    for declared in bins {
        let bin = declared.trim_start_matches("./");
        let target = package_dir.join(bin);
        let link_name = bin.rsplit_once('/').map(|(_, f)| f).unwrap_or(bin);
        let link = bin_dir.join(link_name);
        if !target.exists() {
            continue; // binary declared but missing from the dist: Composer skips it too
        }
        if let Ok(meta) = std::fs::symlink_metadata(&link) {
            if !meta.file_type().is_symlink() {
                if warn_on_overwrite {
                    skipped.push(format!(
                        "    Skipped installation of bin {declared} for package {package}: name conflicts with an existing file"
                    ));
                }
                continue;
            }
            // A symlink (Composer's pre-2.2 mode, or a user's): replaced.
            std::fs::remove_file(&link).map_err(Error::io(&link))?;
        }
        match compat {
            BinCompat::Full => install_full_binaries(vendor_dir, &link, link_name, &target)?,
            BinCompat::Proxy => install_unixy_proxy(vendor_dir, &link, &target)?,
        }
        // `chmod($binPath, 0777 & ~umask())`: the package's own binary is
        // made executable (a dist extracted without its modes gets them
        // here; a mirrored path package too).
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = umask_mode_0777(bin_dir)?;
            std::fs::set_permissions(&target, std::fs::Permissions::from_mode(mode))
                .map_err(Error::io(&target))?;
        }
    }
    Ok(skipped)
}

/// `BinaryInstaller::removeBinaries`: the package's links (and their
/// `.bat`) unlinked whatever they are; the bin directory removed when it
/// ends up empty (only when the package declared binaries).
pub fn remove_binaries(bin_dir: &Path, bins: &[&str]) -> Result<()> {
    if bins.is_empty() {
        return Ok(());
    }
    for bin in bins {
        let bin = bin.trim_start_matches("./");
        let link_name = bin.rsplit_once('/').map(|(_, f)| f).unwrap_or(bin);
        for p in [
            bin_dir.join(link_name),
            bin_dir.join(format!("{link_name}.bat")),
        ] {
            match std::fs::remove_file(&p) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(Error::io(&p)(e)),
            }
        }
    }
    remove_bin_dir_if_empty(bin_dir)
}

/// `is_dir($binDir) && isDirEmpty($binDir)` → `rmdir`.
pub fn remove_bin_dir_if_empty(bin_dir: &Path) -> Result<()> {
    if let Ok(mut entries) = std::fs::read_dir(bin_dir) {
        if entries.next().is_none() {
            std::fs::remove_dir(bin_dir).map_err(Error::io(bin_dir))?;
        }
    }
    Ok(())
}

/// `0777 & ~umask()` without libc: the mode a file created with 0777 gets.
#[cfg(unix)]
fn umask_mode_0777(dir: &Path) -> Result<u32> {
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    let probe = dir.join(format!(".vivacity-umask-{}", std::process::id()));
    let f = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o777)
        .open(&probe)
        .map_err(Error::io(&probe))?;
    let mode = f
        .metadata()
        .map_err(Error::io(&probe))?
        .permissions()
        .mode()
        & 0o777;
    drop(f);
    let _ = std::fs::remove_file(&probe);
    Ok(mode)
}

/// `BinaryInstaller::installFullBinaries`: a real `.bat` target
/// (`substr($binPath, -4)`, case-sensitive) gets ONLY the windows proxy, at
/// the link itself; any other target gets the unixy proxy plus a
/// `<name>.bat` — which is SKIPPED when it already exists (Composer:
/// "Skipped installation of bin <bin>.bat proxy for package <name>: a .bat
/// proxy was already installed").
fn install_full_binaries(
    vendor_dir: &Path,
    link: &Path,
    link_name: &str,
    target: &Path,
) -> Result<()> {
    let bat = if target.to_string_lossy().ends_with(".bat") {
        link.to_path_buf()
    } else {
        install_unixy_proxy(vendor_dir, link, target)?;
        link.with_file_name(format!("{link_name}.bat"))
    };
    if !bat.exists() {
        let content = windows_proxy_content(&bat, link_name, target)?;
        std::fs::write(&bat, content).map_err(Error::io(&bat))?;
        set_executable(&bat)?;
    }
    Ok(())
}

/// `BinaryInstaller::installUnixyProxyBinaries`.
fn install_unixy_proxy(vendor_dir: &Path, link: &Path, target: &Path) -> Result<()> {
    let content = proxy_content(vendor_dir, link, target)?;
    std::fs::write(link, content).map_err(Error::io(link))?;
    set_executable(link)
}

/// `Silencer::call('chmod', $link, 0777 & ~umask())` — 0755 under the usual
/// umask; a no-op on Windows.
fn set_executable(link: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::set_permissions(link, std::fs::Permissions::from_mode(0o755))
            .map_err(Error::io(link))?;
    }
    #[cfg(not(unix))]
    let _ = link;
    Ok(())
}