| 1 |
import hashlib |
| 2 |
import json |
| 3 |
import os |
| 4 |
import platform |
| 5 |
import re |
| 6 |
import sys |
| 7 |
import tarfile |
| 8 |
import time |
| 9 |
from contextlib import closing |
| 10 |
from ftplib import FTP |
| 11 |
from pathlib import Path |
| 12 |
|
| 13 |
import urllib.error |
| 14 |
from urllib.parse import urljoin, quote as urlquote, unquote, urlparse |
| 15 |
from urllib.request import urlretrieve, urlopen, Request |
| 16 |
|
| 17 |
multi_make_options = [] |
| 18 |
try: |
| 19 |
import multiprocessing |
| 20 |
cpus = multiprocessing.cpu_count() |
| 21 |
if cpus > 1: |
| 22 |
if cpus > 5: |
| 23 |
cpus = 5 |
| 24 |
multi_make_options = ['-j%d' % (cpus+1)] |
| 25 |
except Exception: |
| 26 |
pass |
| 27 |
|
| 28 |
|
| 29 |
# overridable to control script usage |
| 30 |
sys_platform = sys.platform |
| 31 |
|
| 32 |
|
| 33 |
# use pre-built libraries on Windows |
| 34 |
|
| 35 |
def read_file_digest(file): |
| 36 |
buffer = bytearray(2**18) |
| 37 |
view = memoryview(buffer) |
| 38 |
|
| 39 |
from hashlib import sha256 |
| 40 |
filehash = sha256() |
| 41 |
with open(file, 'rb') as f: |
| 42 |
while True: |
| 43 |
size = f.readinto(buffer) |
| 44 |
if not size: |
| 45 |
break |
| 46 |
filehash.update(view[:size]) |
| 47 |
|
| 48 |
return 'sha256:' + filehash.hexdigest() |
| 49 |
|
| 50 |
|
| 51 |
def download_and_extract_windows_binaries(destdir, arch=None): |
| 52 |
# Check for native ARM64 build or the environment variable that is set by |
| 53 |
# Visual Studio for cross-compilation (same variable as setuptools uses) |
| 54 |
if platform.machine() == 'ARM64' or os.getenv('VSCMD_ARG_TGT_ARCH') == 'arm64': |
| 55 |
arch = "win-arm64" |
| 56 |
elif arch == 'win32' or (arch != 'win64' and sys.maxsize <= 2**32): |
| 57 |
arch = "win32" |
| 58 |
else: |
| 59 |
arch = "win64" |
| 60 |
|
| 61 |
def build_libzip_name(libname, version): |
| 62 |
return f"{libname}-{version}.{arch}.zip" |
| 63 |
|
| 64 |
def read_latest_release(): |
| 65 |
url = "https://api.github.com/repos/lxml/libxml2-win-binaries/releases?per_page=5" |
| 66 |
releases, _ = read_url( |
| 67 |
url, |
| 68 |
accept="application/vnd.github+json", |
| 69 |
as_json=True, |
| 70 |
github_api_token=os.environ.get("GITHUB_API_TOKEN"), |
| 71 |
) |
| 72 |
|
| 73 |
max_release = {'tag_name': ''} |
| 74 |
for release in releases: |
| 75 |
if max_release['tag_name'] < release.get('tag_name', ''): |
| 76 |
max_release = release |
| 77 |
|
| 78 |
return max_release |
| 79 |
|
| 80 |
latest_release = read_latest_release() |
| 81 |
|
| 82 |
release_tag = latest_release['tag_name'] |
| 83 |
download_url = f"https://github.com/lxml/libxml2-win-binaries/releases/download/{urlquote(release_tag)}/" |
| 84 |
|
| 85 |
arch_part = f'.{arch}.' |
| 86 |
asset_files = { |
| 87 |
asset['name']: (asset['size'], asset['digest']) |
| 88 |
for asset in latest_release.get('assets', ()) |
| 89 |
if arch_part in asset['name'] |
| 90 |
} |
| 91 |
|
| 92 |
lib_file_names = list(asset_files) |
| 93 |
libs = { |
| 94 |
libname: build_libzip_name(libname, find_max_version(libname, lib_file_names)) |
| 95 |
for libname in ['libxml2', 'libxslt', 'zlib', 'iconv'] |
| 96 |
} |
| 97 |
|
| 98 |
if not os.path.exists(destdir): |
| 99 |
os.makedirs(destdir) |
| 100 |
|
| 101 |
for libfn in libs.values(): |
| 102 |
srcfile = urljoin(download_url, libfn) |
| 103 |
destfile = os.path.join(destdir, libfn) |
| 104 |
if os.path.exists(destfile): |
| 105 |
file_size, file_digest = asset_files.get(libfn, (None, None)) |
| 106 |
if file_size and os.path.getsize(destfile) == file_size and read_file_digest(destfile) == file_digest: |
| 107 |
print(f'Using local copy of "{srcfile}"') |
| 108 |
continue |
| 109 |
|
| 110 |
print(f'Retrieving "{srcfile}" to "{destfile}"') |
| 111 |
urlretrieve(srcfile, destfile) |
| 112 |
|
| 113 |
lib_dirs = { |
| 114 |
libname: unpack_zipfile(os.path.join(destdir, libfn), destdir) |
| 115 |
for libname, libfn in libs.items() |
| 116 |
} |
| 117 |
return lib_dirs |
| 118 |
|
| 119 |
|
| 120 |
def find_top_dir_of_zipfile(zipfile): |
| 121 |
topdir = None |
| 122 |
files = [f.filename for f in zipfile.filelist] |
| 123 |
dirs = [d for d in files if d.endswith('/')] |
| 124 |
if dirs: |
| 125 |
dirs.sort(key=len) |
| 126 |
topdir = dirs[0] |
| 127 |
topdir = topdir[:topdir.index("/")+1] |
| 128 |
for path in files: |
| 129 |
if not path.startswith(topdir): |
| 130 |
topdir = None |
| 131 |
break |
| 132 |
assert topdir, ( |
| 133 |
"cannot determine single top-level directory in zip file %s" % |
| 134 |
zipfile.filename) |
| 135 |
return topdir.rstrip('/') |
| 136 |
|
| 137 |
|
| 138 |
def unpack_zipfile(zipfn, destdir): |
| 139 |
assert zipfn.endswith('.zip') |
| 140 |
import zipfile |
| 141 |
|
| 142 |
print(f'Unpacking {os.path.basename(zipfn)} into {destdir}') |
| 143 |
with zipfile.ZipFile(zipfn) as f: |
| 144 |
extracted_dir = os.path.join(destdir, find_top_dir_of_zipfile(f)) |
| 145 |
f.extractall(path=destdir) |
| 146 |
|
| 147 |
assert os.path.exists(extracted_dir), 'missing: %s' % extracted_dir |
| 148 |
return extracted_dir |
| 149 |
|
| 150 |
|
| 151 |
def get_prebuilt_libxml2xslt(download_dir, static_include_dirs, static_library_dirs, arch=None): |
| 152 |
assert sys_platform.startswith('win') |
| 153 |
libs = download_and_extract_windows_binaries(download_dir, arch=arch) |
| 154 |
for libname, path in libs.items(): |
| 155 |
i = os.path.join(path, 'include') |
| 156 |
l = os.path.join(path, 'lib') |
| 157 |
assert os.path.exists(i), 'does not exist: %s' % i |
| 158 |
assert os.path.exists(l), 'does not exist: %s' % l |
| 159 |
static_include_dirs.append(i) |
| 160 |
static_library_dirs.append(l) |
| 161 |
|
| 162 |
|
| 163 |
## Routines to download and build libxml2/xslt from sources: |
| 164 |
|
| 165 |
LIBXML2_LOCATION = 'https://download.gnome.org/sources/libxml2/' |
| 166 |
LIBXSLT_LOCATION = 'https://download.gnome.org/sources/libxslt/' |
| 167 |
LIBICONV_LOCATION = 'https://ftp.gnu.org/pub/gnu/libiconv/' |
| 168 |
ZLIB_LOCATION = 'https://zlib.net/' |
| 169 |
match_libfile_version = re.compile('^[^-]*-([.0-9-]+)[.].*').match |
| 170 |
|
| 171 |
|
| 172 |
def _find_content_encoding(response, default='iso8859-1'): |
| 173 |
from email.message import Message |
| 174 |
content_type = response.headers.get('Content-Type') |
| 175 |
if content_type: |
| 176 |
msg = Message() |
| 177 |
msg.add_header('Content-Type', content_type) |
| 178 |
charset = msg.get_content_charset(default) |
| 179 |
else: |
| 180 |
charset = default |
| 181 |
return charset |
| 182 |
|
| 183 |
|
| 184 |
def remote_listdir(url): |
| 185 |
try: |
| 186 |
return _list_dir_urllib(url) |
| 187 |
except IOError: |
| 188 |
assert url.lower().startswith('ftp://') |
| 189 |
print("Requesting with urllib failed. Falling back to ftplib. " |
| 190 |
"Proxy argument will be ignored for %s" % url) |
| 191 |
return _list_dir_ftplib(url) |
| 192 |
|
| 193 |
|
| 194 |
def _list_dir_ftplib(url): |
| 195 |
parts = urlparse(url) |
| 196 |
ftp = FTP(parts.netloc) |
| 197 |
try: |
| 198 |
ftp.login() |
| 199 |
ftp.cwd(parts.path) |
| 200 |
data = [] |
| 201 |
ftp.dir(data.append) |
| 202 |
finally: |
| 203 |
ftp.quit() |
| 204 |
return parse_text_ftplist("\n".join(data)) |
| 205 |
|
| 206 |
|
| 207 |
def read_url(url, decode=True, accept=None, as_json=False, github_api_token=None): |
| 208 |
headers = {'User-Agent': 'https://github.com/lxml/lxml'} |
| 209 |
if accept: |
| 210 |
headers['Accept'] = accept |
| 211 |
if github_api_token: |
| 212 |
headers['authorization'] = "Bearer " + github_api_token |
| 213 |
request = Request(url, headers=headers) |
| 214 |
|
| 215 |
with closing(urlopen(request)) as res: |
| 216 |
charset = _find_content_encoding(res) |
| 217 |
content_type = res.headers.get('Content-Type') |
| 218 |
data = res.read() |
| 219 |
|
| 220 |
if decode: |
| 221 |
data = data.decode(charset) |
| 222 |
if as_json: |
| 223 |
data = json.loads(data) |
| 224 |
return data, content_type |
| 225 |
|
| 226 |
|
| 227 |
def _list_dir_urllib(url): |
| 228 |
data, content_type = read_url(url) |
| 229 |
if content_type and content_type.startswith('text/html'): |
| 230 |
files = parse_html_filelist(data) |
| 231 |
else: |
| 232 |
files = parse_text_ftplist(data) |
| 233 |
return files |
| 234 |
|
| 235 |
|
| 236 |
def http_find_latest_version_directory(url, version=None): |
| 237 |
data, _ = read_url(url) |
| 238 |
# e.g. <a href="1.0/"> |
| 239 |
directories = [ |
| 240 |
(int(v[0]), int(v[1])) |
| 241 |
for v in re.findall(r' href=["\']([0-9]+)\.([0-9]+)/?["\']', data) |
| 242 |
] |
| 243 |
if not directories: |
| 244 |
return url |
| 245 |
best_version = max(directories) |
| 246 |
if version: |
| 247 |
major, minor, _ = version.split(".", 2) |
| 248 |
major, minor = int(major), int(minor) |
| 249 |
if (major, minor) in directories: |
| 250 |
best_version = (major, minor) |
| 251 |
latest_dir = "%s.%s" % best_version |
| 252 |
return urljoin(url, latest_dir) + "/" |
| 253 |
|
| 254 |
|
| 255 |
def http_listfiles(url, re_pattern): |
| 256 |
data, _ = read_url(url) |
| 257 |
files = re.findall(re_pattern, data) |
| 258 |
return files |
| 259 |
|
| 260 |
|
| 261 |
def parse_text_ftplist(s): |
| 262 |
for line in s.splitlines(): |
| 263 |
if not line.startswith('d'): |
| 264 |
# -rw-r--r-- 1 ftp ftp 476 Sep 1 2011 md5sum.txt |
| 265 |
# Last (9th) element is 'md5sum.txt' in the above example, but there |
| 266 |
# may be variations, so we discard only the first 8 entries. |
| 267 |
yield line.split(None, 8)[-1] |
| 268 |
|
| 269 |
|
| 270 |
def parse_html_filelist(s): |
| 271 |
re_href = re.compile( |
| 272 |
r'''<a[^>]*\shref=["']([^;?"']+?)[;?"']''', |
| 273 |
re.I|re.M) |
| 274 |
links = set(re_href.findall(s)) |
| 275 |
for link in links: |
| 276 |
if not link.endswith('/'): |
| 277 |
yield unquote(link) |
| 278 |
|
| 279 |
|
| 280 |
def tryint(s): |
| 281 |
try: |
| 282 |
return int(s) |
| 283 |
except ValueError: |
| 284 |
return s |
| 285 |
|
| 286 |
|
| 287 |
ARCHIVE_HASHES = { |
| 288 |
# Default hash algorithm is SHA-256. |
| 289 |
# Prefix hash with e.g. "sha512:" for alternative algorithms. |
| 290 |
filename: digest |
| 291 |
for line in """ |
| 292 |
c8b9bc81f8b590c33af8cc6c336dbff2f53409973588a351c95f1c621b13d09d libxml2-2.15.2.tar.xz |
| 293 |
7ce458a0affeb83f0b55f1f4f9e0e55735dbfc1a9de124ee86fb4a66b597203a libxml2-2.14.6.tar.xz |
| 294 |
|
| 295 |
9acfe68419c4d06a45c550321b3212762d92f41465062ca4ea19e632ee5d216e libxslt-1.1.45.tar.xz |
| 296 |
5a3d6b383ca5afc235b171118e90f5ff6aa27e9fea3303065231a6d403f0183a libxslt-1.1.43.tar.xz |
| 297 |
|
| 298 |
88dd96a8c0464eca144fc791ae60cd31cd8ee78321e67397e25fc095c4a19aa6 libiconv-1.19.tar.gz |
| 299 |
3b08f5f4f9b4eb82f151a7040bfd6fe6c6fb922efe4b1659c66ea933276965e8 libiconv-1.18.tar.gz |
| 300 |
|
| 301 |
bb329a0a2cd0274d05519d61c667c062e06990d72e125ee2dfa8de64f0119d16 zlib-1.3.2.tar.gz |
| 302 |
""".strip().splitlines() |
| 303 |
if len(line) > 64 |
| 304 |
for digest, filename in [line.split()] |
| 305 |
} |
| 306 |
|
| 307 |
|
| 308 |
def download_libxml2(dest_dir, version=None): |
| 309 |
"""Downloads libxml2, returning the filename where the library was downloaded""" |
| 310 |
#version_re = re.compile(r'LATEST_LIBXML2_IS_([0-9.]+[0-9](?:-[abrc0-9]+)?)') |
| 311 |
version_re = re.compile(r'libxml2-([0-9.]+[0-9])[.]tar[.]xz') |
| 312 |
filename = 'libxml2-%s.tar.xz' |
| 313 |
|
| 314 |
if version == "2.9.12": |
| 315 |
# Temporarily using the latest master (2.9.12+) until there is a release that supports lxml again. |
| 316 |
from_location = "https://gitlab.gnome.org/GNOME/libxml2/-/archive/dea91c97debeac7c1aaf9c19f79029809e23a353/" |
| 317 |
version = "dea91c97debeac7c1aaf9c19f79029809e23a353" |
| 318 |
else: |
| 319 |
from_location = http_find_latest_version_directory(LIBXML2_LOCATION, version=version) |
| 320 |
|
| 321 |
return download_library(dest_dir, from_location, 'libxml2', |
| 322 |
version_re, filename, version=version) |
| 323 |
|
| 324 |
|
| 325 |
def download_libxslt(dest_dir, version=None): |
| 326 |
"""Downloads libxslt, returning the filename where the library was downloaded""" |
| 327 |
#version_re = re.compile(r'LATEST_LIBXSLT_IS_([0-9.]+[0-9](?:-[abrc0-9]+)?)') |
| 328 |
version_re = re.compile(r'libxslt-([0-9.]+[0-9])[.]tar[.]xz') |
| 329 |
filename = 'libxslt-%s.tar.xz' |
| 330 |
from_location = http_find_latest_version_directory(LIBXSLT_LOCATION, version=version) |
| 331 |
return download_library(dest_dir, from_location, 'libxslt', |
| 332 |
version_re, filename, version=version) |
| 333 |
|
| 334 |
|
| 335 |
def download_libiconv(dest_dir, version=None): |
| 336 |
"""Downloads libiconv, returning the filename where the library was downloaded""" |
| 337 |
version_re = re.compile(r'libiconv-([0-9.]+[0-9])[.]tar[.]gz') |
| 338 |
filename = 'libiconv-%s.tar.gz' |
| 339 |
return download_library(dest_dir, LIBICONV_LOCATION, 'libiconv', |
| 340 |
version_re, filename, version=version) |
| 341 |
|
| 342 |
|
| 343 |
def download_zlib(dest_dir, version): |
| 344 |
"""Downloads zlib, returning the filename where the library was downloaded""" |
| 345 |
version_re = re.compile(r'zlib-([0-9.]+[0-9])[.]tar[.]gz') |
| 346 |
filename = 'zlib-%s.tar.gz' |
| 347 |
return download_library(dest_dir, ZLIB_LOCATION, 'zlib', |
| 348 |
version_re, filename, version=version) |
| 349 |
|
| 350 |
|
| 351 |
def find_max_version(libname, filenames, version_re=None): |
| 352 |
if version_re is None: |
| 353 |
version_re = re.compile(r'%s-([0-9.]+[0-9](?:-[abrc0-9]+)?)' % libname) |
| 354 |
versions = [] |
| 355 |
for fn in filenames: |
| 356 |
match = version_re.search(fn) |
| 357 |
if match: |
| 358 |
version_string = match.group(1) |
| 359 |
versions.append(( |
| 360 |
tuple(map(tryint, version_string.replace("-", ".-").split('.'))), |
| 361 |
version_string, |
| 362 |
)) |
| 363 |
if not versions: |
| 364 |
raise Exception( |
| 365 |
"Could not find the most current version of %s from the files: %s" % ( |
| 366 |
libname, list(filenames))) |
| 367 |
versions.sort() |
| 368 |
version_string = versions[-1][-1] |
| 369 |
print('Latest version of %s is %s' % (libname, version_string)) |
| 370 |
return version_string |
| 371 |
|
| 372 |
|
| 373 |
def file_exists(file_path: Path, size=None, digest=None): |
| 374 |
if not file_path.exists(): |
| 375 |
return False |
| 376 |
if size is not None: |
| 377 |
if file_path.stat().st_size != size: |
| 378 |
return False |
| 379 |
if digest is not None and hasattr(hashlib, 'file_digest'): |
| 380 |
hash_alg = 'sha256' |
| 381 |
if ':' in digest: |
| 382 |
hash_alg, _, digest = digest.partition(':') |
| 383 |
with file_path.open(mode='rb') as f: |
| 384 |
file_digest = hashlib.file_digest(f, hash_alg) |
| 385 |
if digest != file_digest.hexdigest(): |
| 386 |
return False |
| 387 |
return True |
| 388 |
|
| 389 |
|
| 390 |
def download_library(dest_dir, location, name, version_re, filename, version=None): |
| 391 |
if version is None: |
| 392 |
try: |
| 393 |
if location.startswith('ftp://'): |
| 394 |
fns = list(remote_listdir(location)) |
| 395 |
else: |
| 396 |
fns = http_listfiles(location, '(%s)' % filename.replace('%s', '(?:[0-9.]+[0-9])')) |
| 397 |
print(f"Found {len(fns)} links at {location}") |
| 398 |
version = find_max_version(name, fns, version_re) |
| 399 |
except IOError: |
| 400 |
# network failure - maybe we have the files already? |
| 401 |
latest = (0,0,0) |
| 402 |
fns = os.listdir(dest_dir) |
| 403 |
for fn in fns: |
| 404 |
if fn.startswith(name+'-'): |
| 405 |
match = match_libfile_version(fn) |
| 406 |
if match: |
| 407 |
version_tuple = tuple(map(tryint, match.group(1).split('.'))) |
| 408 |
if version_tuple > latest: |
| 409 |
latest = version_tuple |
| 410 |
filename = fn |
| 411 |
version = None |
| 412 |
if latest == (0,0,0): |
| 413 |
raise |
| 414 |
if version: |
| 415 |
filename = filename % version |
| 416 |
|
| 417 |
full_url = urljoin(location, filename) |
| 418 |
dest_filepath = Path(dest_dir) / filename |
| 419 |
if file_exists(dest_filepath, digest=ARCHIVE_HASHES.get(filename)): |
| 420 |
print(f'Using existing {name} downloaded into {dest_filepath} ' |
| 421 |
'(delete this file if you want to re-download the package)') |
| 422 |
return dest_filepath |
| 423 |
|
| 424 |
print('Downloading %s into %s from %s' % (name, dest_filepath, full_url)) |
| 425 |
for retry_after_seconds in (2, 5, 10, None): |
| 426 |
try: |
| 427 |
urlretrieve(full_url, dest_filepath) |
| 428 |
except urllib.error.URLError as exc: |
| 429 |
if retry_after_seconds is None: |
| 430 |
print(f"Download failed: {exc}") |
| 431 |
break |
| 432 |
else: |
| 433 |
print(f"Download failed: {exc}, retrying in {int(retry_after_seconds)} seconds…") |
| 434 |
time.sleep(retry_after_seconds) |
| 435 |
else: |
| 436 |
if file_exists(dest_filepath, digest=ARCHIVE_HASHES.get(filename)): |
| 437 |
return dest_filepath |
| 438 |
|
| 439 |
if not file_exists(dest_filepath, digest=ARCHIVE_HASHES.get(filename)): |
| 440 |
raise RuntimeError(f"File download of {filename} failed to write the correct file.") |
| 441 |
|
| 442 |
return dest_filepath |
| 443 |
|
| 444 |
|
| 445 |
def unpack_tarball(tar_filename, dest) -> str: |
| 446 |
print('Unpacking %s into %s' % (os.path.basename(tar_filename), dest)) |
| 447 |
os_path = os.path |
| 448 |
abs_dest = os_path.abspath(dest) |
| 449 |
|
| 450 |
tar_cm = tarfile.open(tar_filename) |
| 451 |
|
| 452 |
if hasattr(tarfile, 'data_filter'): |
| 453 |
tar_cm.extraction_filter = tarfile.data_filter |
| 454 |
|
| 455 |
base_dir = None |
| 456 |
with closing(tar_cm) as tar: |
| 457 |
directories = [] |
| 458 |
for member in tar: |
| 459 |
# Guard against malicious tar file content. |
| 460 |
path = os_path.join(dest, member.name) |
| 461 |
abs_path = os_path.abspath(path) |
| 462 |
if not os_path.commonpath([abs_dest, abs_path]).startswith(abs_dest): |
| 463 |
raise RuntimeError('Unexpected path in %s: %s' % (tar_filename, member.name)) |
| 464 |
|
| 465 |
if member.isdir(): |
| 466 |
directories.append(member) |
| 467 |
continue |
| 468 |
elif member.issym() or member.islnk(): |
| 469 |
link_path = os_path.abspath(os_path.join( |
| 470 |
os_path.dirname(abs_path) if member.issym() else abs_dest, |
| 471 |
member.linkname)) |
| 472 |
if not os_path.commonpath([abs_dest, link_path]).startswith(abs_dest): |
| 473 |
raise RuntimeError('Unexpected path in %s: %s' % (tar_filename, member.name)) |
| 474 |
elif member.islnk(): |
| 475 |
link_path = os_path.abspath(os_path.join(abs_dest, member.linkname)) |
| 476 |
elif not member.isfile(): |
| 477 |
raise RuntimeError('Unexpected path in %s: %s' % (tar_filename, member.name)) |
| 478 |
|
| 479 |
# Find common base directory. |
| 480 |
first_dir = member.name.split('/')[0] |
| 481 |
if base_dir is None: |
| 482 |
base_dir = first_dir |
| 483 |
elif base_dir != first_dir: |
| 484 |
print('Unexpected path in %s: %s' % (tar_filename, first_dir)) |
| 485 |
continue |
| 486 |
|
| 487 |
# Extract only new files. |
| 488 |
if os_path.exists(abs_path) and os_path.getsize(abs_path) == member.size: |
| 489 |
continue |
| 490 |
tar.extract(member, abs_dest) |
| 491 |
|
| 492 |
# Update directory properties/times/etc. |
| 493 |
for member in directories: |
| 494 |
tar.extract(member, abs_dest) |
| 495 |
|
| 496 |
return os_path.join(dest, base_dir) |
| 497 |
|
| 498 |
|
| 499 |
def call_subprocess(cmd, **kw): |
| 500 |
import subprocess |
| 501 |
cwd = kw.get('cwd', '.') |
| 502 |
cmd_desc = ' '.join(cmd) |
| 503 |
print(f'Running "{cmd_desc}" in {cwd}') |
| 504 |
returncode = subprocess.call(cmd, **kw) |
| 505 |
if returncode: |
| 506 |
raise Exception('Command "%s" returned code %s' % (cmd_desc, returncode)) |
| 507 |
|
| 508 |
|
| 509 |
def safe_mkdir(dir): |
| 510 |
if not os.path.exists(dir): |
| 511 |
os.makedirs(dir) |
| 512 |
|
| 513 |
|
| 514 |
def cmmi(configure_cmd, build_dir, multicore=None, **call_setup): |
| 515 |
print('Starting build in %s' % build_dir) |
| 516 |
call_subprocess(configure_cmd, cwd=build_dir, **call_setup) |
| 517 |
if not multicore: |
| 518 |
make_jobs = multi_make_options |
| 519 |
elif int(multicore) > 1: |
| 520 |
make_jobs = ['-j%s' % multicore] |
| 521 |
else: |
| 522 |
make_jobs = [] |
| 523 |
call_subprocess( |
| 524 |
['make'] + make_jobs, |
| 525 |
cwd=build_dir, **call_setup) |
| 526 |
call_subprocess( |
| 527 |
['make'] + make_jobs + ['install'], |
| 528 |
cwd=build_dir, **call_setup) |
| 529 |
|
| 530 |
|
| 531 |
def configure_darwin_env(env_setup): |
| 532 |
import platform |
| 533 |
# configure target architectures on MacOS-X (x86_64 + Arm64, by default) |
| 534 |
major_version, minor_version = tuple(map(int, platform.mac_ver()[0].split('.')[:2])) |
| 535 |
if major_version >= 11: |
| 536 |
env_default = { |
| 537 |
'CFLAGS': "-arch x86_64 -arch arm64 -O3", |
| 538 |
'LDFLAGS': "-arch x86_64 -arch arm64", |
| 539 |
'MACOSX_DEPLOYMENT_TARGET': "11.0" |
| 540 |
} |
| 541 |
env_default.update(os.environ) |
| 542 |
env_setup['env'] = env_default |
| 543 |
|
| 544 |
|
| 545 |
def build_libxml2xslt( |
| 546 |
download_dir, build_dir, |
| 547 |
static_include_dirs, static_library_dirs, |
| 548 |
static_cflags, static_binaries, |
| 549 |
libxml2_version=None, |
| 550 |
libxslt_version=None, |
| 551 |
libiconv_version=None, |
| 552 |
zlib_version=None, |
| 553 |
multicore=None, |
| 554 |
with_zlib=True): |
| 555 |
lib_dirs = download_libs(download_dir, build_dir, |
| 556 |
libxml2_version, libxslt_version, libiconv_version, zlib_version, with_zlib=with_zlib) |
| 557 |
return build_libs( |
| 558 |
build_dir, lib_dirs, |
| 559 |
static_include_dirs, static_library_dirs, static_cflags, static_binaries, |
| 560 |
libxml2_version=libxml2_version, |
| 561 |
multicore=multicore, |
| 562 |
with_zlib=with_zlib, |
| 563 |
) |
| 564 |
|
| 565 |
|
| 566 |
def download_libs( |
| 567 |
download_dir, build_dir, |
| 568 |
libxml2_version=None, |
| 569 |
libxslt_version=None, |
| 570 |
libiconv_version=None, |
| 571 |
zlib_version=None, |
| 572 |
with_zlib=True): |
| 573 |
safe_mkdir(download_dir) |
| 574 |
safe_mkdir(build_dir) |
| 575 |
|
| 576 |
zlib_dir = None |
| 577 |
if with_zlib: |
| 578 |
zlib_dir = unpack_tarball(download_zlib(download_dir, zlib_version), build_dir) |
| 579 |
|
| 580 |
libiconv_dir = unpack_tarball(download_libiconv(download_dir, libiconv_version), build_dir) |
| 581 |
libxml2_dir = unpack_tarball(download_libxml2(download_dir, libxml2_version), build_dir) |
| 582 |
libxslt_dir = unpack_tarball(download_libxslt(download_dir, libxslt_version), build_dir) |
| 583 |
|
| 584 |
# Patch after unpacking to assure a clean target directory. |
| 585 |
_patch_library(zlib_dir) |
| 586 |
_patch_library(libiconv_dir) |
| 587 |
_patch_library(libxml2_dir) |
| 588 |
_patch_library(libxslt_dir) |
| 589 |
|
| 590 |
return zlib_dir, libiconv_dir, libxml2_dir, libxslt_dir |
| 591 |
|
| 592 |
|
| 593 |
LIBRARY_PATCHES = { |
| 594 |
"libxslt-1.1.43": "libxslt-1.1.43-backport1.patch", |
| 595 |
} |
| 596 |
|
| 597 |
|
| 598 |
def _patch_library(libdir): |
| 599 |
if not libdir: |
| 600 |
return |
| 601 |
dirname = os.path.basename(libdir) |
| 602 |
if dirname not in LIBRARY_PATCHES: |
| 603 |
return |
| 604 |
patch_file = LIBRARY_PATCHES[dirname] |
| 605 |
|
| 606 |
from patch_lxml_deplibs import apply_patch_file |
| 607 |
print(f"Applying patch {patch_file} to {libdir}") |
| 608 |
apply_patch_file(patch_file, libdir) |
| 609 |
|
| 610 |
|
| 611 |
def build_libs( |
| 612 |
build_dir, lib_dirs, |
| 613 |
static_include_dirs, static_library_dirs, |
| 614 |
static_cflags, static_binaries, |
| 615 |
libxml2_version=None, |
| 616 |
multicore=None, |
| 617 |
with_zlib=True): |
| 618 |
zlib_dir, libiconv_dir, libxml2_dir, libxslt_dir = lib_dirs |
| 619 |
|
| 620 |
prefix = os.path.join(os.path.abspath(build_dir), 'libxml2') |
| 621 |
lib_dir = os.path.join(prefix, 'lib') |
| 622 |
safe_mkdir(prefix) |
| 623 |
|
| 624 |
lib_names = ['libxml2', 'libexslt', 'libxslt', 'iconv'] + (['libz'] if with_zlib else []) |
| 625 |
existing_libs = { |
| 626 |
lib: os.path.join(lib_dir, filename) |
| 627 |
for lib in lib_names |
| 628 |
for filename in os.listdir(lib_dir) |
| 629 |
if lib in filename and filename.endswith('.a') |
| 630 |
} if os.path.isdir(lib_dir) else {} |
| 631 |
|
| 632 |
def has_current_lib(name, build_dir, _build_all_following=[False]): |
| 633 |
if _build_all_following[0]: |
| 634 |
return False # a dependency was rebuilt => rebuilt this lib as well |
| 635 |
lib_file = existing_libs.get(name) |
| 636 |
found = lib_file and os.path.getmtime(lib_file) > os.path.getmtime(build_dir) |
| 637 |
if found: |
| 638 |
print("Found pre-built '%s'" % name) |
| 639 |
else: |
| 640 |
# also rebuild all following libs (which may depend on this one) |
| 641 |
_build_all_following[0] = True |
| 642 |
return found |
| 643 |
|
| 644 |
call_setup = {} |
| 645 |
if sys_platform == 'darwin': |
| 646 |
configure_darwin_env(call_setup) |
| 647 |
|
| 648 |
configure_cmd = ['./configure', |
| 649 |
'--disable-dependency-tracking', |
| 650 |
'--disable-shared', |
| 651 |
'--prefix=%s' % prefix, |
| 652 |
] |
| 653 |
|
| 654 |
# build zlib |
| 655 |
if with_zlib: |
| 656 |
zlib_configure_cmd = [ |
| 657 |
'./configure', |
| 658 |
'--prefix=%s' % prefix, |
| 659 |
] |
| 660 |
if not has_current_lib("libz", zlib_dir): |
| 661 |
cmmi(zlib_configure_cmd, zlib_dir, multicore, **call_setup) |
| 662 |
|
| 663 |
# build libiconv |
| 664 |
if not has_current_lib("iconv", libiconv_dir): |
| 665 |
cmmi(configure_cmd, libiconv_dir, multicore, **call_setup) |
| 666 |
|
| 667 |
# build libxml2 |
| 668 |
libxml2_configure_cmd = configure_cmd + [ |
| 669 |
'--without-python', |
| 670 |
'--with-iconv=%s' % prefix, |
| 671 |
('--with-zlib=%s' % prefix) if with_zlib else '--without-zlib', |
| 672 |
] |
| 673 |
|
| 674 |
if not libxml2_version: |
| 675 |
libxml2_version = os.path.basename(libxml2_dir).split('-', 1)[-1] |
| 676 |
|
| 677 |
if tuple(map(tryint, libxml2_version.split('-', 1)[0].split('.'))) >= (2, 9, 5): |
| 678 |
libxml2_configure_cmd.append('--without-lzma') # can't currently build that |
| 679 |
|
| 680 |
try: |
| 681 |
if tuple(map(tryint, libxml2_version.split('-', 1)[0].split('.'))) >= (2, 7, 3): |
| 682 |
libxml2_configure_cmd.append('--enable-rebuild-docs=no') |
| 683 |
except Exception: |
| 684 |
pass # this isn't required, so ignore any errors |
| 685 |
if not has_current_lib("libxml2", libxml2_dir): |
| 686 |
if not os.path.exists(os.path.join(libxml2_dir, "configure")): |
| 687 |
# Allow building from git sources by running autoconf etc. |
| 688 |
libxml2_configure_cmd[0] = "./autogen.sh" |
| 689 |
cmmi(libxml2_configure_cmd, libxml2_dir, multicore, **call_setup) |
| 690 |
|
| 691 |
# Fix up libxslt configure script (needed up to and including 1.1.34) |
| 692 |
# https://gitlab.gnome.org/GNOME/libxslt/-/commit/90c34c8bb90e095a8a8fe8b2ce368bd9ff1837cc |
| 693 |
with open(os.path.join(libxslt_dir, "configure"), 'rb') as f: |
| 694 |
config_script = f.read() |
| 695 |
if b' --libs print ' in config_script: |
| 696 |
config_script = config_script.replace(b' --libs print ', b' --libs ') |
| 697 |
with open(os.path.join(libxslt_dir, "configure"), 'wb') as f: |
| 698 |
f.write(config_script) |
| 699 |
|
| 700 |
# build libxslt |
| 701 |
libxslt_configure_cmd = configure_cmd + [ |
| 702 |
'--without-python', |
| 703 |
'--with-libxml-prefix=%s' % prefix, |
| 704 |
'--without-crypto', |
| 705 |
] |
| 706 |
if not (has_current_lib("libxslt", libxslt_dir) and has_current_lib("libexslt", libxslt_dir)): |
| 707 |
cmmi(libxslt_configure_cmd, libxslt_dir, multicore, **call_setup) |
| 708 |
|
| 709 |
# collect build setup for lxml |
| 710 |
xslt_config = os.path.join(prefix, 'bin', 'xslt-config') |
| 711 |
xml2_config = os.path.join(prefix, 'bin', 'xml2-config') |
| 712 |
|
| 713 |
static_include_dirs.extend([ |
| 714 |
os.path.join(prefix, 'include'), |
| 715 |
os.path.join(prefix, 'include', 'libxml2'), |
| 716 |
os.path.join(prefix, 'include', 'libxslt'), |
| 717 |
os.path.join(prefix, 'include', 'libexslt')]) |
| 718 |
static_library_dirs.append(lib_dir) |
| 719 |
|
| 720 |
listdir = os.listdir(lib_dir) |
| 721 |
static_binaries += [os.path.join(lib_dir, filename) |
| 722 |
for lib in lib_names |
| 723 |
for filename in listdir |
| 724 |
if lib in filename and filename.endswith('.a')] |
| 725 |
|
| 726 |
return xml2_config, xslt_config |
| 727 |
|
| 728 |
|
| 729 |
def main(with_zlib=True, download_only=False, platform=None): |
| 730 |
static_include_dirs = [] |
| 731 |
static_library_dirs = [] |
| 732 |
download_dir = "libs" |
| 733 |
|
| 734 |
arch = None |
| 735 |
if platform is None: |
| 736 |
platform = sys_platform |
| 737 |
elif platform in ('win32', 'win64', 'win_arm64'): |
| 738 |
arch = platform |
| 739 |
|
| 740 |
if platform.startswith('win'): |
| 741 |
return get_prebuilt_libxml2xslt( |
| 742 |
download_dir, static_include_dirs, static_library_dirs, arch=arch) |
| 743 |
|
| 744 |
get_env = os.environ.get |
| 745 |
zlib_version = get_env('ZLIB_VERSION') |
| 746 |
libiconv_version = get_env('LIBICONV_VERSION') |
| 747 |
libxml2_version = get_env('LIBXML2_VERSION') |
| 748 |
libxslt_version = get_env('LIBXSLT_VERSION') |
| 749 |
|
| 750 |
build_dir = 'build/tmp' |
| 751 |
lib_dirs = download_libs( |
| 752 |
download_dir, build_dir, |
| 753 |
libxml2_version=libxml2_version, |
| 754 |
libxslt_version=libxslt_version, |
| 755 |
libiconv_version=libiconv_version, |
| 756 |
zlib_version=zlib_version, |
| 757 |
with_zlib=with_zlib, |
| 758 |
) |
| 759 |
if download_only: |
| 760 |
return None, None |
| 761 |
|
| 762 |
return build_libs( |
| 763 |
build_dir, lib_dirs, |
| 764 |
static_include_dirs, static_library_dirs, |
| 765 |
static_cflags=[], |
| 766 |
static_binaries=[], |
| 767 |
libxml2_version=libxml2_version, |
| 768 |
with_zlib=with_zlib, |
| 769 |
) |
| 770 |
|
| 771 |
|
| 772 |
if __name__ == '__main__': |
| 773 |
args = sys.argv[1:] |
| 774 |
download_only = '--download-only' in args |
| 775 |
if download_only: |
| 776 |
args.remove('--download-only') |
| 777 |
platform_arg = args[0] if args else None |
| 778 |
if platform_arg: |
| 779 |
# change global sys_platform setting |
| 780 |
sys_platform = platform_arg |
| 781 |
main(download_only=download_only, platform=platform_arg) |