Path: blob/main/test/lib/python3.9/site-packages/setuptools/command/build_py.py
4799 views
from functools import partial1from glob import glob2from distutils.util import convert_path3import distutils.command.build_py as orig4import os5import fnmatch6import textwrap7import io8import distutils.errors9import itertools10import stat11import warnings12from pathlib import Path13from setuptools._deprecation_warning import SetuptoolsDeprecationWarning14from setuptools.extern.more_itertools import unique_everseen151617def make_writable(target):18os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE)192021class build_py(orig.build_py):22"""Enhanced 'build_py' command that includes data files with packages2324The data files are specified via a 'package_data' argument to 'setup()'.25See 'setuptools.dist.Distribution' for more details.2627Also, this version of the 'build_py' command allows you to specify both28'py_modules' and 'packages' in the same setup operation.29"""3031def finalize_options(self):32orig.build_py.finalize_options(self)33self.package_data = self.distribution.package_data34self.exclude_package_data = self.distribution.exclude_package_data or {}35if 'data_files' in self.__dict__:36del self.__dict__['data_files']37self.__updated_files = []3839def run(self):40"""Build modules, packages, and copy data files to build directory"""41if not self.py_modules and not self.packages:42return4344if self.py_modules:45self.build_modules()4647if self.packages:48self.build_packages()49self.build_package_data()5051# Only compile actual .py files, using our base class' idea of what our52# output files are.53self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))5455def __getattr__(self, attr):56"lazily compute data files"57if attr == 'data_files':58self.data_files = self._get_data_files()59return self.data_files60return orig.build_py.__getattr__(self, attr)6162def build_module(self, module, module_file, package):63outfile, copied = orig.build_py.build_module(self, module, module_file, package)64if copied:65self.__updated_files.append(outfile)66return outfile, copied6768def _get_data_files(self):69"""Generate list of '(package,src_dir,build_dir,filenames)' tuples"""70self.analyze_manifest()71return list(map(self._get_pkg_data_files, self.packages or ()))7273def get_data_files_without_manifest(self):74"""75Generate list of ``(package,src_dir,build_dir,filenames)`` tuples,76but without triggering any attempt to analyze or build the manifest.77"""78# Prevent eventual errors from unset `manifest_files`79# (that would otherwise be set by `analyze_manifest`)80self.__dict__.setdefault('manifest_files', {})81return list(map(self._get_pkg_data_files, self.packages or ()))8283def _get_pkg_data_files(self, package):84# Locate package source directory85src_dir = self.get_package_dir(package)8687# Compute package build directory88build_dir = os.path.join(*([self.build_lib] + package.split('.')))8990# Strip directory from globbed filenames91filenames = [92os.path.relpath(file, src_dir)93for file in self.find_data_files(package, src_dir)94]95return package, src_dir, build_dir, filenames9697def find_data_files(self, package, src_dir):98"""Return filenames for package's data files in 'src_dir'"""99patterns = self._get_platform_patterns(100self.package_data,101package,102src_dir,103)104globs_expanded = map(partial(glob, recursive=True), patterns)105# flatten the expanded globs into an iterable of matches106globs_matches = itertools.chain.from_iterable(globs_expanded)107glob_files = filter(os.path.isfile, globs_matches)108files = itertools.chain(109self.manifest_files.get(package, []),110glob_files,111)112return self.exclude_data_files(package, src_dir, files)113114def build_package_data(self):115"""Copy data files into build directory"""116for package, src_dir, build_dir, filenames in self.data_files:117for filename in filenames:118target = os.path.join(build_dir, filename)119self.mkpath(os.path.dirname(target))120srcfile = os.path.join(src_dir, filename)121outf, copied = self.copy_file(srcfile, target)122make_writable(target)123srcfile = os.path.abspath(srcfile)124125def analyze_manifest(self):126self.manifest_files = mf = {}127if not self.distribution.include_package_data:128return129src_dirs = {}130for package in self.packages or ():131# Locate package source directory132src_dirs[assert_relative(self.get_package_dir(package))] = package133134self.run_command('egg_info')135check = _IncludePackageDataAbuse()136ei_cmd = self.get_finalized_command('egg_info')137for path in ei_cmd.filelist.files:138d, f = os.path.split(assert_relative(path))139prev = None140oldf = f141while d and d != prev and d not in src_dirs:142prev = d143d, df = os.path.split(d)144f = os.path.join(df, f)145if d in src_dirs:146if f == oldf:147if check.is_module(f):148continue # it's a module, not data149else:150importable = check.importable_subpackage(src_dirs[d], f)151if importable:152check.warn(importable)153mf.setdefault(src_dirs[d], []).append(path)154155def get_data_files(self):156pass # Lazily compute data files in _get_data_files() function.157158def check_package(self, package, package_dir):159"""Check namespace packages' __init__ for declare_namespace"""160try:161return self.packages_checked[package]162except KeyError:163pass164165init_py = orig.build_py.check_package(self, package, package_dir)166self.packages_checked[package] = init_py167168if not init_py or not self.distribution.namespace_packages:169return init_py170171for pkg in self.distribution.namespace_packages:172if pkg == package or pkg.startswith(package + '.'):173break174else:175return init_py176177with io.open(init_py, 'rb') as f:178contents = f.read()179if b'declare_namespace' not in contents:180raise distutils.errors.DistutilsError(181"Namespace package problem: %s is a namespace package, but "182"its\n__init__.py does not call declare_namespace()! Please "183'fix it.\n(See the setuptools manual under '184'"Namespace Packages" for details.)\n"' % (package,)185)186return init_py187188def initialize_options(self):189self.packages_checked = {}190orig.build_py.initialize_options(self)191192def get_package_dir(self, package):193res = orig.build_py.get_package_dir(self, package)194if self.distribution.src_root is not None:195return os.path.join(self.distribution.src_root, res)196return res197198def exclude_data_files(self, package, src_dir, files):199"""Filter filenames for package's data files in 'src_dir'"""200files = list(files)201patterns = self._get_platform_patterns(202self.exclude_package_data,203package,204src_dir,205)206match_groups = (fnmatch.filter(files, pattern) for pattern in patterns)207# flatten the groups of matches into an iterable of matches208matches = itertools.chain.from_iterable(match_groups)209bad = set(matches)210keepers = (fn for fn in files if fn not in bad)211# ditch dupes212return list(unique_everseen(keepers))213214@staticmethod215def _get_platform_patterns(spec, package, src_dir):216"""217yield platform-specific path patterns (suitable for glob218or fn_match) from a glob-based spec (such as219self.package_data or self.exclude_package_data)220matching package in src_dir.221"""222raw_patterns = itertools.chain(223spec.get('', []),224spec.get(package, []),225)226return (227# Each pattern has to be converted to a platform-specific path228os.path.join(src_dir, convert_path(pattern))229for pattern in raw_patterns230)231232233def assert_relative(path):234if not os.path.isabs(path):235return path236from distutils.errors import DistutilsSetupError237238msg = (239textwrap.dedent(240"""241Error: setup script specifies an absolute path:242243%s244245setup() arguments must *always* be /-separated paths relative to the246setup.py directory, *never* absolute paths.247"""248).lstrip()249% path250)251raise DistutilsSetupError(msg)252253254class _IncludePackageDataAbuse:255"""Inform users that package or module is included as 'data file'"""256257MESSAGE = """\258Installing {importable!r} as data is deprecated, please list it in `packages`.259!!\n\n260############################261# Package would be ignored #262############################263Python recognizes {importable!r} as an importable package, however it is264included in the distribution as "data".265This behavior is likely to change in future versions of setuptools (and266therefore is considered deprecated).267268Please make sure that {importable!r} is included as a package by using269setuptools' `packages` configuration field or the proper discovery methods270(for example by using `find_namespace_packages(...)`/`find_namespace:`271instead of `find_packages(...)`/`find:`).272273You can read more about "package discovery" and "data files" on setuptools274documentation page.275\n\n!!276"""277278def __init__(self):279self._already_warned = set()280281def is_module(self, file):282return file.endswith(".py") and file[:-len(".py")].isidentifier()283284def importable_subpackage(self, parent, file):285pkg = Path(file).parent286parts = list(itertools.takewhile(str.isidentifier, pkg.parts))287if parts:288return ".".join([parent, *parts])289return None290291def warn(self, importable):292if importable not in self._already_warned:293msg = textwrap.dedent(self.MESSAGE).format(importable=importable)294warnings.warn(msg, SetuptoolsDeprecationWarning, stacklevel=2)295self._already_warned.add(importable)296297298