M3.1: PHP detection and pinned Phpactor download
- crates/lsp toolchain: PHP from php.executable or PATH, `php -v` with a 5 s timeout and capped output, version parsing (proptest), PHP >= 8.2. - Pinned Phpactor 2026.06.25.0 (SHA-256 832510fe...59e9); newer releases need ext-posix and do not start on Windows. - Download with ureq + rustls (ring, OS roots via rustls-native-certs): HTTPS only, 32 MiB cap, SHA-256 verified before an atomic write, retry with backoff. Tests use a local HTTP server only. - Engine: settings php.executable, phpactor.path, phpactor.autoDownload (bool and string setting kinds), toolchain.status, toolchain.downloadPhpactor, toolchainChanged, notifications; worker thread off the engine lock, results via the pump. Downloads only after the host calls Engine::allow_downloads (the desktop does). - Docs: architecture Toolchain section (network access, D15), G6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
78709dd76b
commit
50f36cce8b
23 changed files with 2577 additions and 10 deletions
371
crates/lsp/src/toolchain/php.rs
Normal file
371
crates/lsp/src/toolchain/php.rs
Normal file
|
|
@ -0,0 +1,371 @@
|
|||
//! 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`), 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, 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 })
|
||||
}
|
||||
|
||||
/// 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 = command.spawn().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();
|
||||
let _ = child.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 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue