title
stringclasses
1 value
text
stringlengths
46
1.11M
id
stringlengths
27
30
matplotlib/setupext.py/add_libagg_flags def add_libagg_flags(ext): # We need a patched Agg not available elsewhere, so always use the vendored # version. ext.include_dirs.insert(0, "extern/agg24-svn/include")
negative_train_query273_06699
matplotlib/setupext.py/add_libagg_flags_and_sources def add_libagg_flags_and_sources(ext): # We need a patched Agg not available elsewhere, so always use the vendored # version. ext.include_dirs.insert(0, "extern/agg24-svn/include") agg_sources = [ "agg_bezier_arc.cpp", "agg_curves.cpp", "agg_image_filters.cpp", "agg_trans_affine.cpp", "agg_vcgen_contour.cpp", "agg_vcgen_dash.cpp", "agg_vcgen_stroke.cpp", "agg_vpgen_segmentator.cpp", ] ext.sources.extend( os.path.join("extern", "agg24-svn", "src", x) for x in agg_sources)
negative_train_query273_06700
matplotlib/setupext.py/get_ccompiler def get_ccompiler(): """ Return a new CCompiler instance. CCompiler used to be constructible via `distutils.ccompiler.new_compiler`, but this API was removed as part of the distutils deprecation. Instead, we trick setuptools into instantiating it by creating a dummy Distribution with a list of extension modules that claims to be truthy, but is actually empty, and then running the Distribution's build_ext command. (If using a plain empty ext_modules, build_ext would early-return without doing anything.) """ class L(list): def __bool__(self): return True build_ext = Distribution({"ext_modules": L()}).get_command_obj("build_ext") build_ext.finalize_options() build_ext.run() return build_ext.compiler
negative_train_query273_06701
matplotlib/setupext.py/print_raw def print_raw(*args, **kwargs): pass # Suppress our own output.
negative_train_query273_06702
matplotlib/setupext.py/SetupPackage/check class SetupPackage: def check(self): """ If the package should be installed, return an informative string, or None if no information should be displayed at all. If the package should be skipped, raise a `Skipped` exception. If a missing build dependency is fatal, call `sys.exit`. """
negative_train_query273_06703
matplotlib/setupext.py/SetupPackage/get_package_data class SetupPackage: def get_package_data(self): """ Get a package data dictionary to add to the configuration. These are merged into to the *package_data* list passed to `setuptools.setup`. """ return {}
negative_train_query273_06704
matplotlib/setupext.py/SetupPackage/get_extensions class SetupPackage: def get_extensions(self): """ Return or yield a list of C extensions (`distutils.core.Extension` objects) to add to the configuration. These are added to the *extensions* list passed to `setuptools.setup`. """ return []
negative_train_query273_06705
matplotlib/setupext.py/SetupPackage/do_custom_build class SetupPackage: def do_custom_build(self, env): """ If a package needs to do extra custom things, such as building a third-party library, before building an extension, it should override this method. """
negative_train_query273_06706
matplotlib/setupext.py/OptionalPackage/check class OptionalPackage: def check(self): """ Check whether ``mplsetup.cfg`` requests this package to be installed. May be overridden by subclasses for additional checks. """ if config.getboolean("packages", self.name, fallback=self.default_config): return "installing" else: # Configuration opt-out by user raise Skipped("skipping due to configuration")
negative_train_query273_06707
matplotlib/setupext.py/Platform/check class Platform: def check(self): return sys.platform
negative_train_query273_06708
matplotlib/setupext.py/Python/check class Python: def check(self): return sys.version
negative_train_query273_06709
matplotlib/setupext.py/Matplotlib/get_package_data class Matplotlib: def get_package_data(self): return { 'matplotlib': [ 'mpl-data/matplotlibrc', *_pkg_data_helper('matplotlib', 'mpl-data'), *_pkg_data_helper('matplotlib', 'backends/web_backend'), '*.dll', # Only actually matters on Windows. ], }
negative_train_query273_06710
matplotlib/setupext.py/Matplotlib/get_extensions class Matplotlib: def get_extensions(self): # agg ext = Extension( "matplotlib.backends._backend_agg", [ "src/py_converters.cpp", "src/_backend_agg.cpp", "src/_backend_agg_wrapper.cpp", ]) add_numpy_flags(ext) add_libagg_flags_and_sources(ext) FreeType.add_flags(ext) yield ext # c_internal_utils ext = Extension( "matplotlib._c_internal_utils", ["src/_c_internal_utils.c"], libraries=({ "linux": ["dl"], "win32": ["ole32", "shell32", "user32"], }.get(sys.platform, []))) yield ext # ft2font ext = Extension( "matplotlib.ft2font", [ "src/ft2font.cpp", "src/ft2font_wrapper.cpp", "src/py_converters.cpp", ]) FreeType.add_flags(ext) add_numpy_flags(ext) add_libagg_flags(ext) yield ext # image ext = Extension( "matplotlib._image", [ "src/_image_wrapper.cpp", "src/py_converters.cpp", ]) add_numpy_flags(ext) add_libagg_flags_and_sources(ext) yield ext # path ext = Extension( "matplotlib._path", [ "src/py_converters.cpp", "src/_path_wrapper.cpp", ]) add_numpy_flags(ext) add_libagg_flags_and_sources(ext) yield ext # qhull ext = Extension( "matplotlib._qhull", ["src/_qhull_wrapper.cpp"], define_macros=[("MPL_DEVNULL", os.devnull)]) add_numpy_flags(ext) Qhull.add_flags(ext) yield ext # tkagg ext = Extension( "matplotlib.backends._tkagg", [ "src/_tkagg.cpp", ], include_dirs=["src"], # psapi library needed for finding Tcl/Tk at run time. libraries={"linux": ["dl"], "win32": ["comctl32", "psapi"], "cygwin": ["comctl32", "psapi"]}.get(sys.platform, []), extra_link_args={"win32": ["-mwindows"]}.get(sys.platform, [])) add_numpy_flags(ext) add_libagg_flags(ext) yield ext # tri ext = Pybind11Extension( "matplotlib._tri", [ "src/tri/_tri.cpp", "src/tri/_tri_wrapper.cpp", ], cxx_std=11) yield ext # ttconv ext = Extension( "matplotlib._ttconv", [ "src/_ttconv.cpp", "extern/ttconv/pprdrv_tt.cpp", "extern/ttconv/pprdrv_tt2.cpp", "extern/ttconv/ttutil.cpp", ], include_dirs=["extern"]) add_numpy_flags(ext) yield ext
negative_train_query273_06711
matplotlib/setupext.py/Tests/get_package_data class Tests: def get_package_data(self): return { 'matplotlib': [ *_pkg_data_helper('matplotlib', 'tests/baseline_images'), *_pkg_data_helper('matplotlib', 'tests/tinypages'), 'tests/cmr10.pfb', 'tests/Courier10PitchBT-Bold.pfb', 'tests/mpltest.ttf', 'tests/test_*.ipynb', ], 'mpl_toolkits': [ *_pkg_data_helper('mpl_toolkits', 'axes_grid1/tests/baseline_images'), *_pkg_data_helper('mpl_toolkits', 'axisartist/tests/baseline_images'), *_pkg_data_helper('mpl_toolkits', 'mplot3d/tests/baseline_images'), ] }
negative_train_query273_06712
matplotlib/setupext.py/FreeType/add_flags class FreeType: def add_flags(cls, ext): # checkdep_freetype2.c immediately aborts the compilation either with # "foo.h: No such file or directory" if the header is not found, or an # appropriate error message if the header indicates a too-old version. ext.sources.insert(0, 'src/checkdep_freetype2.c') if options.get('system_freetype'): pkg_config_setup_extension( # FreeType 2.3 has libtool version 9.11.3 as can be checked # from the tarball. For FreeType>=2.4, there is a conversion # table in docs/VERSIONS.txt in the FreeType source tree. ext, 'freetype2', atleast_version='9.11.3', alt_exec=['freetype-config'], default_libraries=['freetype']) ext.define_macros.append(('FREETYPE_BUILD_TYPE', 'system')) else: src_path = Path('build', f'freetype-{LOCAL_FREETYPE_VERSION}') # Statically link to the locally-built freetype. ext.include_dirs.insert(0, str(src_path / 'include')) ext.extra_objects.insert( 0, str((src_path / 'objs/.libs/libfreetype').with_suffix( '.lib' if sys.platform == 'win32' else '.a'))) ext.define_macros.append(('FREETYPE_BUILD_TYPE', 'local')) if sys.platform == 'darwin': name = ext.name.split('.')[-1] ext.extra_link_args.append( f'-Wl,-exported_symbol,_PyInit_{name}')
negative_train_query273_06713
matplotlib/setupext.py/FreeType/do_custom_build class FreeType: def do_custom_build(self, env): # We're using a system freetype if options.get('system_freetype'): return tarball = f'freetype-{LOCAL_FREETYPE_VERSION}.tar.gz' src_path = get_and_extract_tarball( urls=[ (f'https://downloads.sourceforge.net/project/freetype' f'/freetype2/{LOCAL_FREETYPE_VERSION}/{tarball}'), (f'https://download.savannah.gnu.org/releases/freetype' f'/{tarball}'), (f'https://download.savannah.gnu.org/releases/freetype' f'/freetype-old/{tarball}') ], sha=LOCAL_FREETYPE_HASH, dirname=f'freetype-{LOCAL_FREETYPE_VERSION}', ) libfreetype = (src_path / "objs/.libs/libfreetype").with_suffix( ".lib" if sys.platform == "win32" else ".a") if libfreetype.is_file(): return # Bail out because we have already built FreeType. print(f"Building freetype in {src_path}") if sys.platform != 'win32': # compilation on non-windows env = { **{ var: value for var, value in sysconfig.get_config_vars().items() if var in {"CC", "CFLAGS", "CXX", "CXXFLAGS", "LD", "LDFLAGS"} }, **env, } configure_ac = Path(src_path, "builds/unix/configure.ac") if ((src_path / "autogen.sh").exists() and not configure_ac.exists()): print(f"{configure_ac} does not exist. " f"Using sh autogen.sh to generate.") subprocess.check_call( ["sh", "./autogen.sh"], env=env, cwd=src_path) env["CFLAGS"] = env.get("CFLAGS", "") + " -fPIC" configure = [ "./configure", "--with-zlib=no", "--with-bzip2=no", "--with-png=no", "--with-harfbuzz=no", "--enable-static", "--disable-shared" ] host = sysconfig.get_config_var('HOST_GNU_TYPE') if host is not None: # May be unset on PyPy. configure.append(f"--host={host}") subprocess.check_call(configure, env=env, cwd=src_path) if 'GNUMAKE' in env: make = env['GNUMAKE'] elif 'MAKE' in env: make = env['MAKE'] else: try: output = subprocess.check_output(['make', '-v'], stderr=subprocess.DEVNULL) except subprocess.CalledProcessError: output = b'' if b'GNU' not in output and b'makepp' not in output: make = 'gmake' else: make = 'make' subprocess.check_call([make], env=env, cwd=src_path) else: # compilation on windows shutil.rmtree(src_path / "objs", ignore_errors=True) base_path = Path( f"build/freetype-{LOCAL_FREETYPE_VERSION}/builds/windows" ) vc = 'vc2010' sln_path = base_path / vc / "freetype.sln" # https://developercommunity.visualstudio.com/comments/190992/view.html (sln_path.parent / "Directory.Build.props").write_text( "<?xml version='1.0' encoding='utf-8'?>" "<Project>" "<PropertyGroup>" # WindowsTargetPlatformVersion must be given on a single line. "<WindowsTargetPlatformVersion>$(" "[Microsoft.Build.Utilities.ToolLocationHelper]" "::GetLatestSDKTargetPlatformVersion('Windows', '10.0')" ")</WindowsTargetPlatformVersion>" "</PropertyGroup>" "</Project>", encoding="utf-8") # It is not a trivial task to determine PlatformToolset to plug it # into msbuild command, and Directory.Build.props will not override # the value in the project file. # The DefaultPlatformToolset is from Microsoft.Cpp.Default.props with open(base_path / vc / "freetype.vcxproj", 'r+b') as f: toolset_repl = b'PlatformToolset>$(DefaultPlatformToolset)<' vcxproj = f.read().replace(b'PlatformToolset>v100<', toolset_repl) assert toolset_repl in vcxproj, ( 'Upgrading Freetype might break this') f.seek(0) f.truncate() f.write(vcxproj) cc = get_ccompiler() cc.initialize() # On setuptools versions that use "local" distutils, # ``cc.spawn(["msbuild", ...])`` no longer manages to locate the # right executable, even though they are correctly on the PATH, # because only the env kwarg to Popen() is updated, and not # os.environ["PATH"]. Instead, use shutil.which to walk the PATH # and get absolute executable paths. with TemporaryDirectory() as tmpdir: dest = Path(tmpdir, "path") cc.spawn([ sys.executable, "-c", "import pathlib, shutil, sys\n" "dest = pathlib.Path(sys.argv[1])\n" "dest.write_text(shutil.which('msbuild'))\n", str(dest), ]) msbuild_path = dest.read_text() msbuild_platform = ( "ARM64" if platform.machine() == "ARM64" else "x64" if platform.architecture()[0] == "64bit" else "Win32") # Freetype 2.10.0+ support static builds. msbuild_config = ( "Release Static" if [*map(int, LOCAL_FREETYPE_VERSION.split("."))] >= [2, 10] else "Release" ) cc.spawn([msbuild_path, str(sln_path), "/t:Clean;Build", f"/p:Configuration={msbuild_config};" f"Platform={msbuild_platform}"]) # Move to the corresponding Unix build path. libfreetype.parent.mkdir() # Be robust against change of FreeType version. lib_paths = Path(src_path / "objs").rglob('freetype*.lib') # Select FreeType library for required platform lib_path, = [ p for p in lib_paths if msbuild_platform in p.resolve().as_uri() ] print(f"Copying {lib_path} to {libfreetype}") shutil.copy2(lib_path, libfreetype)
negative_train_query273_06714
matplotlib/setupext.py/Qhull/add_flags class Qhull: def add_flags(cls, ext): if options.get("system_qhull"): ext.libraries.append("qhull_r") else: cls._extensions_to_update.append(ext)
negative_train_query273_06715
matplotlib/setupext.py/Qhull/do_custom_build class Qhull: def do_custom_build(self, env): if options.get('system_qhull'): return toplevel = get_and_extract_tarball( urls=["http://www.qhull.org/download/qhull-2020-src-8.0.2.tgz"], sha=LOCAL_QHULL_HASH, dirname=f"qhull-{LOCAL_QHULL_VERSION}", ) shutil.copyfile(toplevel / "COPYING.txt", "LICENSE/LICENSE_QHULL") for ext in self._extensions_to_update: qhull_path = Path(f'build/qhull-{LOCAL_QHULL_VERSION}/src') ext.include_dirs.insert(0, str(qhull_path)) ext.sources.extend( map(str, sorted(qhull_path.glob('libqhull_r/*.c')))) if sysconfig.get_config_var("LIBM") == "-lm": ext.libraries.extend("m")
negative_train_query273_06716
matplotlib/setupext.py/BackendMacOSX/check class BackendMacOSX: def check(self): if sys.platform != 'darwin': raise Skipped("Mac OS-X only") return super().check()
negative_train_query273_06717
matplotlib/setupext.py/BackendMacOSX/get_extensions class BackendMacOSX: def get_extensions(self): ext = Extension( 'matplotlib.backends._macosx', [ 'src/_macosx.m' ]) ext.extra_compile_args.extend(['-Werror']) ext.extra_link_args.extend(['-framework', 'Cocoa']) if platform.python_implementation().lower() == 'pypy': ext.extra_compile_args.append('-DPYPY=1') yield ext
negative_train_query273_06718
matplotlib/setupext.py/L/__bool__ class L: def __bool__(self): return True
negative_train_query273_06719
matplotlib/setup.py/has_flag def has_flag(self, flagname): """Return whether a flag name is supported on the specified compiler.""" import tempfile with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f: f.write('int main (int argc, char **argv) { return 0; }') try: self.compile([f.name], extra_postargs=[flagname]) except Exception as exc: # https://github.com/pypa/setuptools/issues/2698 if type(exc).__name__ != "CompileError": raise return False return True
negative_train_query273_06720
matplotlib/setup.py/update_matplotlibrc def update_matplotlibrc(path): # If packagers want to change the default backend, insert a `#backend: ...` # line. Otherwise, use the default `##backend: Agg` which has no effect # even after decommenting, which allows _auto_backend_sentinel to be filled # in at import time. template_lines = path.read_text(encoding="utf-8").splitlines(True) backend_line_idx, = [ # Also asserts that there is a single such line. idx for idx, line in enumerate(template_lines) if "#backend:" in line] template_lines[backend_line_idx] = ( "#backend: {}\n".format(setupext.options["backend"]) if setupext.options["backend"] else "##backend: Agg\n") path.write_text("".join(template_lines), encoding="utf-8")
negative_train_query273_06721
matplotlib/setup.py/prepare_flags def prepare_flags(name, enable_lto): """ Prepare *FLAGS from the environment. If set, return them, and also check whether LTO is disabled in each one, raising an error if Matplotlib config explicitly enabled LTO. """ if name in os.environ: if '-fno-lto' in os.environ[name]: if enable_lto is True: raise ValueError('Configuration enable_lto=True, but ' '{0} contains -fno-lto'.format(name)) enable_lto = False return [os.environ[name]], enable_lto return [], enable_lto
negative_train_query273_06722
matplotlib/setup.py/BuildExtraLibraries/finalize_options class BuildExtraLibraries: def finalize_options(self): # If coverage is enabled then need to keep the .o and .gcno files in a # non-temporary directory otherwise coverage info not collected. cppflags = os.getenv('CPPFLAGS') if cppflags and '--coverage' in cppflags: self.build_temp = 'build' self.distribution.ext_modules[:] = [ ext for package in good_packages for ext in package.get_extensions() ] super().finalize_options()
negative_train_query273_06723
matplotlib/setup.py/BuildExtraLibraries/add_optimization_flags class BuildExtraLibraries: def add_optimization_flags(self): """ Add optional optimization flags to extension. This adds flags for LTO and hidden visibility to both compiled extensions, and to the environment variables so that vendored libraries will also use them. If the compiler does not support these flags, then none are added. """ env = os.environ.copy() if sys.platform == 'win32': return env enable_lto = setupext.config.getboolean('libs', 'enable_lto', fallback=None) def prepare_flags(name, enable_lto): """ Prepare *FLAGS from the environment. If set, return them, and also check whether LTO is disabled in each one, raising an error if Matplotlib config explicitly enabled LTO. """ if name in os.environ: if '-fno-lto' in os.environ[name]: if enable_lto is True: raise ValueError('Configuration enable_lto=True, but ' '{0} contains -fno-lto'.format(name)) enable_lto = False return [os.environ[name]], enable_lto return [], enable_lto _, enable_lto = prepare_flags('CFLAGS', enable_lto) # Only check lto. cppflags, enable_lto = prepare_flags('CPPFLAGS', enable_lto) cxxflags, enable_lto = prepare_flags('CXXFLAGS', enable_lto) ldflags, enable_lto = prepare_flags('LDFLAGS', enable_lto) if enable_lto is False: return env if has_flag(self.compiler, '-fvisibility=hidden'): for ext in self.extensions: ext.extra_compile_args.append('-fvisibility=hidden') cppflags.append('-fvisibility=hidden') if has_flag(self.compiler, '-fvisibility-inlines-hidden'): for ext in self.extensions: if self.compiler.detect_language(ext.sources) != 'cpp': continue ext.extra_compile_args.append('-fvisibility-inlines-hidden') cxxflags.append('-fvisibility-inlines-hidden') ranlib = 'RANLIB' in env if not ranlib and self.compiler.compiler_type == 'unix': try: result = subprocess.run(self.compiler.compiler + ['--version'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) except Exception: pass else: version = result.stdout.lower() if 'gcc' in version: ranlib = shutil.which('gcc-ranlib') elif 'clang' in version: if sys.platform == 'darwin': ranlib = True else: ranlib = shutil.which('llvm-ranlib') if ranlib and has_flag(self.compiler, '-flto'): for ext in self.extensions: ext.extra_compile_args.append('-flto') cppflags.append('-flto') ldflags.append('-flto') # Needed so FreeType static library doesn't lose its LTO objects. if isinstance(ranlib, str): env['RANLIB'] = ranlib env['CPPFLAGS'] = ' '.join(cppflags) env['CXXFLAGS'] = ' '.join(cxxflags) env['LDFLAGS'] = ' '.join(ldflags) return env
negative_train_query273_06724
matplotlib/setup.py/BuildExtraLibraries/build_extensions class BuildExtraLibraries: def build_extensions(self): if (self.compiler.compiler_type == 'msvc' and os.environ.get('MPL_DISABLE_FH4')): # Disable FH4 Exception Handling implementation so that we don't # require VCRUNTIME140_1.dll. For more details, see: # https://devblogs.microsoft.com/cppblog/making-cpp-exception-handling-smaller-x64/ # https://github.com/joerick/cibuildwheel/issues/423#issuecomment-677763904 for ext in self.extensions: ext.extra_compile_args.append('/d2FH4-') env = self.add_optimization_flags() for package in good_packages: package.do_custom_build(env) return super().build_extensions()
negative_train_query273_06725
matplotlib/setup.py/BuildExtraLibraries/build_extension class BuildExtraLibraries: def build_extension(self, ext): # When C coverage is enabled, the path to the object file is saved. # Since we re-use source files in multiple extensions, libgcov will # complain at runtime that it is trying to save coverage for the same # object file at different timestamps (since each source is compiled # again for each extension). Thus, we need to use unique temporary # build directories to store object files for each extension. orig_build_temp = self.build_temp self.build_temp = os.path.join(self.build_temp, ext.name) try: super().build_extension(ext) finally: self.build_temp = orig_build_temp
negative_train_query273_06726
matplotlib/setup.py/BuildPy/run class BuildPy: def run(self): super().run() if not getattr(self, 'editable_mode', False): update_matplotlibrc( Path(self.build_lib, "matplotlib/mpl-data/matplotlibrc"))
negative_train_query273_06727
matplotlib/setup.py/Sdist/make_release_tree class Sdist: def make_release_tree(self, base_dir, files): super().make_release_tree(base_dir, files) update_matplotlibrc( Path(base_dir, "lib/matplotlib/mpl-data/matplotlibrc"))
negative_train_query273_06728