Debian Codegraph @

setupinfo.py

raw
1 import sys
2 import io
3 import os
4 import os.path
5 import subprocess
6
7 from setuptools.command.build_ext import build_ext as _build_ext
8 from distutils.core import Extension
9 from distutils.errors import CompileError, DistutilsOptionError
10 from versioninfo import get_base_dir
11
12 try:
13 import Cython.Compiler.Version
14 CYTHON_INSTALLED = True
15 except ImportError:
16 CYTHON_INSTALLED = False
17
18 EXT_MODULES = ["lxml.etree", "lxml.objectify"]
19 COMPILED_MODULES = [
20 "lxml.builder",
21 "lxml._elementpath",
22 "lxml.html.diff",
23 "lxml.html._difflib",
24 "lxml.sax",
25 ]
26 HEADER_FILES = ['etree.h', 'etree_api.h']
27
28 if hasattr(sys, 'pypy_version_info') or (
29 getattr(sys, 'implementation', None) and sys.implementation.name != 'cpython'):
30 # disable Cython compilation of Python modules in PyPy and other non-CPythons
31 del COMPILED_MODULES[:]
32
33 SOURCE_PATH = "src"
34 INCLUDE_PACKAGE_PATH = os.path.join(SOURCE_PATH, 'lxml', 'includes')
35
36 _system_encoding = sys.getdefaultencoding()
37 if _system_encoding is None:
38 _system_encoding = "iso-8859-1" # :-)
39
40 def decode_input(data):
41 if isinstance(data, str):
42 return data
43 return data.decode(_system_encoding)
44
45 def env_var(name):
46 value = os.getenv(name)
47 if value:
48 value = decode_input(value)
49 if sys.platform == 'win32' and ';' in value:
50 return value.split(';')
51 else:
52 return value.split()
53 else:
54 return []
55
56
57 def _prefer_reldirs(base_dir, dirs):
58 return [
59 os.path.relpath(path) if path.startswith(base_dir) else path
60 for path in dirs
61 ]
62
63 def ext_modules(static_include_dirs, static_library_dirs,
64 static_cflags, static_binaries):
65 global XML2_CONFIG, XSLT_CONFIG
66 if OPTION_BUILD_LIBXML2XSLT:
67 from buildlibxml import build_libxml2xslt, get_prebuilt_libxml2xslt
68 if sys.platform.startswith('win'):
69 get_prebuilt_libxml2xslt(
70 OPTION_DOWNLOAD_DIR, static_include_dirs, static_library_dirs)
71 else:
72 XML2_CONFIG, XSLT_CONFIG = build_libxml2xslt(
73 OPTION_DOWNLOAD_DIR, 'build/tmp',
74 static_include_dirs, static_library_dirs,
75 static_cflags, static_binaries,
76 libiconv_version=OPTION_LIBICONV_VERSION,
77 libxml2_version=OPTION_LIBXML2_VERSION,
78 libxslt_version=OPTION_LIBXSLT_VERSION,
79 zlib_version=OPTION_ZLIB_VERSION,
80 with_zlib=OPTION_WITH_ZLIB,
81 multicore=OPTION_MULTICORE,
82 )
83
84 modules = EXT_MODULES + COMPILED_MODULES
85 if OPTION_WITHOUT_OBJECTIFY:
86 modules = [entry for entry in modules if 'objectify' not in entry]
87
88 module_files = list(os.path.join(SOURCE_PATH, *module.split('.')) for module in modules)
89 c_files_exist = [os.path.exists(module + '.c') for module in module_files]
90
91 use_cython = True
92 if CYTHON_INSTALLED and (OPTION_WITH_CYTHON or not all(c_files_exist)):
93 print("Building with Cython %s." % Cython.Compiler.Version.version)
94 # generate module cleanup code
95 from Cython.Compiler import Options
96 Options.generate_cleanup_code = 3
97 Options.clear_to_none = False
98 elif not OPTION_WITHOUT_CYTHON and not all(c_files_exist):
99 for exists, module in zip(c_files_exist, module_files):
100 if not exists:
101 raise RuntimeError(
102 "ERROR: Trying to build without Cython, but pre-generated '%s.c' "
103 "is not available (to ignore this error, pass --without-cython or "
104 "set environment variable WITHOUT_CYTHON=true)." % module)
105 else:
106 if not all(c_files_exist):
107 for exists, module in zip(c_files_exist, module_files):
108 if not exists:
109 print("WARNING: Trying to build without Cython, but pre-generated "
110 "'%s.c' is not available." % module)
111 use_cython = False
112 print("Building without Cython.")
113
114 if not check_build_dependencies():
115 raise RuntimeError("Dependency missing")
116
117 base_dir = get_base_dir()
118 _include_dirs = _prefer_reldirs(
119 base_dir, include_dirs(static_include_dirs) + [
120 SOURCE_PATH,
121 INCLUDE_PACKAGE_PATH,
122 ])
123 _library_dirs = _prefer_reldirs(base_dir, library_dirs(static_library_dirs))
124 _cflags = cflags(static_cflags)
125 _ldflags = ['-isysroot', get_xcode_isysroot()] if sys.platform == 'darwin' else None
126 _define_macros = define_macros()
127 _libraries = libraries()
128
129 if _library_dirs:
130 message = "Building against libxml2/libxslt in "
131 if len(_library_dirs) > 1:
132 print(message + "one of the following directories:")
133 for dir in _library_dirs:
134 print(" " + dir)
135 else:
136 print(message + "the following directory: " +
137 _library_dirs[0])
138
139 if OPTION_AUTO_RPATH:
140 runtime_library_dirs = _library_dirs
141 else:
142 runtime_library_dirs = []
143
144 if CYTHON_INSTALLED and OPTION_SHOW_WARNINGS:
145 from Cython.Compiler import Errors
146 Errors.LEVEL = 0
147
148 cythonize_directives = {
149 'binding': True,
150 }
151 if OPTION_WITH_COVERAGE:
152 cythonize_directives['linetrace'] = True
153
154 result = []
155 for module, src_file in zip(modules, module_files):
156 is_py = module in COMPILED_MODULES
157 main_module_source = src_file + (
158 '.c' if not use_cython else '.py' if is_py else '.pyx')
159 result.append(
160 Extension(
161 module,
162 sources = [main_module_source],
163 depends = find_dependencies(module),
164 extra_compile_args = _cflags,
165 extra_link_args = None if is_py else _ldflags,
166 extra_objects = None if is_py else static_binaries,
167 define_macros = _define_macros,
168 include_dirs = _include_dirs,
169 library_dirs = None if is_py else _library_dirs,
170 runtime_library_dirs = None if is_py else runtime_library_dirs,
171 libraries = None if is_py else _libraries,
172 ))
173 if CYTHON_INSTALLED and OPTION_WITH_CYTHON_GDB:
174 for ext in result:
175 ext.cython_gdb = True
176
177 if CYTHON_INSTALLED and use_cython:
178 # build .c files right now and convert Extension() objects
179 from Cython.Build import cythonize
180 result = cythonize(result, compiler_directives=cythonize_directives)
181
182 # for backwards compatibility reasons, provide "etree[_api].h" also as "lxml.etree[_api].h"
183 for header_filename in HEADER_FILES:
184 src_file = os.path.join(SOURCE_PATH, 'lxml', header_filename)
185 dst_file = os.path.join(SOURCE_PATH, 'lxml', 'lxml.' + header_filename)
186 if not os.path.exists(src_file):
187 continue
188 if os.path.exists(dst_file) and os.path.getmtime(dst_file) >= os.path.getmtime(src_file):
189 continue
190
191 with io.open(src_file, 'r', encoding='iso8859-1') as f:
192 content = f.read()
193 for filename in HEADER_FILES:
194 content = content.replace('"%s"' % filename, '"lxml.%s"' % filename)
195 with io.open(dst_file, 'w', encoding='iso8859-1') as f:
196 f.write(content)
197
198 return result
199
200
201 def find_dependencies(module):
202 if not CYTHON_INSTALLED or 'lxml.html' in module:
203 return []
204 base_dir = get_base_dir()
205 package_dir = os.path.join(base_dir, SOURCE_PATH, 'lxml')
206 includes_dir = os.path.join(base_dir, INCLUDE_PACKAGE_PATH)
207
208 pxd_files = [
209 os.path.join(INCLUDE_PACKAGE_PATH, filename)
210 for filename in os.listdir(includes_dir)
211 if filename.endswith('.pxd')
212 ]
213
214 if module == 'lxml.etree':
215 pxi_files = [
216 os.path.join(SOURCE_PATH, 'lxml', filename)
217 for filename in os.listdir(package_dir)
218 if filename.endswith('.pxi') and 'objectpath' not in filename
219 ]
220 pxd_files = [
221 filename for filename in pxd_files
222 if 'etreepublic' not in filename
223 ]
224 elif module == 'lxml.objectify':
225 pxi_files = [os.path.join(SOURCE_PATH, 'lxml', 'objectpath.pxi')]
226 else:
227 pxi_files = pxd_files = []
228
229 return pxd_files + pxi_files
230
231
232 def extra_setup_args():
233 class CheckLibxml2BuildExt(_build_ext):
234 """Subclass to check whether libxml2 is really available if the build fails"""
235 def run(self):
236 try:
237 _build_ext.run(self) # old-style class in Py2
238 except CompileError as e:
239 print('Compile failed: %s' % e)
240 if not seems_to_have_libxml2():
241 print_libxml_error()
242 raise
243 result = {'cmdclass': {'build_ext': CheckLibxml2BuildExt}}
244 return result
245
246
247 def seems_to_have_libxml2():
248 from distutils import ccompiler
249 compiler = ccompiler.new_compiler()
250 return compiler.has_function(
251 'xmlXPathInit',
252 include_dirs=include_dirs([]) + ['/usr/include/libxml2'],
253 includes=['libxml/xpath.h'],
254 library_dirs=library_dirs([]),
255 libraries=['xml2'])
256
257
258 def print_libxml_error():
259 print('*********************************************************************************')
260 print("Could not find function xmlXPathInit in library libxml2. Is libxml2 installed?")
261 print("Is your C compiler installed and configured correctly?")
262 if sys.platform in ('darwin',):
263 print('Perhaps try: xcode-select --install')
264 print('*********************************************************************************')
265
266
267 def libraries():
268 standard_libs = []
269 if 'linux' in sys.platform:
270 standard_libs.append('rt')
271 if not OPTION_BUILD_LIBXML2XSLT:
272 standard_libs.append('z')
273 standard_libs.append('m')
274
275 if sys.platform in ('win32',):
276 libs = ['libxslt', 'libexslt', 'libxml2', 'iconv']
277 if OPTION_STATIC:
278 libs = ['%s_a' % lib for lib in libs]
279 libs.extend(['zlib', 'WS2_32'])
280 elif OPTION_STATIC:
281 libs = standard_libs
282 else:
283 libs = ['xslt', 'exslt', 'xml2'] + standard_libs
284 return libs
285
286 def library_dirs(static_library_dirs):
287 if OPTION_STATIC:
288 if not static_library_dirs:
289 static_library_dirs = env_var('LIBRARY')
290 assert static_library_dirs, "Static build not configured, see doc/build.txt"
291 return static_library_dirs
292 # filter them from xslt-config --libs
293 result = []
294 possible_library_dirs = flags('libs')
295 for possible_library_dir in possible_library_dirs:
296 if possible_library_dir.startswith('-L'):
297 result.append(possible_library_dir[2:])
298 return result
299
300 def include_dirs(static_include_dirs):
301 if OPTION_STATIC:
302 if not static_include_dirs:
303 static_include_dirs = env_var('INCLUDE')
304 return static_include_dirs
305 # filter them from xslt-config --cflags
306 result = []
307 possible_include_dirs = flags('cflags')
308 for possible_include_dir in possible_include_dirs:
309 if possible_include_dir.startswith('-I'):
310 result.append(possible_include_dir[2:])
311 return result
312
313 def cflags(static_cflags):
314 result = []
315 if not OPTION_SHOW_WARNINGS:
316 result.append('-w')
317 if OPTION_DEBUG_GCC:
318 result.append('-g2')
319
320 if OPTION_STATIC:
321 if not static_cflags:
322 static_cflags = env_var('CFLAGS')
323 result.extend(static_cflags)
324 else:
325 # anything from xslt-config --cflags that doesn't start with -I
326 possible_cflags = flags('cflags')
327 for possible_cflag in possible_cflags:
328 if not possible_cflag.startswith('-I'):
329 result.append(possible_cflag)
330
331 return result
332
333 def define_macros():
334 macros = []
335 if OPTION_WITHOUT_ASSERT:
336 macros.append(('PYREX_WITHOUT_ASSERTIONS', None))
337 if OPTION_WITHOUT_THREADING:
338 macros.append(('WITHOUT_THREADING', None))
339 if OPTION_WITH_REFNANNY:
340 macros.append(('CYTHON_REFNANNY', None))
341 if OPTION_WITH_UNICODE_STRINGS:
342 macros.append(('LXML_UNICODE_STRINGS', '1'))
343 if OPTION_WITH_COVERAGE:
344 macros.append(('CYTHON_TRACE_NOGIL', '1'))
345 # coverage.py does not support Cython together with sys.monitoring.
346 # See https://github.com/nedbat/coveragepy/issues/1790
347 macros.append(('CYTHON_USE_SYS_MONITORING', '0'))
348 if OPTION_BUILD_LIBXML2XSLT:
349 macros.append(('LIBXML_STATIC', None))
350 macros.append(('LIBXSLT_STATIC', None))
351 macros.append(('LIBEXSLT_STATIC', None))
352 # Disable showing C lines in tracebacks, unless explicitly requested.
353 macros.append(('CYTHON_CLINE_IN_TRACEBACK', '1' if OPTION_WITH_CLINES else '0'))
354 return macros
355
356
357 def run_command(cmd, *args):
358 if not cmd:
359 return ''
360 if args:
361 cmd = ' '.join((cmd,) + args)
362
363 p = subprocess.Popen(cmd, shell=True,
364 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
365 stdout_data, errors = p.communicate()
366
367 if p.returncode != 0 and errors:
368 return ''
369 return decode_input(stdout_data).strip()
370
371
372 def check_min_version(version, min_version, libname):
373 if not version:
374 # this is ok for targets like sdist etc.
375 return True
376 lib_version = tuple(map(int, version.split('.')[:3]))
377 req_version = tuple(map(int, min_version.split('.')[:3]))
378 if lib_version < req_version:
379 print("Minimum required version of %s is %s. Your system has version %s." % (
380 libname, min_version, version))
381 return False
382 return True
383
384
385 def get_library_version(prog, libname=None):
386 if libname:
387 return run_command(prog, '--modversion %s' % libname)
388 else:
389 return run_command(prog, '--version')
390
391
392 PKG_CONFIG = None
393 XML2_CONFIG = None
394 XSLT_CONFIG = None
395
396 def get_library_versions():
397 global XML2_CONFIG, XSLT_CONFIG
398
399 # Pre-built libraries
400 if XML2_CONFIG and XSLT_CONFIG:
401 xml2_version = get_library_version(XML2_CONFIG)
402 xslt_version = get_library_version(XSLT_CONFIG)
403 return xml2_version, xslt_version
404
405 # Path to xml2-config and xslt-config specified on the command line
406 if OPTION_WITH_XML2_CONFIG:
407 xml2_version = get_library_version(OPTION_WITH_XML2_CONFIG)
408 if xml2_version and OPTION_WITH_XSLT_CONFIG:
409 xslt_version = get_library_version(OPTION_WITH_XSLT_CONFIG)
410 if xslt_version:
411 XML2_CONFIG = OPTION_WITH_XML2_CONFIG
412 XSLT_CONFIG = OPTION_WITH_XSLT_CONFIG
413 return xml2_version, xslt_version
414
415 # Try pkg-config
416 global PKG_CONFIG
417 PKG_CONFIG = os.getenv('PKG_CONFIG', 'pkg-config')
418 xml2_version = get_library_version(PKG_CONFIG, 'libxml-2.0')
419 if xml2_version:
420 xslt_version = get_library_version(PKG_CONFIG, 'libxslt')
421 if xml2_version and xslt_version:
422 return xml2_version, xslt_version
423
424 # Try xml2-config and xslt-config
425 XML2_CONFIG = os.getenv('XML2_CONFIG', 'xml2-config')
426 xml2_version = get_library_version(XML2_CONFIG)
427 if xml2_version:
428 XSLT_CONFIG = os.getenv('XSLT_CONFIG', 'xslt-config')
429 xslt_version = get_library_version(XSLT_CONFIG)
430 if xml2_version and xslt_version:
431 return xml2_version, xslt_version
432
433 # One or both build dependencies not found. Fail on Linux platforms only.
434 if sys.platform.startswith('win'):
435 return '', ''
436 print("Error: Please make sure the libxml2 and libxslt development packages are installed.")
437 sys.exit(1)
438
439
440 def check_build_dependencies():
441 xml2_version, xslt_version = get_library_versions()
442
443 xml2_ok = check_min_version(xml2_version, '2.7.0', 'libxml2')
444 xslt_ok = check_min_version(xslt_version, '1.1.23', 'libxslt')
445
446 if not OPTION_BUILD_LIBXML2XSLT and xml2_version in ('2.9.11', '2.9.12'):
447 print("\n"
448 "WARNING: The stock libxml2 versions 2.9.11 and 2.9.12 are incompatible"
449 " with this lxml version. "
450 "They produce excess content on serialisation. "
451 "Use a different library version or a static build."
452 "\n")
453
454 if xml2_version and xslt_version:
455 print("Building against libxml2 %s and libxslt %s" % (xml2_version, xslt_version))
456 else:
457 print("Building against pre-built libxml2 andl libxslt libraries")
458
459 return (xml2_ok and xslt_ok)
460
461
462 def get_flags(prog, option, libname=None):
463 if libname:
464 return run_command(prog, '--%s %s' % (option, libname))
465 else:
466 return run_command(prog, '--%s' % option)
467
468
469 def flags(option):
470 if XML2_CONFIG:
471 xml2_flags = get_flags(XML2_CONFIG, option)
472 xslt_flags = get_flags(XSLT_CONFIG, option)
473 else:
474 xml2_flags = get_flags(PKG_CONFIG, option, 'libxml-2.0')
475 xslt_flags = get_flags(PKG_CONFIG, option, 'libxslt')
476
477 flag_list = xml2_flags.split()
478 for flag in xslt_flags.split():
479 if flag not in flag_list:
480 flag_list.append(flag)
481 return flag_list
482
483
484 def get_xcode_isysroot():
485 return run_command('xcrun', '--show-sdk-path')
486
487
488 ## Option handling:
489
490 def has_option(name):
491 try:
492 sys.argv.remove('--%s' % name)
493 return True
494 except ValueError:
495 pass
496 # allow passing all cmd line options also as environment variables
497 env_val = os.getenv(name.upper().replace('-', '_'), 'false').lower()
498 if env_val == "true":
499 return True
500 return False
501
502
503 def option_value(name, deprecated_for=None):
504 for index, option in enumerate(sys.argv):
505 if option == '--' + name:
506 if index+1 >= len(sys.argv):
507 raise DistutilsOptionError(
508 'The option %s requires a value' % option)
509 value = sys.argv[index+1]
510 sys.argv[index:index+2] = []
511 if deprecated_for:
512 print_deprecated_option(name, deprecated_for)
513 return value
514 if option.startswith('--' + name + '='):
515 value = option[len(name)+3:]
516 sys.argv[index:index+1] = []
517 if deprecated_for:
518 print_deprecated_option(name, deprecated_for)
519 return value
520 env_name = name.upper().replace('-', '_')
521 env_val = os.getenv(env_name)
522 if env_val and deprecated_for:
523 print_deprecated_option(env_name, deprecated_for.upper().replace('-', '_'))
524 return env_val or None
525
526
527 def print_deprecated_option(name, new_name):
528 print("WARN: Option '%s' is deprecated. Use '%s' instead." % (name, new_name))
529
530
531 staticbuild = bool(os.environ.get('STATICBUILD', ''))
532 # pick up any commandline options and/or env variables
533 OPTION_WITHOUT_OBJECTIFY = has_option('without-objectify')
534 OPTION_WITH_UNICODE_STRINGS = has_option('with-unicode-strings')
535 OPTION_WITHOUT_ASSERT = has_option('without-assert')
536 OPTION_WITHOUT_THREADING = has_option('without-threading')
537 OPTION_WITHOUT_CYTHON = has_option('without-cython')
538 OPTION_WITH_CYTHON = has_option('with-cython')
539 OPTION_WITH_CYTHON_GDB = has_option('cython-gdb')
540 OPTION_WITH_REFNANNY = has_option('with-refnanny')
541 OPTION_WITH_COVERAGE = has_option('with-coverage')
542 OPTION_WITH_CLINES = has_option('with-clines')
543 OPTION_WITH_ZLIB = not has_option('without-zlib')
544 if OPTION_WITHOUT_CYTHON:
545 CYTHON_INSTALLED = False
546 OPTION_STATIC = staticbuild or has_option('static')
547 OPTION_DEBUG_GCC = has_option('debug-gcc')
548 OPTION_SHOW_WARNINGS = has_option('warnings')
549 OPTION_AUTO_RPATH = has_option('auto-rpath')
550 OPTION_BUILD_LIBXML2XSLT = staticbuild or has_option('static-deps')
551 if OPTION_BUILD_LIBXML2XSLT:
552 OPTION_STATIC = True
553 OPTION_WITH_XML2_CONFIG = option_value('with-xml2-config') or option_value('xml2-config', deprecated_for='with-xml2-config')
554 OPTION_WITH_XSLT_CONFIG = option_value('with-xslt-config') or option_value('xslt-config', deprecated_for='with-xslt-config')
555 OPTION_LIBXML2_VERSION = option_value('libxml2-version')
556 OPTION_LIBXSLT_VERSION = option_value('libxslt-version')
557 OPTION_LIBICONV_VERSION = option_value('libiconv-version')
558 OPTION_ZLIB_VERSION = option_value('zlib-version')
559 OPTION_MULTICORE = option_value('multicore')
560 OPTION_DOWNLOAD_DIR = option_value('download-dir')
561 if OPTION_DOWNLOAD_DIR is None:
562 OPTION_DOWNLOAD_DIR = 'libs'