static-php-py 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- resources/__init__.py +5 -0
- static_php_py/__init__.py +49 -0
- static_php_py/exceptions.py +63 -0
- static_php_py/models.py +42 -0
- static_php_py/php.py +226 -0
- static_php_py/providers.py +403 -0
- static_php_py-0.1.0.dist-info/METADATA +732 -0
- static_php_py-0.1.0.dist-info/RECORD +10 -0
- static_php_py-0.1.0.dist-info/WHEEL +4 -0
- static_php_py-0.1.0.dist-info/licenses/LICENSE +339 -0
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""PHP binary providers for different resolution strategies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import importlib.resources
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import platform
|
|
10
|
+
import shutil
|
|
11
|
+
import sys
|
|
12
|
+
import tarfile
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
import zipfile
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Protocol
|
|
18
|
+
|
|
19
|
+
from platformdirs import user_cache_dir
|
|
20
|
+
|
|
21
|
+
from static_php_py.exceptions import BinaryNotFoundError, DownloadError, InvalidArchiveError
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _PHPProvider(Protocol):
|
|
27
|
+
"""Protocol defining interface for PHP binary resolution strategies.
|
|
28
|
+
|
|
29
|
+
All provider implementations must implement the resolve() method
|
|
30
|
+
to return a valid PHP executable path or raise BinaryNotFoundError.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def resolve(self) -> Path:
|
|
34
|
+
"""Resolve and return PHP binary path.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
Path to PHP executable.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
BinaryNotFoundError: If resolution fails.
|
|
41
|
+
"""
|
|
42
|
+
...
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _PathProvider:
|
|
46
|
+
"""Resolve PHP binary from explicit path or system PATH.
|
|
47
|
+
|
|
48
|
+
Implements two-tier resolution:
|
|
49
|
+
1. If explicit path provided, validate and return it
|
|
50
|
+
2. Otherwise, search system PATH for php executable
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
_explicit_path: User-specified path to PHP binary, or None.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(self, path: Path | str | None = None) -> None:
|
|
57
|
+
"""Initialize with optional explicit path.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
path: Optional explicit path to PHP binary.
|
|
61
|
+
"""
|
|
62
|
+
self._explicit_path = Path(path) if path else None
|
|
63
|
+
|
|
64
|
+
def resolve(self) -> Path:
|
|
65
|
+
"""Return explicit path if provided, otherwise search system PATH.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
Path to PHP executable.
|
|
69
|
+
|
|
70
|
+
Raises:
|
|
71
|
+
BinaryNotFoundError: If PHP binary not found.
|
|
72
|
+
"""
|
|
73
|
+
if self._explicit_path:
|
|
74
|
+
if not self._validate_binary(self._explicit_path):
|
|
75
|
+
raise BinaryNotFoundError(
|
|
76
|
+
f"PHP binary not found at explicit path: {self._explicit_path}"
|
|
77
|
+
)
|
|
78
|
+
return self._explicit_path
|
|
79
|
+
|
|
80
|
+
path = self._find_in_path()
|
|
81
|
+
if not path:
|
|
82
|
+
raise BinaryNotFoundError(
|
|
83
|
+
"PHP binary not found in system PATH. "
|
|
84
|
+
"Install PHP or use create(path=...) to specify location."
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
return path
|
|
88
|
+
|
|
89
|
+
def _find_in_path(self) -> Path | None:
|
|
90
|
+
"""Search system PATH for php executable."""
|
|
91
|
+
php_path = shutil.which("php")
|
|
92
|
+
if not php_path:
|
|
93
|
+
logger.debug("PHP not found in system PATH")
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
resolved = Path(php_path)
|
|
97
|
+
logger.debug("Found PHP in PATH: %s", resolved)
|
|
98
|
+
return resolved
|
|
99
|
+
|
|
100
|
+
def _validate_binary(self, path: Path) -> bool:
|
|
101
|
+
"""Check if path exists and is executable."""
|
|
102
|
+
if not path.exists():
|
|
103
|
+
logger.debug("Path does not exist: %s", path)
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
if not path.is_file():
|
|
107
|
+
logger.debug("Path is not a file: %s", path)
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
if not os.access(path, os.X_OK):
|
|
111
|
+
logger.debug("Path is not executable: %s", path)
|
|
112
|
+
return False
|
|
113
|
+
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class _ResourceProvider:
|
|
118
|
+
"""Load PHP binary from package resources.
|
|
119
|
+
|
|
120
|
+
Loads pre-built PHP binary from resources directory.
|
|
121
|
+
The binary should already exist in the package (extracted during wheel
|
|
122
|
+
installation). No runtime extraction or platform detection.
|
|
123
|
+
|
|
124
|
+
Attributes:
|
|
125
|
+
_package_dir: Directory where package is installed.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
def __init__(self) -> None:
|
|
129
|
+
"""Initialize resource provider."""
|
|
130
|
+
self._package_dir = self._get_package_directory()
|
|
131
|
+
|
|
132
|
+
def _get_package_directory(self) -> Path:
|
|
133
|
+
"""Get package installation directory."""
|
|
134
|
+
try:
|
|
135
|
+
package = importlib.resources.files("resources")
|
|
136
|
+
# importlib.resources.files() returns a Path-like object
|
|
137
|
+
if isinstance(package, Path):
|
|
138
|
+
# If it's a file, get parent; if directory, use directly
|
|
139
|
+
if package.is_file():
|
|
140
|
+
return package.parent
|
|
141
|
+
return package
|
|
142
|
+
# Fallback: try to convert to Path
|
|
143
|
+
return Path(str(package))
|
|
144
|
+
except (ModuleNotFoundError, AttributeError, TypeError) as e:
|
|
145
|
+
logger.error("Cannot determine package directory: %s", e)
|
|
146
|
+
raise BinaryNotFoundError(
|
|
147
|
+
"PHP binary not found in package resources. "
|
|
148
|
+
"Install platform-specific wheel or use create(path=...) to specify location."
|
|
149
|
+
) from e
|
|
150
|
+
|
|
151
|
+
def resolve(self) -> Path:
|
|
152
|
+
"""Load PHP binary from package resources.
|
|
153
|
+
|
|
154
|
+
Simply checks if php binary exists in resources directory.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
Path to PHP executable in resources directory.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
BinaryNotFoundError: If binary not found.
|
|
161
|
+
"""
|
|
162
|
+
# Check for php binary in package directory
|
|
163
|
+
package_binary = self._package_dir / "php"
|
|
164
|
+
|
|
165
|
+
if not package_binary.exists():
|
|
166
|
+
logger.error("PHP binary not found in resources directory: %s", package_binary)
|
|
167
|
+
raise BinaryNotFoundError(
|
|
168
|
+
f"PHP binary not found at {package_binary}. "
|
|
169
|
+
"Install platform-specific wheel or use PHP.local(path) to specify location."
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
# If binary exists but not executable, set permission
|
|
173
|
+
if not os.access(package_binary, os.X_OK):
|
|
174
|
+
try:
|
|
175
|
+
os.chmod(package_binary, 0o755)
|
|
176
|
+
logger.debug("Set execute permission on binary: %s", package_binary)
|
|
177
|
+
except OSError as e:
|
|
178
|
+
logger.warning("Cannot set execute permission: %s", e)
|
|
179
|
+
|
|
180
|
+
logger.debug("Using binary from resources: %s", package_binary)
|
|
181
|
+
return package_binary
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class _RemoteProvider:
|
|
186
|
+
"""Download and resolve PHP binary from remote URL.
|
|
187
|
+
|
|
188
|
+
Downloads PHP binaries or archives (tar.gz, tgz, zip) from remote URLs,
|
|
189
|
+
extracts if needed, and caches them locally. Supports force re-download option.
|
|
190
|
+
|
|
191
|
+
Attributes:
|
|
192
|
+
_url: Remote URL to download from.
|
|
193
|
+
_force: Force re-download flag, ignoring cache.
|
|
194
|
+
_timeout: Download timeout in seconds.
|
|
195
|
+
_cache_dir: Directory for downloaded files.
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
def __init__(self, url: str, force: bool = False, timeout: float = 300.0) -> None:
|
|
199
|
+
"""Initialize remote provider with URL and options.
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
url: Remote URL to PHP binary or archive (tar.gz, tgz, or zip).
|
|
203
|
+
force: Force re-download ignoring cache.
|
|
204
|
+
timeout: Download timeout in seconds.
|
|
205
|
+
"""
|
|
206
|
+
self._url = url
|
|
207
|
+
self._force = force
|
|
208
|
+
self._timeout = timeout
|
|
209
|
+
|
|
210
|
+
cache_base = user_cache_dir("static-php-py", "static-php-py")
|
|
211
|
+
url_hash = hashlib.sha256(url.encode()).hexdigest()[:16]
|
|
212
|
+
self._cache_dir = Path(cache_base) / "downloads" / url_hash
|
|
213
|
+
self._cache_dir.mkdir(parents=True, exist_ok=True)
|
|
214
|
+
|
|
215
|
+
def resolve(self) -> Path:
|
|
216
|
+
"""Download file, extract if archive, and return PHP binary path.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
Path to downloaded/extracted PHP executable.
|
|
220
|
+
|
|
221
|
+
Raises:
|
|
222
|
+
DownloadError: If network/HTTP download fails.
|
|
223
|
+
InvalidArchiveError: If archive is invalid or missing php executable.
|
|
224
|
+
"""
|
|
225
|
+
downloaded_file = self._cache_dir / "downloaded"
|
|
226
|
+
php_binary = self._cache_dir / "php"
|
|
227
|
+
|
|
228
|
+
if not self._force and php_binary.exists() and os.access(php_binary, os.X_OK):
|
|
229
|
+
logger.debug("Using cached binary from URL: %s", self._url)
|
|
230
|
+
return php_binary
|
|
231
|
+
|
|
232
|
+
if not downloaded_file.exists() or self._force:
|
|
233
|
+
try:
|
|
234
|
+
self._download_file(downloaded_file)
|
|
235
|
+
except (urllib.error.URLError, urllib.error.HTTPError, OSError) as e:
|
|
236
|
+
logger.error("Failed to download from URL: %s", self._url)
|
|
237
|
+
raise DownloadError(f"Failed to download from {self._url}: {e}") from e
|
|
238
|
+
|
|
239
|
+
if self._is_archive_url(self._url):
|
|
240
|
+
try:
|
|
241
|
+
extracted_php = self._extract_archive(downloaded_file)
|
|
242
|
+
if extracted_php != php_binary:
|
|
243
|
+
shutil.copy2(extracted_php, php_binary)
|
|
244
|
+
os.chmod(php_binary, 0o755)
|
|
245
|
+
except (tarfile.TarError, zipfile.BadZipFile, FileNotFoundError, ValueError) as e:
|
|
246
|
+
logger.error("Failed to extract archive: %s", downloaded_file)
|
|
247
|
+
raise InvalidArchiveError(
|
|
248
|
+
f"Failed to extract archive or find php executable: {e}"
|
|
249
|
+
) from e
|
|
250
|
+
else:
|
|
251
|
+
shutil.copy2(downloaded_file, php_binary)
|
|
252
|
+
os.chmod(php_binary, 0o755)
|
|
253
|
+
|
|
254
|
+
return php_binary
|
|
255
|
+
|
|
256
|
+
def _download_file(self, target_path: Path) -> None:
|
|
257
|
+
"""Download file using urllib.request to cache directory."""
|
|
258
|
+
logger.debug("Downloading from URL: %s", self._url)
|
|
259
|
+
|
|
260
|
+
try:
|
|
261
|
+
with urllib.request.urlopen(self._url, timeout=self._timeout) as response:
|
|
262
|
+
target_path.write_bytes(response.read())
|
|
263
|
+
logger.debug("Downloaded to: %s", target_path)
|
|
264
|
+
except urllib.error.HTTPError as e:
|
|
265
|
+
raise DownloadError(f"HTTP error {e.code} from {self._url}: {e.reason}") from e
|
|
266
|
+
except urllib.error.URLError as e:
|
|
267
|
+
raise DownloadError(f"URL error from {self._url}: {e.reason}") from e
|
|
268
|
+
except OSError as e:
|
|
269
|
+
raise DownloadError(f"IO error downloading from {self._url}: {e}") from e
|
|
270
|
+
|
|
271
|
+
def _is_archive_url(self, url: str) -> bool:
|
|
272
|
+
"""Check if URL points to archive by extension.
|
|
273
|
+
|
|
274
|
+
Supported formats: tar.gz, tgz, zip
|
|
275
|
+
"""
|
|
276
|
+
url_lower = url.lower()
|
|
277
|
+
return (url_lower.endswith(".tar.gz") or
|
|
278
|
+
url_lower.endswith(".tgz") or
|
|
279
|
+
url_lower.endswith(".zip"))
|
|
280
|
+
|
|
281
|
+
def _extract_archive(self, archive_path: Path) -> Path:
|
|
282
|
+
"""Extract archive (tar.gz or zip) and locate php executable.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
archive_path: Path to downloaded archive file.
|
|
286
|
+
|
|
287
|
+
Returns:
|
|
288
|
+
Path to php executable in extracted directory.
|
|
289
|
+
|
|
290
|
+
Raises:
|
|
291
|
+
InvalidArchiveError: If extraction fails or php not found.
|
|
292
|
+
"""
|
|
293
|
+
extract_dir = self._cache_dir / "extracted"
|
|
294
|
+
extract_dir.mkdir(exist_ok=True)
|
|
295
|
+
|
|
296
|
+
# Determine archive type from URL (not filename, since downloaded file is named "downloaded")
|
|
297
|
+
url_lower = self._url.lower()
|
|
298
|
+
try:
|
|
299
|
+
if url_lower.endswith(".zip"):
|
|
300
|
+
with zipfile.ZipFile(archive_path, "r") as zf:
|
|
301
|
+
zf.extractall(extract_dir)
|
|
302
|
+
elif url_lower.endswith((".tar.gz", ".tgz")):
|
|
303
|
+
with tarfile.open(archive_path, "r:gz") as tar:
|
|
304
|
+
tar.extractall(extract_dir)
|
|
305
|
+
else:
|
|
306
|
+
raise InvalidArchiveError(f"Unsupported archive format: {self._url}")
|
|
307
|
+
except (tarfile.TarError, zipfile.BadZipFile) as e:
|
|
308
|
+
raise InvalidArchiveError(f"Failed to extract archive: {e}") from e
|
|
309
|
+
|
|
310
|
+
php_path = self._find_php_in_directory(extract_dir)
|
|
311
|
+
if not php_path:
|
|
312
|
+
raise InvalidArchiveError("No php executable found in extracted archive")
|
|
313
|
+
|
|
314
|
+
return php_path
|
|
315
|
+
|
|
316
|
+
def _find_php_in_directory(self, directory: Path) -> Path | None:
|
|
317
|
+
"""Locate php executable in directory tree.
|
|
318
|
+
|
|
319
|
+
Searches for executables with common PHP-related names:
|
|
320
|
+
- php, php* (e.g., php8.3, php-cli)
|
|
321
|
+
- spc, spc* (static-php-cli binaries)
|
|
322
|
+
"""
|
|
323
|
+
for root, _dirs, files in os.walk(directory):
|
|
324
|
+
for name in files:
|
|
325
|
+
# Check for php, php*, spc, spc* executables
|
|
326
|
+
if name == "php" or name.startswith("php") or name == "spc" or name.startswith("spc"):
|
|
327
|
+
candidate = Path(root) / name
|
|
328
|
+
if os.access(candidate, os.X_OK) or candidate.is_file():
|
|
329
|
+
logger.debug("Found PHP executable: %s", candidate)
|
|
330
|
+
return candidate
|
|
331
|
+
|
|
332
|
+
return None
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class _PHPResolver:
|
|
336
|
+
"""Internal factory implementing fallback resolution strategy.
|
|
337
|
+
|
|
338
|
+
Resolves PHP binary using a priority chain:
|
|
339
|
+
1. Explicit path (if provided) via _PathProvider
|
|
340
|
+
2. Package resource (bundled binary) via _ResourceProvider
|
|
341
|
+
3. System PATH via _PathProvider
|
|
342
|
+
|
|
343
|
+
Attributes:
|
|
344
|
+
_path_provider: Provider for explicit path or system PATH resolution.
|
|
345
|
+
_resource_provider: Provider for package resource resolution.
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
def __init__(self) -> None:
|
|
349
|
+
"""Initialize resolver with provider instances."""
|
|
350
|
+
self._path_provider = _PathProvider()
|
|
351
|
+
self._resource_provider = _ResourceProvider()
|
|
352
|
+
|
|
353
|
+
def resolve(self, path: Path | str | None = None) -> Path:
|
|
354
|
+
"""Resolve PHP binary using fallback strategy.
|
|
355
|
+
|
|
356
|
+
Priority order:
|
|
357
|
+
1. Explicit path (if provided)
|
|
358
|
+
2. Package resource (bundled binary)
|
|
359
|
+
3. System PATH
|
|
360
|
+
|
|
361
|
+
Args:
|
|
362
|
+
path: Optional explicit path to PHP binary.
|
|
363
|
+
|
|
364
|
+
Returns:
|
|
365
|
+
Path to PHP executable.
|
|
366
|
+
|
|
367
|
+
Raises:
|
|
368
|
+
BinaryNotFoundError: If all resolution methods fail.
|
|
369
|
+
"""
|
|
370
|
+
# Priority 1: If explicit path provided, use it
|
|
371
|
+
if path:
|
|
372
|
+
path_provider = _PathProvider(path)
|
|
373
|
+
try:
|
|
374
|
+
resolved = path_provider.resolve()
|
|
375
|
+
logger.debug("Resolved PHP binary via explicit path: %s", resolved)
|
|
376
|
+
return resolved
|
|
377
|
+
except BinaryNotFoundError as e:
|
|
378
|
+
logger.error("Explicit path failed: %s", path)
|
|
379
|
+
raise BinaryNotFoundError(
|
|
380
|
+
f"PHP binary not found at explicit path: {path}"
|
|
381
|
+
) from e
|
|
382
|
+
|
|
383
|
+
# Priority 2: Try package resource (bundled binary)
|
|
384
|
+
try:
|
|
385
|
+
resolved = self._resource_provider.resolve()
|
|
386
|
+
logger.debug("Resolved PHP binary via ResourceProvider: %s", resolved)
|
|
387
|
+
return resolved
|
|
388
|
+
except BinaryNotFoundError:
|
|
389
|
+
logger.debug("ResourceProvider failed, trying system PATH")
|
|
390
|
+
|
|
391
|
+
# Priority 3: Fall back to system PATH
|
|
392
|
+
path_provider = _PathProvider(None)
|
|
393
|
+
try:
|
|
394
|
+
resolved = path_provider.resolve()
|
|
395
|
+
logger.debug("Resolved PHP binary via system PATH: %s", resolved)
|
|
396
|
+
return resolved
|
|
397
|
+
except BinaryNotFoundError as e:
|
|
398
|
+
logger.error("All resolution methods failed")
|
|
399
|
+
raise BinaryNotFoundError(
|
|
400
|
+
"PHP binary not found. "
|
|
401
|
+
"Install PHP system-wide, use create(path=...) to specify location, "
|
|
402
|
+
"or install platform-specific wheel with bundled binary."
|
|
403
|
+
) from e
|