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
#![doc = include_str!("../README.md")]
mod ext;
use anyhow::{bail, Context, Result as AResult};
use cargo_metadata::{camino::Utf8PathBuf, Target};
use clap::Parser;
use dialoguer::{Confirm, Select};
use std::{
borrow::Cow,
ffi::OsString,
fs::{File, OpenOptions},
io::{BufRead, BufReader, Write},
path::PathBuf,
process::{Command, Stdio},
str::FromStr,
};
use self::ext::Ext;
use ext_php_rs::describe::ToStub;
#[macro_export]
macro_rules! stub_symbols {
($($s: ident),*) => {
$(
$crate::stub_symbols!(@INTERNAL; $s);
)*
};
(@INTERNAL; $s: ident) => {
#[allow(non_upper_case_globals)]
#[no_mangle]
pub static mut $s: *mut () = ::std::ptr::null_mut();
};
}
pub type Result = anyhow::Result<()>;
pub fn run() -> Result {
let mut args: Vec<_> = std::env::args().collect();
if args.get(1).map(|nth| nth == "php").unwrap_or(false) {
args.remove(1);
}
Args::parse_from(args).handle()
}
#[derive(Parser)]
#[clap(
about = "Installs extensions and generates stub files for PHP extensions generated with `ext-php-rs`.",
author = "David Cole <david.cole1340@gmail.com>",
version = env!("CARGO_PKG_VERSION")
)]
enum Args {
Install(Install),
Remove(Remove),
Stubs(Stubs),
}
#[derive(Parser)]
struct Install {
#[clap(long)]
install_dir: Option<PathBuf>,
#[clap(long)]
ini_path: Option<PathBuf>,
#[clap(long)]
disable: bool,
#[clap(long)]
release: bool,
#[clap(long)]
manifest: Option<PathBuf>,
}
#[derive(Parser)]
struct Remove {
#[clap(long)]
install_dir: Option<PathBuf>,
#[clap(long)]
ini_path: Option<PathBuf>,
#[clap(long)]
manifest: Option<PathBuf>,
}
#[derive(Parser)]
struct Stubs {
ext: Option<PathBuf>,
#[clap(short, long)]
out: Option<PathBuf>,
#[clap(long, conflicts_with = "out")]
stdout: bool,
#[clap(long, conflicts_with = "ext")]
manifest: Option<PathBuf>,
}
impl Args {
pub fn handle(self) -> Result {
match self {
Args::Install(install) => install.handle(),
Args::Remove(remove) => remove.handle(),
Args::Stubs(stubs) => stubs.handle(),
}
}
}
impl Install {
pub fn handle(self) -> Result {
let artifact = find_ext(&self.manifest)?;
let ext_path = build_ext(&artifact, self.release)?;
let (mut ext_dir, mut php_ini) = if let Some(install_dir) = self.install_dir {
(install_dir, None)
} else {
let php_config = PhpConfig::new();
(php_config.get_ext_dir()?, Some(php_config.get_php_ini()?))
};
if let Some(ini_path) = self.ini_path {
php_ini = Some(ini_path);
}
if !Confirm::new()
.with_prompt(format!(
"Are you sure you want to install the extension `{}`?",
artifact.name
))
.interact()?
{
bail!("Installation cancelled.");
}
debug_assert!(ext_path.is_file());
let ext_name = ext_path.file_name().expect("ext path wasn't a filepath");
if ext_dir.is_dir() {
ext_dir.push(ext_name);
}
std::fs::copy(&ext_path, &ext_dir).with_context(|| {
"Failed to copy extension from target directory to extension directory"
})?;
if let Some(php_ini) = php_ini {
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(php_ini)
.with_context(|| "Failed to open `php.ini`")?;
let mut ext_line = format!("extension={}", ext_name);
let mut new_lines = vec![];
for line in BufReader::new(&file).lines() {
let line = line.with_context(|| "Failed to read line from `php.ini`")?;
if !line.contains(&ext_line) {
new_lines.push(line);
}
}
if self.disable {
ext_line.insert(0, ';');
}
new_lines.push(ext_line);
file.write(new_lines.join("\n").as_bytes())
.with_context(|| "Failed to update `php.ini`")?;
}
Ok(())
}
}
impl Remove {
pub fn handle(self) -> Result {
use std::env::consts;
let artifact = find_ext(&self.manifest)?;
let (mut ext_path, mut php_ini) = if let Some(install_dir) = self.install_dir {
(install_dir, None)
} else {
let php_config = PhpConfig::new();
(php_config.get_ext_dir()?, Some(php_config.get_php_ini()?))
};
if let Some(ini_path) = self.ini_path {
php_ini = Some(ini_path);
}
let ext_file = format!(
"{}{}{}",
consts::DLL_PREFIX,
artifact.name.replace("-", "_"),
consts::DLL_SUFFIX
);
ext_path.push(&ext_file);
if !ext_path.is_file() {
bail!("Unable to find extension installed.");
}
if !Confirm::new()
.with_prompt(format!(
"Are you sure you want to remove the extension `{}`?",
artifact.name
))
.interact()?
{
bail!("Installation cancelled.");
}
std::fs::remove_file(ext_path).with_context(|| "Failed to remove extension")?;
if let Some(php_ini) = php_ini.filter(|path| path.is_file()) {
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(php_ini)
.with_context(|| "Failed to open `php.ini`")?;
let mut new_lines = vec![];
for line in BufReader::new(&file).lines() {
let line = line.with_context(|| "Failed to read line from `php.ini`")?;
if !line.contains(&ext_file) {
new_lines.push(line);
}
}
file.write(new_lines.join("\n").as_bytes())
.with_context(|| "Failed to update `php.ini`")?;
}
Ok(())
}
}
impl Stubs {
pub fn handle(self) -> Result {
let ext_path = if let Some(ext_path) = self.ext {
ext_path
} else {
let target = find_ext(&self.manifest)?;
build_ext(&target, false)?.into()
};
if !ext_path.is_file() {
bail!("Invalid extension path given, not a file.");
}
let ext = Ext::load(ext_path)?;
let result = ext.describe();
let cli_version = semver::VersionReq::from_str(ext_php_rs::VERSION).with_context(|| {
"Failed to parse `ext-php-rs` version that `cargo php` was compiled with"
})?;
let ext_version = semver::Version::from_str(result.version).with_context(|| {
"Failed to parse `ext-php-rs` version that your extension was compiled with"
})?;
if !cli_version.matches(&ext_version) {
bail!("Extension was compiled with an incompatible version of `ext-php-rs` - Extension: {}, CLI: {}", ext_version, cli_version);
}
let stubs = result
.module
.to_stub()
.with_context(|| "Failed to generate stubs.")?;
if self.stdout {
print!("{}", stubs);
} else {
let out_path = if let Some(out_path) = &self.out {
Cow::Borrowed(out_path)
} else {
let mut cwd = std::env::current_dir()
.with_context(|| "Failed to get current working directory")?;
cwd.push(format!("{}.stubs.php", result.module.name));
Cow::Owned(cwd)
};
std::fs::write(out_path.as_ref(), &stubs)
.with_context(|| "Failed to write stubs to file")?;
}
Ok(())
}
}
struct PhpConfig {
path: OsString,
}
impl PhpConfig {
pub fn new() -> Self {
Self {
path: if let Some(php_config) = std::env::var_os("PHP_CONFIG") {
php_config
} else {
OsString::from("php-config")
},
}
}
pub fn get_ext_dir(&self) -> AResult<PathBuf> {
Ok(PathBuf::from(
self.exec(
|cmd| cmd.arg("--extension-dir"),
"retrieve extension directory",
)?
.trim(),
))
}
pub fn get_php_ini(&self) -> AResult<PathBuf> {
let mut path = PathBuf::from(
self.exec(|cmd| cmd.arg("--ini-path"), "retrieve `php.ini` path")?
.trim(),
);
path.push("php.ini");
if !path.exists() {
File::create(&path).with_context(|| "Failed to create `php.ini`")?;
}
Ok(path)
}
fn exec<F>(&self, f: F, ctx: &str) -> AResult<String>
where
F: FnOnce(&mut Command) -> &mut Command,
{
let mut cmd = Command::new(&self.path);
f(&mut cmd);
let out = cmd
.output()
.with_context(|| format!("Failed to {} from `php-config`", ctx))?;
String::from_utf8(out.stdout)
.with_context(|| "Failed to convert `php-config` output to string")
}
}
fn find_ext(manifest: &Option<PathBuf>) -> AResult<cargo_metadata::Target> {
let mut cmd = cargo_metadata::MetadataCommand::new();
if let Some(manifest) = manifest {
cmd.manifest_path(manifest);
}
let meta = cmd
.features(cargo_metadata::CargoOpt::AllFeatures)
.exec()
.with_context(|| "Failed to call `cargo metadata`")?;
let package = meta
.root_package()
.with_context(|| "Failed to retrieve metadata about crate")?;
let targets: Vec<_> = package
.targets
.iter()
.filter(|target| {
target
.crate_types
.iter()
.any(|ty| ty == "dylib" || ty == "cdylib")
})
.collect();
let target = match targets.len() {
0 => bail!("No library targets were found."),
1 => targets[0],
_ => {
let target_names: Vec<_> = targets.iter().map(|target| &target.name).collect();
let chosen = Select::new()
.with_prompt("There were multiple library targets detected in the project. Which would you like to use?")
.items(&target_names)
.interact()?;
targets[chosen]
}
};
Ok(target.clone())
}
fn build_ext(target: &Target, release: bool) -> AResult<Utf8PathBuf> {
let mut cmd = Command::new("cargo");
cmd.arg("build")
.arg("--message-format=json-render-diagnostics");
if release {
cmd.arg("--release");
}
let mut spawn = cmd
.stdout(Stdio::piped())
.spawn()
.with_context(|| "Failed to spawn `cargo build`")?;
let reader = BufReader::new(
spawn
.stdout
.take()
.with_context(|| "Failed to take `cargo build` stdout")?,
);
let mut artifact = None;
for message in cargo_metadata::Message::parse_stream(reader) {
let message = message.with_context(|| "Invalid message received from `cargo build`")?;
match message {
cargo_metadata::Message::CompilerArtifact(a) => {
if &a.target == target {
artifact = Some(a);
}
}
cargo_metadata::Message::BuildFinished(b) => {
if !b.success {
bail!("Compilation failed, cancelling installation.")
} else {
break;
}
}
_ => continue,
}
}
let artifact = artifact.with_context(|| "Extension artifact was not compiled")?;
for file in artifact.filenames {
if file.extension() == Some(std::env::consts::DLL_EXTENSION) {
return Ok(file);
}
}
bail!("Failed to retrieve extension path from artifact")
}