- docs/macos.md: step-by-step setup for a fresh Apple Silicon Mac (Xcode CLT, Homebrew, git, PHP, Composer, Node 22, pnpm, rustup, clone from Forgejo), the machine report, Gatekeeper notes, macOS differences and what Windows cannot check. - cargo xtask mac-report: versions, the gate steps, the bundled-UI desktop build and a self-check over the control channel (project, file, Phpactor, hover, git.status, terminal, screenshot, quit); every step times out and runs in a lutra_proc group; one report.md to send back. - Fixes: macOS native menu (system menus only; Cmd+W stays buffer.close, Cmd+Q runs app.quit), xcap screenshot region in points on macOS (Retina), login shell (-l, /bin/zsh fallback) and LANG for the terminal on macOS, PHP lookup in Homebrew/MacPorts dirs for Finder starts, case-insensitive LSP path mapping on macOS, rendezvous file mode re-set to 0600, CLI-started desktop in its own process group. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
422 lines
14 KiB
Rust
422 lines
14 KiB
Rust
//! Finding the user's PHP and checking its version.
|
|
//!
|
|
//! Lutra does not ship PHP (owner decision D15). The executable comes from
|
|
//! the `php.executable` setting or from `PATH`; [`detect`] runs `php -v`
|
|
//! with a timeout and parses the first line. The output is untrusted: it is
|
|
//! read with a size cap, and anything that does not look like a PHP
|
|
//! version line is an error, never a crash.
|
|
|
|
use std::ffi::OsString;
|
|
use std::fmt;
|
|
use std::io::Read;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::{Command, Stdio};
|
|
use std::sync::mpsc;
|
|
use std::time::{Duration, Instant};
|
|
|
|
/// Oldest PHP the pinned Phpactor release runs on
|
|
/// ([`super::phpactor::VERSION`] declares `"php": "^8.2"` in its
|
|
/// `composer.json`).
|
|
pub const MIN_VERSION: PhpVersion = PhpVersion {
|
|
major: 8,
|
|
minor: 2,
|
|
patch: 0,
|
|
};
|
|
|
|
/// How long `php -v` may take.
|
|
pub const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
|
|
|
/// Most bytes of `php -v` output that are read.
|
|
pub const MAX_OUTPUT: u64 = 64 * 1024;
|
|
|
|
/// A PHP version, `major.minor.patch`.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
pub struct PhpVersion {
|
|
/// Major version, e.g. 8.
|
|
pub major: u32,
|
|
/// Minor version, e.g. 4.
|
|
pub minor: u32,
|
|
/// Patch level, e.g. 24; 0 when the output had none.
|
|
pub patch: u32,
|
|
}
|
|
|
|
impl fmt::Display for PhpVersion {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
|
|
}
|
|
}
|
|
|
|
/// A PHP executable that runs and is new enough.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Php {
|
|
/// The executable.
|
|
pub path: PathBuf,
|
|
/// Its version.
|
|
pub version: PhpVersion,
|
|
}
|
|
|
|
/// Why no usable PHP was found.
|
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
|
pub enum PhpError {
|
|
/// Neither the setting nor `PATH` names an existing executable.
|
|
#[error("{0}")]
|
|
NotFound(String),
|
|
/// The executable could not be run, timed out or failed.
|
|
#[error("{path}: {reason}")]
|
|
Failed {
|
|
/// The executable.
|
|
path: PathBuf,
|
|
/// What went wrong.
|
|
reason: String,
|
|
},
|
|
/// `php -v` did not print a PHP version line.
|
|
#[error("{path}: no PHP version in the output of php -v")]
|
|
NoVersion {
|
|
/// The executable.
|
|
path: PathBuf,
|
|
},
|
|
/// The version is older than [`MIN_VERSION`].
|
|
#[error("{path} is PHP {version}; Phpactor needs PHP {MIN_VERSION} or newer")]
|
|
TooOld {
|
|
/// The executable.
|
|
path: PathBuf,
|
|
/// Its version.
|
|
version: PhpVersion,
|
|
},
|
|
}
|
|
|
|
impl PhpError {
|
|
/// The executable the error is about, if one was found.
|
|
pub fn path(&self) -> Option<&Path> {
|
|
match self {
|
|
Self::NotFound(_) => None,
|
|
Self::Failed { path, .. } | Self::NoVersion { path } | Self::TooOld { path, .. } => {
|
|
Some(path)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The version found, for [`PhpError::TooOld`].
|
|
pub fn version(&self) -> Option<PhpVersion> {
|
|
match self {
|
|
Self::TooOld { version, .. } => Some(*version),
|
|
_ => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Finds PHP and checks it: the `setting` (`php.executable`; empty means
|
|
/// look in `PATH`, see [`search_path`]), resolved with [`locate`], then
|
|
/// `php -v` with [`PROBE_TIMEOUT`].
|
|
///
|
|
/// # Errors
|
|
/// [`PhpError`] saying what is missing or wrong.
|
|
pub fn detect(setting: &str) -> Result<Php, PhpError> {
|
|
let path = locate(setting, search_path(std::env::var_os("PATH")))?;
|
|
let output = run_version(&path, PROBE_TIMEOUT)?;
|
|
let version =
|
|
parse_version(&output).ok_or_else(|| PhpError::NoVersion { path: path.clone() })?;
|
|
if version < MIN_VERSION {
|
|
return Err(PhpError::TooOld { path, version });
|
|
}
|
|
Ok(Php { path, version })
|
|
}
|
|
|
|
/// Package manager folders searched after `PATH` on macOS: Homebrew on
|
|
/// Apple Silicon, Homebrew on Intel and MacPorts.
|
|
pub const MACOS_EXTRA_DIRS: [&str; 3] = ["/opt/homebrew/bin", "/usr/local/bin", "/opt/local/bin"];
|
|
|
|
/// The directories PHP is looked up in: `path_env`, and on macOS
|
|
/// [`MACOS_EXTRA_DIRS`] after it. An app started from the Finder or Dock
|
|
/// inherits only the system `PATH` (`/usr/bin:/bin:/usr/sbin:/sbin`), which
|
|
/// has no PHP since macOS 12, so Homebrew's PHP would not be found although
|
|
/// it works in Terminal.
|
|
pub fn search_path(path_env: Option<OsString>) -> Option<OsString> {
|
|
if !cfg!(target_os = "macos") {
|
|
return path_env;
|
|
}
|
|
with_extra_dirs(path_env, &MACOS_EXTRA_DIRS)
|
|
}
|
|
|
|
/// `path_env` with `extra` appended, skipping folders it lists already.
|
|
/// `None` only if both are empty; a `PATH` that cannot be joined again
|
|
/// (an entry with the separator in it) is returned unchanged.
|
|
fn with_extra_dirs(path_env: Option<OsString>, extra: &[&str]) -> Option<OsString> {
|
|
let mut dirs: Vec<PathBuf> = path_env
|
|
.as_ref()
|
|
.map(|p| std::env::split_paths(p).collect())
|
|
.unwrap_or_default();
|
|
for dir in extra {
|
|
if !dirs.iter().any(|d| d == Path::new(dir)) {
|
|
dirs.push(PathBuf::from(dir));
|
|
}
|
|
}
|
|
if dirs.is_empty() {
|
|
return path_env;
|
|
}
|
|
std::env::join_paths(dirs).ok().or(path_env)
|
|
}
|
|
|
|
/// Resolves the PHP executable.
|
|
///
|
|
/// - `setting` is the `php.executable` value, trimmed. A value with a path
|
|
/// separator must name an existing file. A bare name (`php8.3`) is looked
|
|
/// up in `path_env` like the default.
|
|
/// - Empty: `php` is looked up in `path_env` (on Windows `php.exe`, then
|
|
/// `php.bat` and `php.cmd`).
|
|
///
|
|
/// # Errors
|
|
/// [`PhpError::NotFound`] with a message naming the setting.
|
|
pub fn locate(setting: &str, path_env: Option<OsString>) -> Result<PathBuf, PhpError> {
|
|
let setting = setting.trim();
|
|
if setting.contains(['/', '\\']) {
|
|
let path = PathBuf::from(setting);
|
|
return if path.is_file() {
|
|
Ok(path)
|
|
} else {
|
|
Err(PhpError::NotFound(format!(
|
|
"php.executable {setting} is not a file"
|
|
)))
|
|
};
|
|
}
|
|
let name = if setting.is_empty() { "php" } else { setting };
|
|
let dirs = path_env
|
|
.map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
|
|
.unwrap_or_default();
|
|
dirs.iter()
|
|
.flat_map(|dir| candidates(name).into_iter().map(move |n| dir.join(n)))
|
|
.find(|p| p.is_file())
|
|
.ok_or_else(|| {
|
|
PhpError::NotFound(format!(
|
|
"{name} was not found in PATH; install PHP {MIN_VERSION} or newer or set php.executable"
|
|
))
|
|
})
|
|
}
|
|
|
|
/// File names that run `name` on this platform.
|
|
fn candidates(name: &str) -> Vec<String> {
|
|
if cfg!(windows) && !name.contains('.') {
|
|
["exe", "bat", "cmd"]
|
|
.iter()
|
|
.map(|ext| format!("{name}.{ext}"))
|
|
.collect()
|
|
} else {
|
|
vec![name.to_string()]
|
|
}
|
|
}
|
|
|
|
/// Runs `path -v` and returns at most [`MAX_OUTPUT`] bytes of its standard
|
|
/// output, killing it after `timeout`. On Windows no console window opens.
|
|
///
|
|
/// # Errors
|
|
/// [`PhpError::Failed`] if it cannot start, times out or exits with an
|
|
/// error.
|
|
pub fn run_version(path: &Path, timeout: Duration) -> Result<Vec<u8>, PhpError> {
|
|
let failed = |reason: String| PhpError::Failed {
|
|
path: path.to_path_buf(),
|
|
reason,
|
|
};
|
|
let mut command = Command::new(path);
|
|
command
|
|
.arg("-v")
|
|
.stdin(Stdio::null())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::null());
|
|
hide_window(&mut command);
|
|
let mut child = lutra_proc::spawn(command).map_err(|e| failed(e.to_string()))?;
|
|
let stdout = child
|
|
.stdout
|
|
.take()
|
|
.ok_or_else(|| failed("no output pipe".into()))?;
|
|
let (tx, rx) = mpsc::channel();
|
|
std::thread::Builder::new()
|
|
.name("lutra-php-probe".into())
|
|
.spawn(move || {
|
|
let mut out = Vec::new();
|
|
let _ = stdout.take(MAX_OUTPUT).read_to_end(&mut out);
|
|
let _ = tx.send(out);
|
|
})
|
|
.map_err(|e| failed(e.to_string()))?;
|
|
let started = Instant::now();
|
|
let deadline = started.checked_add(timeout).unwrap_or(started);
|
|
let status = loop {
|
|
match child.try_wait() {
|
|
Ok(Some(status)) => break status,
|
|
Ok(None) if Instant::now() >= deadline => {
|
|
let _ = child.kill_and_wait();
|
|
return Err(failed(format!(
|
|
"php -v did not finish within {} s",
|
|
timeout.as_secs()
|
|
)));
|
|
}
|
|
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
|
|
Err(e) => return Err(failed(e.to_string())),
|
|
}
|
|
};
|
|
let out = rx
|
|
.recv_timeout(Duration::from_secs(1))
|
|
.map_err(|_| failed("its output did not end".into()))?;
|
|
if !status.success() {
|
|
return Err(failed(format!("php -v exited with {status}")));
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Keeps a console window from flashing up when a GUI app runs PHP on
|
|
/// Windows (`CREATE_NO_WINDOW`).
|
|
#[cfg(windows)]
|
|
fn hide_window(command: &mut Command) {
|
|
use std::os::windows::process::CommandExt;
|
|
command.creation_flags(0x0800_0000);
|
|
}
|
|
|
|
/// Nothing to hide outside Windows.
|
|
#[cfg(not(windows))]
|
|
fn hide_window(_command: &mut Command) {}
|
|
|
|
/// Finds the version in `php -v` output: the first line that starts with
|
|
/// `PHP ` followed by `major.minor` and optionally `.patch`, such as
|
|
/// `PHP 8.4.24 (cli) (built: …)` or `PHP 8.3.6-1ubuntu1 (cli)`. Lines before
|
|
/// it (startup warnings) are skipped. Numbers that overflow, missing parts
|
|
/// and invalid UTF-8 give `None` or are skipped, never a panic.
|
|
pub fn parse_version(output: &[u8]) -> Option<PhpVersion> {
|
|
let text = String::from_utf8_lossy(output);
|
|
text.lines().find_map(|line| {
|
|
let rest = line.trim_start().strip_prefix("PHP ")?;
|
|
let token = rest.split_whitespace().next()?;
|
|
let mut parts = token.splitn(3, '.');
|
|
let major = number(parts.next()?)?;
|
|
let minor = number(parts.next()?)?;
|
|
let patch = match parts.next() {
|
|
Some(p) => number(p)?,
|
|
None => 0,
|
|
};
|
|
Some(PhpVersion {
|
|
major,
|
|
minor,
|
|
patch,
|
|
})
|
|
})
|
|
}
|
|
|
|
/// The leading decimal digits of `part` as a number; `None` without digits
|
|
/// or on overflow.
|
|
fn number(part: &str) -> Option<u32> {
|
|
let end = part
|
|
.char_indices()
|
|
.find(|(_, c)| !c.is_ascii_digit())
|
|
.map_or(part.len(), |(i, _)| i);
|
|
part.get(..end)?.parse().ok()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use proptest::prelude::*;
|
|
|
|
use super::*;
|
|
|
|
fn v(major: u32, minor: u32, patch: u32) -> Option<PhpVersion> {
|
|
Some(PhpVersion {
|
|
major,
|
|
minor,
|
|
patch,
|
|
})
|
|
}
|
|
|
|
#[test]
|
|
fn parses_real_outputs() {
|
|
let windows = b"PHP 8.4.24 (cli) (built: Jul 29 2026 06:00:56) (ZTS Visual C++ 2022 x64)\r\nCopyright (c) The PHP Group\r\nZend Engine v4.4.24\r\n";
|
|
assert_eq!(parse_version(windows), v(8, 4, 24));
|
|
assert_eq!(
|
|
parse_version(b"PHP 8.3.6-1ubuntu1.2 (cli) (built: Jan 1 2026)"),
|
|
v(8, 3, 6)
|
|
);
|
|
assert_eq!(parse_version(b"PHP 8.5.0-dev (cli)"), v(8, 5, 0));
|
|
assert_eq!(
|
|
parse_version(b"PHP Warning: Module 'x' already loaded\nPHP 8.2.1 (cli)"),
|
|
v(8, 2, 1)
|
|
);
|
|
assert_eq!(parse_version(b"PHP 8.1 (cli)"), v(8, 1, 0));
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_non_versions() {
|
|
assert_eq!(parse_version(b""), None);
|
|
assert_eq!(parse_version(b"HHVM 4.0"), None);
|
|
assert_eq!(parse_version(b"PHP x.y"), None);
|
|
assert_eq!(parse_version(b"PHP 99999999999.1.1"), None);
|
|
assert_eq!(parse_version(b"\xff\xfePHP"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn version_order_and_minimum() {
|
|
assert!(v(8, 1, 30) < Some(MIN_VERSION));
|
|
assert!(v(8, 2, 0) >= Some(MIN_VERSION));
|
|
assert!(v(9, 0, 0) > Some(MIN_VERSION));
|
|
assert_eq!(MIN_VERSION.to_string(), "8.2.0");
|
|
}
|
|
|
|
#[test]
|
|
fn locate_reports_the_setting() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let err = locate("", Some(dir.path().as_os_str().to_owned())).unwrap_err();
|
|
assert!(err.to_string().contains("php.executable"), "{err}");
|
|
let missing = dir.path().join("nope").join("php");
|
|
let err = locate(missing.to_str().unwrap(), None).unwrap_err();
|
|
assert!(matches!(err, PhpError::NotFound(_)));
|
|
|
|
let name = if cfg!(windows) { "php.exe" } else { "php" };
|
|
std::fs::write(dir.path().join(name), b"").unwrap();
|
|
let found = locate(" ", Some(dir.path().as_os_str().to_owned())).unwrap();
|
|
assert_eq!(found, dir.path().join(name));
|
|
let given = dir.path().join(name);
|
|
assert_eq!(locate(given.to_str().unwrap(), None).unwrap(), given);
|
|
}
|
|
|
|
#[test]
|
|
fn extra_dirs_come_after_path_once() {
|
|
let path = std::env::join_paths(["/usr/bin", "/opt/homebrew/bin"]).unwrap();
|
|
let joined = with_extra_dirs(Some(path), &["/opt/homebrew/bin", "/opt/local/bin"]);
|
|
let dirs: Vec<PathBuf> = std::env::split_paths(&joined.unwrap()).collect();
|
|
assert_eq!(
|
|
dirs,
|
|
["/usr/bin", "/opt/homebrew/bin", "/opt/local/bin"].map(PathBuf::from)
|
|
);
|
|
let only_extra = with_extra_dirs(None, &["/opt/local/bin"]).unwrap();
|
|
assert_eq!(only_extra, OsString::from("/opt/local/bin"));
|
|
assert_eq!(with_extra_dirs(None, &[]), None);
|
|
if !cfg!(target_os = "macos") {
|
|
assert_eq!(search_path(Some("x".into())), Some("x".into()));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_program_that_is_not_php_fails_cleanly() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let fake = dir
|
|
.path()
|
|
.join(if cfg!(windows) { "php.exe" } else { "php" });
|
|
std::fs::write(&fake, b"not a program").unwrap();
|
|
let err = run_version(&fake, Duration::from_secs(2)).unwrap_err();
|
|
assert!(matches!(err, PhpError::Failed { .. }), "{err:?}");
|
|
}
|
|
|
|
proptest! {
|
|
#[test]
|
|
fn never_panics_on_random_output(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
|
|
let _ = parse_version(&bytes);
|
|
}
|
|
|
|
#[test]
|
|
fn finds_any_formatted_version(
|
|
noise in "[a-zA-Z :]{0,40}",
|
|
major in 0u32..100,
|
|
minor in 0u32..100,
|
|
patch in 0u32..1000,
|
|
suffix in "(-[a-z0-9.]{1,10})?",
|
|
) {
|
|
let text = format!("{noise}\nPHP {major}.{minor}.{patch}{suffix} (cli)\nCopyright");
|
|
prop_assert_eq!(parse_version(text.as_bytes()), v(major, minor, patch));
|
|
}
|
|
}
|
|
}
|