Skip to main content

rsphp_build_tools/
php_config_runner.rs

1use std::ffi::{OsStr, OsString};
2use std::process::Command;
3
4/// Utility for running `php-config` commands.
5#[derive(Debug)]
6pub struct PhpConfigRunner {
7    /// Actual Command object.
8    inner: Command,
9    /// Arguments added to the command, for use in debugging.
10    args: Vec<OsString>,
11}
12
13impl PhpConfigRunner {
14    /// Create a new command runner.
15    #[must_use]
16    pub fn new() -> Self {
17        Self {
18            inner: Command::new("php-config"),
19            args: vec![],
20        }
21    }
22
23    /// Add an argument.
24    pub fn arg<S>(&mut self, arg: S) -> &mut Self
25    where
26        S: AsRef<OsStr>,
27    {
28        self.args.push(arg.as_ref().to_os_string());
29        let _: &mut Command = self.inner.arg(arg);
30        self
31    }
32
33    /// Run the command and return the output, which must be UTF-8.
34    ///
35    /// # Panics
36    ///
37    /// Panics if the command fails or returns output that is not valid UTF-8.
38    #[expect(clippy::panic, reason = "Panic is at build time")]
39    pub fn run(&mut self) -> String {
40        let output = self.inner.output().unwrap_or_else(|err| {
41            panic!(
42                "php-config {} should succeed, got {err}",
43                self.args
44                    .iter()
45                    .map(|arg| arg.display().to_string())
46                    .collect::<Vec<_>>()
47                    .join(" ")
48            )
49        });
50        let stdout_full = std::str::from_utf8(&output.stdout).unwrap_or_else(|err| {
51            panic!(
52                "php-config {} should result in UTF-8, got {err}",
53                self.args
54                    .iter()
55                    .map(|arg| arg.display().to_string())
56                    .collect::<Vec<_>>()
57                    .join(" ")
58            )
59        });
60        stdout_full.trim().to_owned()
61    }
62}
63
64impl Default for PhpConfigRunner {
65    fn default() -> Self {
66        Self::new()
67    }
68}