PKzFNOflit/__init__.py"""A simple packaging tool for simple packages.""" import argparse import logging import pathlib import sys from . import common from .log import enable_colourful_output __version__ = '1.3' log = logging.getLogger(__name__) def add_shared_install_options(parser): parser.add_argument('--user', action='store_true', default=None, help="Do a user-local install (default if site.ENABLE_USER_SITE is True)" ) parser.add_argument('--env', action='store_false', dest='user', help="Install into sys.prefix (default if site.ENABLE_USER_SITE is False, i.e. in virtualenvs)" ) parser.add_argument('--python', default=sys.executable, help="Target Python executable, if different from the one running flit" ) def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument('-f', '--ini-file', type=pathlib.Path, default='pyproject.toml') ap.add_argument('-V', '--version', action='version', version='Flit '+__version__) ap.add_argument('--repository', help="Name of the repository to upload to (must be in ~/.pypirc)" ) ap.add_argument('--debug', action='store_true', help=argparse.SUPPRESS) ap.add_argument('--logo', action='store_true', help=argparse.SUPPRESS) subparsers = ap.add_subparsers(title='subcommands', dest='subcmd') parser_build = subparsers.add_parser('build', help="Build wheel and sdist", ) parser_build.add_argument('--format', action='append', help="Select a format to build. Options: 'wheel', 'sdist'" ) parser_publish = subparsers.add_parser('publish', help="Upload wheel and sdist", ) parser_publish.add_argument('--format', action='append', help="Select a format to publish. Options: 'wheel', 'sdist'" ) parser_install = subparsers.add_parser('install', help="Install the package", ) parser_install.add_argument('-s', '--symlink', action='store_true', help="Symlink the module/package into site packages instead of copying it" ) parser_install.add_argument('--pth-file', action='store_true', help="Add .pth file for the module/package to site packages instead of copying it" ) add_shared_install_options(parser_install) parser_install.add_argument('--deps', choices=['all', 'production', 'develop', 'none'], default='all', help="Which set of dependencies to install. If --deps=develop, the extras dev, doc, and test are installed" ) parser_install.add_argument('--extras', default=(), type=lambda l: l.split(',') if l else (), help="Install the dependencies of these (comma separated) extras additionally to the ones implied by --deps. " "--extras=all can be useful in combination with --deps=production, --deps=none precludes using --extras" ) parser_installfrom = subparsers.add_parser('installfrom', help="Download and install a package using flit from source" ) parser_installfrom.add_argument('location', help="A URL to download, or a shorthand like github:takluyver/flit" ) add_shared_install_options(parser_installfrom) parser_init = subparsers.add_parser('init', help="Prepare pyproject.toml for a new package" ) args = ap.parse_args(argv) cf = args.ini_file if ( args.subcmd not in {'init', 'installfrom'} and cf == pathlib.Path('pyproject.toml') and not cf.is_file() ): # Fallback to flit.ini if it's present cf_ini = pathlib.Path('flit.ini') if cf_ini.is_file(): args.ini_file = cf_ini else: sys.exit('Neither pyproject.toml nor flit.ini found, ' 'and no other config file path specified') enable_colourful_output(logging.DEBUG if args.debug else logging.INFO) log.debug("Parsed arguments %r", args) if args.logo: from .logo import clogo print(clogo.format(version=__version__)) sys.exit(0) if args.subcmd == 'build': from .build import main try: main(args.ini_file, formats=set(args.format or [])) except(common.NoDocstringError) as e: sys.exit(e.args[0]) elif args.subcmd == 'publish': from .upload import main main(args.ini_file, args.repository, formats=set(args.format or [])) elif args.subcmd == 'install': from .install import Installer try: Installer(args.ini_file, user=args.user, python=args.python, symlink=args.symlink, deps=args.deps, extras=args.extras, pth=args.pth_file).install() except (common.NoDocstringError, common.NoVersionError) as e: sys.exit(e.args[0]) elif args.subcmd == 'installfrom': from .installfrom import installfrom sys.exit(installfrom(args.location, user=args.user, python=args.python)) elif args.subcmd == 'init': from .init import TerminalIniter TerminalIniter().initialise() else: ap.print_help() sys.exit(1) PKSuzG 755 return new_mode class Metadata: home_page = None author = None maintainer = None maintainer_email = None license = None description = None keywords = None download_url = None requires_python = None description_content_type = None platform = () supported_platform = () classifiers = () provides = () requires = () obsoletes = () project_urls = () provides_dist = () requires_dist = () obsoletes_dist = () requires_external = () provides_extra = () metadata_version = "2.1" def __init__(self, data): self.name = data.pop('name') self.version = data.pop('version') self.author_email = data.pop('author_email') self.summary = data.pop('summary') for k, v in data.items(): assert hasattr(self, k), "data does not have attribute '{}'".format(k) setattr(self, k, v) def _normalise_name(self, n): return n.lower().replace('-', '_') def write_metadata_file(self, fp): """Write out metadata in the email headers format""" fields = [ 'Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'License', ] optional_fields = [ 'Keywords', 'Author', 'Author-email', 'Maintainer', 'Maintainer-email', 'Requires-Python', 'Description-Content-Type', ] for field in fields: value = getattr(self, self._normalise_name(field)) fp.write("{}: {}\n".format(field, value or 'UNKNOWN')) for field in optional_fields: value = getattr(self, self._normalise_name(field)) if value is not None: fp.write("{}: {}\n".format(field, value)) for clsfr in self.classifiers: fp.write('Classifier: {}\n'.format(clsfr)) for req in self.requires_dist: fp.write('Requires-Dist: {}\n'.format(req)) for url in self.project_urls: fp.write('Project-URL: {}\n'.format(url)) for extra in self.provides_extra: fp.write('Provides-Extra: {}\n'.format(extra)) if self.description is not None: fp.write('\n' + self.description + '\n') @property def supports_py2(self) -> bool: """Return True if Requires-Python indicates Python 2 support.""" for part in (self.requires_python or "").split(","): if re.search(r"^\s*(>\s*(=\s*)?)?[3-9]", part): return False return True def make_metadata(module, ini_info): md_dict = {'name': module.name, 'provides': [module.name]} md_dict.update(get_info_from_module(module)) md_dict.update(ini_info['metadata']) return Metadata(md_dict) def metadata_and_module_from_ini_path(ini_path): from . import inifile ini_info = inifile.read_pkg_ini(ini_path) module = Module(ini_info['module'], ini_path.parent) metadata = make_metadata(module, ini_info) return metadata,module def dist_info_name(distribution, version): """Get the correct name of the .dist-info folder""" escaped_name = re.sub(r"[^\w\d.]+", "_", distribution, flags=re.UNICODE) escaped_version = re.sub(r"[^\w\d.]+", "_", version, flags=re.UNICODE) return '{}-{}.dist-info'.format(escaped_name, escaped_version) PKFANk!--flit/inifile.pyimport configparser import difflib import logging import os from pathlib import Path import pytoml as toml from .validate import validate_config from .vendorized.readme.rst import render import io log = logging.getLogger(__name__) class ConfigError(ValueError): pass metadata_list_fields = { 'classifiers', 'requires', 'dev-requires' } metadata_allowed_fields = { 'module', 'author', 'author-email', 'maintainer', 'maintainer-email', 'home-page', 'license', 'keywords', 'requires-python', 'dist-name', 'entry-points-file', 'description-file', 'requires-extra', } | metadata_list_fields metadata_required_fields = { 'module', 'author', 'author-email', } def read_pkg_ini(path: Path): """Read and check the `pyproject.toml` or `flit.ini` file with data about the package. """ if path.suffix == '.toml': with path.open() as f: d = toml.load(f) res = prep_toml_config(d, path) else: # Treat all other extensions as the older flit.ini format cp = _read_pkg_ini(path) res = _validate_config(cp, path) if validate_config(res): if os.environ.get('FLIT_ALLOW_INVALID'): log.warning("Allowing invalid data (FLIT_ALLOW_INVALID set). Uploads may still fail.") else: raise ConfigError("Invalid config values (see log)") return res class EntryPointsConflict(ConfigError): def __str__(self): return ('Please specify console_scripts entry points, or [scripts] in ' 'flit config, not both.') def prep_toml_config(d, path): """Validate config loaded from pyproject.toml and prepare common metadata Returns a dictionary with keys: module, metadata, scripts, entrypoints, raw_config. """ if ('tool' not in d) or ('flit' not in d['tool']) \ or (not isinstance(d['tool']['flit'], dict)): raise ConfigError("TOML file missing [tool.flit] table.") d = d['tool']['flit'] unknown_sections = set(d) - {'metadata', 'scripts', 'entrypoints'} unknown_sections = [s for s in unknown_sections if not s.lower().startswith('x-')] if unknown_sections: raise ConfigError('Unknown sections: ' + ', '.join(unknown_sections)) if 'metadata' not in d: raise ConfigError('[tool.flit.metadata] section is required') md_dict, module, reqs_by_extra = _prep_metadata(d['metadata'], path) if 'scripts' in d: scripts_dict = dict(d['scripts']) else: scripts_dict = {} if 'entrypoints' in d: entrypoints = flatten_entrypoints(d['entrypoints']) else: entrypoints = {} _add_scripts_to_entrypoints(entrypoints, scripts_dict) return { 'module': module, 'metadata': md_dict, 'reqs_by_extra': reqs_by_extra, 'scripts': scripts_dict, 'entrypoints': entrypoints, 'raw_config': d, } def flatten_entrypoints(ep): """Flatten nested entrypoints dicts. Entry points group names can include dots. But dots in TOML make nested dictionaries: [entrypoints.a.b] # {'entrypoints': {'a': {'b': {}}}} The proper way to avoid this is: [entrypoints."a.b"] # {'entrypoints': {'a.b': {}}} But since there isn't a need for arbitrarily nested mappings in entrypoints, flit allows you to use the former. This flattens the nested dictionaries from loading pyproject.toml. """ def _flatten(d, prefix): d1 = {} for k, v in d.items(): if isinstance(v, dict): yield from _flatten(v, prefix+'.'+k) else: d1[k] = v if d1: yield prefix, d1 res = {} for k, v in ep.items(): res.update(_flatten(v, k)) return res def _add_scripts_to_entrypoints(entrypoints, scripts_dict): if scripts_dict: if 'console_scripts' in entrypoints: raise EntryPointsConflict else: entrypoints['console_scripts'] = scripts_dict def _read_pkg_ini(path): """Reads old-style flit.ini """ cp = configparser.ConfigParser() with path.open(encoding='utf-8') as f: cp.read_file(f) return cp readme_ext_to_content_type = { '.rst': 'text/x-rst', '.md': 'text/markdown', '.txt': 'text/plain', } def _prep_metadata(md_sect, path): """Process & verify the metadata from a config file - Pull out the module name we're packaging. - Read description-file and check that it's valid rst - Convert dashes in key names to underscores (e.g. home-page in config -> home_page in metadata) """ if not set(md_sect).issuperset(metadata_required_fields): missing = metadata_required_fields - set(md_sect) raise ConfigError("Required fields missing: " + '\n'.join(missing)) module = md_sect.get('module') if not module.isidentifier(): raise ConfigError("Module name %r is not a valid identifier" % module) md_dict = {} # Description file if 'description-file' in md_sect: description_file = path.parent / md_sect.get('description-file') try: with description_file.open(encoding='utf-8') as f: raw_desc = f.read() except FileNotFoundError: raise ConfigError( "Description file {} does not exist".format(description_file) ) ext = description_file.suffix try: mimetype = readme_ext_to_content_type[ext] except KeyError: log.warning("Unknown extension %r for description file.", ext) log.warning(" Recognised extensions: %s", " ".join(readme_ext_to_content_type)) mimetype = None if mimetype == 'text/x-rst': # rst check stream = io.StringIO() res = render(raw_desc, stream) if not res: log.warning("The file description seems not to be valid rst for PyPI;" " it will be interpreted as plain text") log.warning(stream.getvalue()) md_dict['description'] = raw_desc md_dict['description_content_type'] = mimetype if 'urls' in md_sect: project_urls = md_dict['project_urls'] = [] for label, url in sorted(md_sect.pop('urls').items()): project_urls.append("{}, {}".format(label, url)) for key, value in md_sect.items(): if key in {'description-file', 'module'}: continue if key not in metadata_allowed_fields: closest = difflib.get_close_matches(key, metadata_allowed_fields, n=1, cutoff=0.7) msg = "Unrecognised metadata key: {!r}".format(key) if closest: msg += " (did you mean {!r}?)".format(closest[0]) raise ConfigError(msg) k2 = key.replace('-', '_') md_dict[k2] = value if key in metadata_list_fields: if not isinstance(value, list): raise ConfigError('Expected a list for {} field, found {!r}' .format(key, value)) if not all(isinstance(a, str) for a in value): raise ConfigError('Expected a list of strings for {} field' .format(key)) elif key == 'requires-extra': if not isinstance(value, dict): raise ConfigError('Expected a dict for requires-extra field, found {!r}' .format(value)) if not all(isinstance(e, list) for e in value.values()): raise ConfigError('Expected a dict of lists for requires-extra field') for e, reqs in value.items(): if not all(isinstance(a, str) for a in reqs): raise ConfigError('Expected a string list for requires-extra. (extra {})' .format(e)) else: if not isinstance(value, str): raise ConfigError('Expected a string for {} field, found {!r}' .format(key, value)) # What we call requires in the ini file is technically requires_dist in # the metadata. if 'requires' in md_dict: md_dict['requires_dist'] = md_dict.pop('requires') # And what we call dist-name is name in the metadata if 'dist_name' in md_dict: md_dict['name'] = md_dict.pop('dist_name') # Move dev-requires into requires-extra reqs_noextra = md_dict.pop('requires_dist', []) reqs_by_extra = md_dict.pop('requires_extra', {}) dev_requires = md_dict.pop('dev_requires', None) if dev_requires is not None: if 'dev' in reqs_by_extra: raise ConfigError( 'dev-requires occurs together with its replacement requires-extra.dev.') else: log.warning( '“dev-requires = ...” is obsolete. Use “requires-extra = {"dev" = ...}” instead.') reqs_by_extra['dev'] = dev_requires # Add requires-extra requirements into requires_dist md_dict['requires_dist'] = \ reqs_noextra + list(_expand_requires_extra(reqs_by_extra)) md_dict['provides_extra'] = sorted(reqs_by_extra.keys()) # For internal use, record the main requirements as a '.none' extra. reqs_by_extra['.none'] = reqs_noextra return md_dict, module, reqs_by_extra def _expand_requires_extra(re): for extra, reqs in sorted(re.items()): for req in reqs: if ';' in req: name, envmark = req.split(';', 1) yield '{}; extra == "{}" and ({})'.format(name, extra, envmark) else: yield '{}; extra == "{}"'.format(req, extra) def _validate_config(cp, path): """Validate and process config loaded from a flit.ini file. Returns a dict with keys: module, metadata, scripts, entrypoints, raw_config """ unknown_sections = set(cp.sections()) - {'metadata', 'scripts'} unknown_sections = [s for s in unknown_sections if not s.lower().startswith('x-')] if unknown_sections: raise ConfigError('Unknown sections: ' + ', '.join(unknown_sections)) if not cp.has_section('metadata'): raise ConfigError('[metadata] section is required') md_sect = {} for k, v in cp['metadata'].items(): if k in metadata_list_fields: md_sect[k] = [l for l in v.splitlines() if l.strip()] else: md_sect[k] = v if 'entry-points-file' in md_sect: entry_points_file = path.parent / md_sect.pop('entry-points-file') if not entry_points_file.is_file(): raise FileNotFoundError(entry_points_file) else: entry_points_file = path.parent / 'entry_points.txt' if not entry_points_file.is_file(): entry_points_file = None if entry_points_file: ep_cp = configparser.ConfigParser() with entry_points_file.open() as f: ep_cp.read_file(f) # Convert to regular dict entrypoints = {k: dict(v) for k,v in ep_cp.items()} else: entrypoints = {} md_dict, module, reqs_by_extra = _prep_metadata(md_sect, path) # Scripts --------------- if cp.has_section('scripts'): scripts_dict = dict(cp['scripts']) else: scripts_dict = {} _add_scripts_to_entrypoints(entrypoints, scripts_dict) return { 'module': module, 'metadata': md_dict, 'reqs_by_extra': reqs_by_extra, 'scripts': scripts_dict, 'entrypoints': entrypoints, 'raw_config': cp, } PKRlMkqww flit/init.pyfrom collections import OrderedDict from datetime import date import json import os from pathlib import Path import re import sys import pytoml as toml def get_data_dir(): """Get the directory path for flit user data files. """ home = os.path.realpath(os.path.expanduser('~')) if sys.platform == 'darwin': d = Path(home, 'Library') elif os.name == 'nt': appdata = os.environ.get('APPDATA', None) if appdata: d = Path(appdata) else: d = Path(home, 'AppData', 'Roaming') else: # Linux, non-OS X Unix, AIX, etc. xdg = os.environ.get("XDG_DATA_HOME", None) d = Path(xdg) if xdg else Path(home, '.local/share') return d / 'flit' def get_defaults(): try: with (get_data_dir() / 'init_defaults.json').open(encoding='utf-8') as f: return json.load(f) except FileNotFoundError: return {} def store_defaults(d): data_dir = get_data_dir() try: data_dir.mkdir(parents=True) except FileExistsError: pass with (data_dir / 'init_defaults.json').open('w', encoding='utf-8') as f: json.dump(d, f, indent=2) license_choices = [ ('mit', "MIT - simple and permissive"), ('apache', "Apache - explicitly grants patent rights"), ('gpl3', "GPL - ensures that code based on this is shared with the same terms"), ('skip', "Skip - choose a license later"), ] license_names_to_classifiers = { 'mit': 'License :: OSI Approved :: MIT License', 'gpl3': 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'apache': 'License :: OSI Approved :: Apache Software License' } license_templates_dir = Path(__file__).parent / 'license_templates' class IniterBase: def __init__(self, directory='.'): self.directory = Path(directory) self.defaults = get_defaults() def validate_email(self, s): # Properly validating an email address is much more complex return bool(re.match(r'.+@.+', s)) def validate_homepage(self, s): return not s or s.startswith(('http://', 'https://')) def guess_module_name(self): packages, modules = [], [] for p in self.directory.iterdir(): if not p.stem.isidentifier(): continue if p.is_dir() and (p / '__init__.py').is_file(): if p.name not in {'test', 'tests'}: packages.append(p.name) elif p.is_file() and p.suffix == '.py': if p.stem not in {'setup'} and not p.name.startswith('test_'): modules.append(p.stem) if len(packages) == 1: return packages[0] elif len(packages) == 0 and len(modules) == 1: return modules[0] else: return None def update_defaults(self, author, author_email, module, home_page, license): new_defaults = {'author': author, 'author_email': author_email, 'license': license} name_chunk_pat = r'\b{}\b'.format(re.escape(module)) if re.search(name_chunk_pat, home_page): new_defaults['home_page_template'] = \ re.sub(name_chunk_pat, '{modulename}', home_page, flags=re.I) if any(new_defaults[k] != self.defaults.get(k) for k in new_defaults): self.defaults.update(new_defaults) store_defaults(self.defaults) def write_license(self, name, author): if (self.directory / 'LICENSE').exists(): return year = date.today().year with (license_templates_dir / name).open(encoding='utf-8') as f: license_text = f.read() with (self.directory / 'LICENSE').open('w', encoding='utf-8') as f: f.write(license_text.format(year=year, author=author)) class TerminalIniter(IniterBase): def prompt_text(self, prompt, default, validator, retry_msg="Try again."): if default is not None: p = "{} [{}]: ".format(prompt, default) else: p = prompt + ': ' while True: response = input(p) if response == '' and default is not None: response = default if validator(response): return response print(retry_msg) def prompt_options(self, prompt, options, default=None): default_ix = None print(prompt) for i, (key, text) in enumerate(options, start=1): print("{}. {}".format(i, text)) if key == default: default_ix = i while True: p = "Enter 1-" + str(len(options)) if default_ix is not None: p += ' [{}]'.format(default_ix) response = input(p+': ') if (default_ix is not None) and response == '': return default if response.isnumeric(): ir = int(response) if 1 <= ir <= len(options): return options[ir-1][0] print("Try again.") def initialise(self): if (self.directory / 'pyproject.toml').exists(): resp = input("pyproject.toml exists - overwrite it? [y/N]: ") if (not resp) or resp[0].lower() != 'y': return module = self.prompt_text('Module name', self.guess_module_name(), str.isidentifier) author = self.prompt_text('Author', self.defaults.get('author'), lambda s: s != '') author_email = self.prompt_text('Author email', self.defaults.get('author_email'), self.validate_email) if 'home_page_template' in self.defaults: home_page_default = self.defaults['home_page_template'].replace( '{modulename}', module) else: home_page_default = None home_page = self.prompt_text('Home page', home_page_default, self.validate_homepage, retry_msg="Should start with http:// or https:// - try again.") license = self.prompt_options('Choose a license (see http://choosealicense.com/ for more info)', license_choices, self.defaults.get('license')) self.update_defaults(author=author, author_email=author_email, home_page=home_page, module=module, license=license) metadata = OrderedDict([ ('module', module), ('author', author), ('author-email', author_email), ]) if home_page: metadata['home-page'] = home_page if license != 'skip': metadata['classifiers'] = [license_names_to_classifiers[license]] self.write_license(license, author) with (self.directory / 'pyproject.toml').open('w', encoding='utf-8') as f: f.write(TEMPLATE.format(metadata=toml.dumps(metadata))) print() print("Written pyproject.toml; edit that file to add optional extra info.") TEMPLATE = """\ [build-system] requires = ["flit"] build-backend = "flit.buildapi" [tool.flit.metadata] {metadata} """ if __name__ == '__main__': TerminalIniter().initialise() PKdlM::flit/install.py"""Install packages locally for development """ import logging import os import csv import pathlib import random import re import shutil import site import sys import tempfile from subprocess import check_call, check_output import sysconfig from . import common from . import inifile from .wheel import WheelBuilder from ._get_dirs import get_dirs log = logging.getLogger(__name__) def _requires_dist_to_pip_requirement(requires_dist): """Parse "Foo (v); python_version == '2.x'" from Requires-Dist Returns pip-style appropriate for requirements.txt. """ env_mark = '' if ';' in requires_dist: name_version, env_mark = requires_dist.split(';', 1) else: name_version = requires_dist if '(' in name_version: # turn 'name (X)' and 'name ('): version = '==' + version name_version = name + version # re-add environment marker return ';'.join([name_version, env_mark]) def test_writable_dir(path): """Check if a directory is writable. Uses os.access() on POSIX, tries creating files on Windows. """ if os.name == 'posix': return os.access(path, os.W_OK) return _test_writable_dir_win(path) def _test_writable_dir_win(path): # os.access doesn't work on Windows: http://bugs.python.org/issue2528 # and we can't use tempfile: http://bugs.python.org/issue22107 basename = 'accesstest_deleteme_fishfingers_custard_' alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789' for i in range(10): name = basename + ''.join(random.choice(alphabet) for _ in range(6)) file = os.path.join(path, name) try: with open(file, mode='xb'): pass except FileExistsError: continue except PermissionError: # This could be because there's a directory with the same name. # But it's highly unlikely there's a directory called that, # so we'll assume it's because the parent directory is not writable. return False else: os.unlink(file) return True # This should never be reached msg = ('Unexpected condition testing for writable directory {!r}. ' 'Please open an issue on flit to debug why this occurred.') # pragma: no cover raise EnvironmentError(msg.format(path)) # pragma: no cover class RootInstallError(Exception): def __str__(self): return ("Installing packages as root is not recommended. " "To allow this, set FLIT_ROOT_INSTALL=1 and try again.") class DependencyError(Exception): def __str__(self): return 'To install dependencies for extras, you cannot set deps=none.' class Installer(object): def __init__(self, ini_path, user=None, python=sys.executable, symlink=False, deps='all', extras=(), pth=False): self.ini_path = ini_path self.python = python self.symlink = symlink self.pth = pth self.deps = deps self.extras = extras if deps != 'none' and os.environ.get('FLIT_NO_NETWORK', ''): self.deps = 'none' log.warning('Not installing dependencies, because FLIT_NO_NETWORK is set') if deps == 'none' and extras: raise DependencyError() self.ini_info = inifile.read_pkg_ini(ini_path) self.module = common.Module(self.ini_info['module'], ini_path.parent) if (hasattr(os, 'getuid') and (os.getuid() == 0) and (not os.environ.get('FLIT_ROOT_INSTALL'))): raise RootInstallError if user is None: self.user = self._auto_user(python) else: self.user = user log.debug('User install? %s', self.user) self.installed_files = [] def _run_python(self, code=None, file=None, extra_args=()): if code and file: raise ValueError('Specify code or file, not both') if not (code or file): raise ValueError('Specify code or file') if code: args = [self.python, '-c', code] else: args = [self.python, file] args.extend(extra_args) env = os.environ.copy() env['PYTHONIOENCODING'] = 'utf-8' # On Windows, shell needs to be True to pick up our local PATH # when finding the Python command. shell = (os.name == 'nt') return check_output(args, shell=shell, env=env).decode('utf-8') def _auto_user(self, python): """Default guess for whether to do user-level install. This should be True for system Python, and False in an env. """ if python == sys.executable: user_site = site.ENABLE_USER_SITE lib_dir = sysconfig.get_path('purelib') else: out = self._run_python(code= ("import sysconfig, site; " "print(site.ENABLE_USER_SITE); " "print(sysconfig.get_path('purelib'))")) user_site, lib_dir = out.split('\n', 1) user_site = (user_site.strip() == 'True') lib_dir = lib_dir.strip() if not user_site: # No user site packages - probably a virtualenv log.debug('User site packages not available - env install') return False log.debug('Checking access to %s', lib_dir) return not test_writable_dir(lib_dir) def install_scripts(self, script_defs, scripts_dir): for name, ep in script_defs.items(): module, func = common.parse_entry_point(ep) script_file = pathlib.Path(scripts_dir) / name log.info('Writing script to %s', script_file) with script_file.open('w', encoding='utf-8') as f: f.write(common.script_template.format( interpreter=sys.executable, module=module, func=func )) script_file.chmod(0o755) self.installed_files.append(script_file) if sys.platform == 'win32': cmd_file = script_file.with_suffix('.cmd') cmd = '"{python}" "%~dp0\{script}" %*\r\n'.format( python=sys.executable, script=name) log.debug("Writing script wrapper to %s", cmd_file) with cmd_file.open('w') as f: f.write(cmd) self.installed_files.append(cmd_file) def _record_installed_directory(self, path): for dirpath, dirnames, files in os.walk(path): for f in files: self.installed_files.append(os.path.join(dirpath, f)) def _extras_to_install(self): extras_to_install = set(self.extras) if self.deps == 'all' or 'all' in extras_to_install: extras_to_install |= set(self.ini_info['reqs_by_extra'].keys()) # We don’t remove 'all' from the set because there might be an extra called “all”. elif self.deps == 'develop': extras_to_install |= {'dev', 'doc', 'test'} elif self.deps == 'production': # '.none' is an internal token for normal requirements extras_to_install.add('.none') log.info("Extras to install for deps %r: %s", self.deps, extras_to_install) return extras_to_install def install_requirements(self): """Install requirements of a package with pip. Creates a temporary requirements.txt from requires_dist metadata. """ # construct the full list of requirements, including dev requirements requirements = [] if self.deps == 'none': return for extra in self._extras_to_install(): requirements.extend(self.ini_info['reqs_by_extra'].get(extra, [])) # there aren't any requirements, so return if len(requirements) == 0: return requirements = [ _requires_dist_to_pip_requirement(req_d) for req_d in requirements ] # install the requirements with pip cmd = [self.python, '-m', 'pip', 'install'] if self.user: cmd.append('--user') with tempfile.NamedTemporaryFile(mode='w', suffix='requirements.txt', delete=False) as tf: tf.file.write('\n'.join(requirements)) cmd.extend(['-r', tf.name]) log.info("Installing requirements") try: check_call(cmd) finally: os.remove(tf.name) def install_reqs_my_python_if_needed(self): """Install requirements to this environment if needed. We can normally get the module's docstring and version number without importing it, but if we do need to import it, we may need to install its requirements for the Python where flit is running. """ try: common.get_info_from_module(self.module) except ImportError: if self.deps == 'none': raise # We were asked not to install deps, so bail out. log.warning("Installing requirements to Flit's env to import module.") user = self.user if (self.python == sys.executable) else None i2 = Installer(ini_path=self.ini_path, user=user, deps='production') i2.install_requirements() def _get_dirs(self, user): if self.python == sys.executable: return get_dirs(user=user) else: import json path = os.path.join(os.path.dirname(__file__), '_get_dirs.py') args = ['--user'] if user else [] return json.loads(self._run_python(file=path, extra_args=args)) def install_directly(self): """Install a module/package into site-packages, and create its scripts. """ dirs = self._get_dirs(user=self.user) os.makedirs(dirs['purelib'], exist_ok=True) os.makedirs(dirs['scripts'], exist_ok=True) dst = os.path.join(dirs['purelib'], self.module.path.name) if os.path.lexists(dst): if os.path.isdir(dst) and not os.path.islink(dst): shutil.rmtree(dst) else: os.unlink(dst) # Install requirements to target environment self.install_requirements() # Install requirements to this environment if we need them to # get docstring & version number. if self.python != sys.executable: self.install_reqs_my_python_if_needed() src = str(self.module.path) if self.symlink: log.info("Symlinking %s -> %s", src, dst) os.symlink(str(self.module.path.resolve()), dst) self.installed_files.append(dst) elif self.pth: # .pth points to the the folder containing the module (which is # added to sys.path) pth_target = str(self.module.path.resolve().parent) pth_file = pathlib.Path(dst).with_suffix('.pth') log.info("Adding .pth file %s for %s", pth_file, pth_target) with pth_file.open("w") as f: f.write(pth_target) self.installed_files.append(pth_file) elif self.module.path.is_dir(): log.info("Copying directory %s -> %s", src, dst) shutil.copytree(src, dst) self._record_installed_directory(dst) else: log.info("Copying file %s -> %s", src, dst) shutil.copy2(src, dst) self.installed_files.append(dst) scripts = self.ini_info['scripts'] self.install_scripts(scripts, dirs['scripts']) self.write_dist_info(dirs['purelib']) def install_with_pip(self): self.install_reqs_my_python_if_needed() with tempfile.TemporaryDirectory() as td: temp_whl = os.path.join(td, 'temp.whl') with open(temp_whl, 'w+b') as fp: wb = WheelBuilder(self.ini_path, fp) wb.build() renamed_whl = os.path.join(td, wb.wheel_filename) os.rename(temp_whl, renamed_whl) extras = self._extras_to_install() extras.discard('.none') whl_with_extras = '{}[{}]'.format(renamed_whl, ','.join(extras)) \ if extras else renamed_whl cmd = [self.python, '-m', 'pip', 'install', whl_with_extras] if self.user: cmd.append('--user') if self.deps == 'none': cmd.append('--no-deps') shell = (os.name == 'nt') check_call(cmd, shell=shell) def write_dist_info(self, site_pkgs): """Write dist-info folder, according to PEP 376""" metadata = common.make_metadata(self.module, self.ini_info) dist_info = pathlib.Path(site_pkgs) / common.dist_info_name( metadata.name, metadata.version) try: dist_info.mkdir() except FileExistsError: shutil.rmtree(str(dist_info)) dist_info.mkdir() with (dist_info / 'METADATA').open('w', encoding='utf-8') as f: metadata.write_metadata_file(f) self.installed_files.append(dist_info / 'METADATA') with (dist_info / 'INSTALLER').open('w', encoding='utf-8') as f: f.write('flit') self.installed_files.append(dist_info / 'INSTALLER') # We only handle explicitly requested installations with (dist_info / 'REQUESTED').open('wb'): pass self.installed_files.append(dist_info / 'REQUESTED') if self.ini_info['entrypoints']: with (dist_info / 'entry_points.txt').open('w') as f: common.write_entry_points(self.ini_info['entrypoints'], f) self.installed_files.append(dist_info / 'entry_points.txt') with (dist_info / 'RECORD').open('w', encoding='utf-8') as f: cf = csv.writer(f) for path in self.installed_files: path = pathlib.Path(path) if path.is_symlink() or path.suffix in {'.pyc', '.pyo'}: hash, size = '', '' else: hash = 'sha256=' + common.hash_file(path) size = path.stat().st_size try: path = path.relative_to(site_pkgs) except ValueError: pass cf.writerow((path, hash, size)) cf.writerow(((dist_info / 'RECORD').relative_to(site_pkgs), '', '')) def install(self): if self.symlink or self.pth: self.install_directly() else: self.install_with_pip() PK=lMYɣflit/installfrom.pyimport os.path import pathlib import re import site import sysconfig import sys import tarfile import tempfile from urllib.parse import urlparse import zipfile from requests_download import download from .install import Installer address_formats = { 'github': (r'([\w\d_-]+)/([\w\d_-]+)(/(.+))?$', 'user/project[/commit-tag-or-branch]'), } class BadInput(Exception): """An error resulting from invalid input""" pass class InvalidAddress(BadInput): def __init__(self, address): self.address = address def __str__(self): # pragma: no cover return "Invalid address: {!r}".format(self.address) class UnknownAddressType(BadInput): def __init__(self, address_type): self.address_type = address_type def __str__(self): # pragma: no cover return "Unknown address type: {}".format(self.address_type) class InvalidAddressLocation(BadInput): def __init__(self, address_type, location, expected_pattern): self.address_type = address_type self.location = location self.expected_pattern = expected_pattern def __str__(self): # pragma: no cover return "Invalid location: {!r}\n{}: addresses should look like {}".format( self.location, self.address_type, self.expected_pattern ) def parse_address(address): if os.path.isfile(address): return 'local_file', address elif address.startswith(('http://', 'https://')): return 'url', address if ':' not in address: raise InvalidAddress(address) address_type, location = address.split(':', 1) try: location_regex, location_pattern = address_formats[address_type] except KeyError: raise UnknownAddressType(address_type) if not re.match(location_regex, location): raise InvalidAddressLocation(address_type, location, location_pattern) return address_type, location def unpack(archive): if zipfile.is_zipfile(archive): z = zipfile.ZipFile(archive) unpacked = tempfile.mkdtemp() z.extractall(path=unpacked) elif tarfile.is_tarfile(archive): t = tarfile.TarFile(archive) unpacked = tempfile.mkdtemp() t.extractall(path=unpacked) else: raise RuntimeError('Unknown archive (not zip or tar): %s' % archive) files = os.listdir(unpacked) if len(files) == 1 and os.path.isdir(os.path.join(unpacked, files[0])): return os.path.join(unpacked, files[0]) return unpacked def download_unpack(url): with tempfile.TemporaryDirectory() as td: path = os.path.join(td, urlparse(url).path.split('/')[-1]) download(url, path) unpacked = unpack(path) return unpacked def fetch(address_type, location): if address_type == 'local_file': return unpack(location) if address_type == 'url': return download_unpack(location) if address_type == 'github': m = re.match(address_formats['github'][0], location) user, project, committish = m.group(1, 2, 4) if committish is None: committish = 'master' url = 'https://github.com/{}/{}/archive/{}.zip'.format(user, project, committish) return download_unpack(url) def install_local(path, user=False, python=sys.executable): p = pathlib.Path(path) ininames = ['pyproject.toml', 'flit.ini'] for ininame in ininames: inipath = p / ininame if inipath.is_file(): return Installer(inipath, user=user, python=python, deps='production').install() raise FileNotFoundError('Neither {} found in {}'.format(' nor '.join(ininames), p)) def installfrom(address, user=None, python=sys.executable): if user is None: user = site.ENABLE_USER_SITE \ and not os.access(sysconfig.get_path('purelib'), os.W_OK) try: return install_local(fetch(*parse_address(address)), user=user, python=python) except BadInput as e: print(e, file=sys.stderr) return 2 PKSuzG- flit/log.py"""Nicer log formatting with colours. Code copied from Tornado, Apache licensed. """ # Copyright 2012 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import sys try: import curses except ImportError: curses = None def _stderr_supports_color(): color = False if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except Exception: pass return color class LogFormatter(logging.Formatter): """Log formatter with colour support """ DEFAULT_COLORS = { logging.INFO: 2, # Green logging.WARNING: 3, # Yellow logging.ERROR: 1, # Red logging.CRITICAL: 1, } def __init__(self, color=True, datefmt=None): r""" :arg bool color: Enables color support. :arg string fmt: Log message format. It will be applied to the attributes dict of log records. The text between ``%(color)s`` and ``%(end_color)s`` will be colored depending on the level if color support is on. :arg dict colors: color mappings from logging level to terminal color code :arg string datefmt: Datetime format. Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``. .. versionchanged:: 3.2 Added ``fmt`` and ``datefmt`` arguments. """ logging.Formatter.__init__(self, datefmt=datefmt) self._colors = {} if color and _stderr_supports_color(): # The curses module has some str/bytes confusion in # python3. Until version 3.2.3, most methods return # bytes, but only accept strings. In addition, we want to # output these strings with the logging module, which # works with unicode strings. The explicit calls to # unicode() below are harmless in python2 but will do the # right conversion in python 3. fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf") or "") if (3, 0) < sys.version_info < (3, 2, 3): fg_color = str(fg_color, "ascii") for levelno, code in self.DEFAULT_COLORS.items(): self._colors[levelno] = str(curses.tparm(fg_color, code), "ascii") self._normal = str(curses.tigetstr("sgr0"), "ascii") scr = curses.initscr() self.termwidth = scr.getmaxyx()[1] curses.endwin() else: self._normal = '' # Default width is usually 80, but too wide is worse than too narrow self.termwidth = 70 def formatMessage(self, record): l = len(record.message) right_text = '{initial}-{name}'.format(initial=record.levelname[0], name=record.name) if l + len(right_text) < self.termwidth: space = ' ' * (self.termwidth - (l + len(right_text))) else: space = ' ' if record.levelno in self._colors: start_color = self._colors[record.levelno] end_color = self._normal else: start_color = end_color = '' return record.message + space + start_color + right_text + end_color def enable_colourful_output(level=logging.INFO): handler = logging.StreamHandler() handler.setFormatter(LogFormatter()) logging.root.addHandler(handler) logging.root.setLevel(level) PK!$H& flit/logo.py"""White and colored version for flit""" logo = """ ._ ._ ```. ```. .--.______ `. `-. `. / °,-—´ `. `~-.>.' / `. .` | -..;. / / /___ _____ /r_,.´| | | | ,' `/ |—— | | | .´ ,'/ | |__ | | .´ / . / '__/|/ V {version} """ clogo = '\x1b[36m'+logo+'\x1b[39m' PK;BMg^\%\% flit/sdist.pyfrom collections import defaultdict from copy import copy from gzip import GzipFile import io import logging import os from pathlib import Path from posixpath import join as pjoin from pprint import pformat import tarfile from flit import common, inifile from flit.common import VCSError from flit.vcs import identify_vcs log = logging.getLogger(__name__) SETUP = """\ #!/usr/bin/env python # setup.py generated by flit for tools that don't yet use PEP 517 from distutils.core import setup {before} setup(name={name!r}, version={version!r}, description={description!r}, author={author!r}, author_email={author_email!r}, url={url!r}, {extra} ) """ PKG_INFO = """\ Metadata-Version: 1.1 Name: {name} Version: {version} Summary: {summary} Home-page: {home_page} Author: {author} Author-email: {author_email} """ def auto_packages(pkgdir: str): """Discover subpackages and package_data""" pkgdir = os.path.normpath(pkgdir) pkg_name = os.path.basename(pkgdir) pkg_data = defaultdict(list) # Undocumented distutils feature: the empty string matches all package names pkg_data[''].append('*') packages = [pkg_name] subpkg_paths = set() def find_nearest_pkg(rel_path): parts = rel_path.split(os.sep) for i in reversed(range(1, len(parts))): ancestor = '/'.join(parts[:i]) if ancestor in subpkg_paths: pkg = '.'.join([pkg_name] + parts[:i]) return pkg, '/'.join(parts[i:]) # Relative to the top-level package return pkg_name, rel_path for path, dirnames, filenames in os.walk(pkgdir, topdown=True): if os.path.basename(path) == '__pycache__': continue from_top_level = os.path.relpath(path, pkgdir) if from_top_level == '.': continue is_subpkg = '__init__.py' in filenames if is_subpkg: subpkg_paths.add(from_top_level) parts = from_top_level.split(os.sep) packages.append('.'.join([pkg_name] + parts)) else: pkg, from_nearest_pkg = find_nearest_pkg(from_top_level) pkg_data[pkg].append(pjoin(from_nearest_pkg, '*')) # Sort values in pkg_data pkg_data = {k: sorted(v) for (k, v) in pkg_data.items()} return sorted(packages), pkg_data def _parse_req(requires_dist): """Parse "Foo (v); python_version == '2.x'" from Requires-Dist Returns pip-style appropriate for requirements.txt. """ if ';' in requires_dist: name_version, env_mark = requires_dist.split(';', 1) env_mark = env_mark.strip() else: name_version, env_mark = requires_dist, None if '(' in name_version: # turn 'name (X)' and 'name ('): version = '==' + version name_version = name + version return name_version, env_mark def convert_requires(reqs_by_extra): """Regroup requirements by (extra, env_mark)""" grouping = defaultdict(list) for extra, reqs in reqs_by_extra.items(): for req in reqs: name_version, env_mark = _parse_req(req) grouping[(extra, env_mark)].append(name_version) install_reqs = grouping.pop(('.none', None), []) extra_reqs = {} for (extra, env_mark), reqs in grouping.items(): if extra == '.none': extra = '' if env_mark is None: extra_reqs[extra] = reqs else: extra_reqs[extra + ':' + env_mark] = reqs return install_reqs, extra_reqs def include_path(p): return not (p.startswith('dist' + os.sep) or (os.sep+'__pycache__' in p) or p.endswith('.pyc')) def clean_tarinfo(ti, mtime=None): """Clean metadata from a TarInfo object to make it more reproducible. - Set uid & gid to 0 - Set uname and gname to "" - Normalise permissions to 644 or 755 - Set mtime if not None """ ti = copy(ti) ti.uid = 0 ti.gid = 0 ti.uname = '' ti.gname = '' ti.mode = common.normalize_file_permissions(ti.mode) if mtime is not None: ti.mtime = mtime return ti class SdistBuilder: def __init__(self, ini_path=Path('flit.ini')): self.ini_path = ini_path self.ini_info = inifile.read_pkg_ini(ini_path) self.module = common.Module(self.ini_info['module'], ini_path.parent) self.metadata = common.make_metadata(self.module, self.ini_info) self.srcdir = ini_path.parent def prep_entry_points(self): # Reformat entry points from dict-of-dicts to dict-of-lists res = defaultdict(list) for groupname, group in self.ini_info['entrypoints'].items(): for name, ep in sorted(group.items()): res[groupname].append('{} = {}'.format(name, ep)) return dict(res) def find_tracked_files(self): vcs_mod = identify_vcs(self.srcdir) untracked_deleted = vcs_mod.list_untracked_deleted_files(self.srcdir) if list(filter(include_path, untracked_deleted)): raise VCSError("Untracked or deleted files in the source directory. " "Commit, undo or ignore these files in your VCS.", self.srcdir) files = vcs_mod.list_tracked_files(self.srcdir) log.info("Found %d files tracked in %s", len(files), vcs_mod.name) return sorted(filter(include_path, files)) def make_setup_py(self): before, extra = [], [] if self.module.is_package: packages, package_data = auto_packages(str(self.module.path)) before.append("packages = \\\n%s\n" % pformat(sorted(packages))) before.append("package_data = \\\n%s\n" % pformat(package_data)) extra.append("packages=packages,") extra.append("package_data=package_data,") else: extra.append("py_modules={!r},".format([self.module.name])) install_reqs, extra_reqs = convert_requires(self.ini_info['reqs_by_extra']) if install_reqs: before.append("install_requires = \\\n%s\n" % pformat(install_reqs)) extra.append("install_requires=install_requires,") if extra_reqs: before.append("extras_require = \\\n%s\n" % pformat(extra_reqs)) extra.append("extras_require=extras_require,") entrypoints = self.prep_entry_points() if entrypoints: before.append("entry_points = \\\n%s\n" % pformat(entrypoints)) extra.append("entry_points=entry_points,") if self.metadata.requires_python: extra.append('python_requires=%r,' % self.metadata.requires_python) return SETUP.format( before='\n'.join(before), name=self.metadata.name, version=self.metadata.version, description=self.metadata.summary, author=self.metadata.author, author_email=self.metadata.author_email, url=self.metadata.home_page, extra='\n '.join(extra), ).encode('utf-8') def build(self, target_dir:Path =None): if target_dir is None: target_dir = self.ini_path.parent / 'dist' if not target_dir.exists(): target_dir.mkdir(parents=True) target = target_dir / '{}-{}.tar.gz'.format( self.metadata.name, self.metadata.version) source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH', '') mtime = int(source_date_epoch) if source_date_epoch else None gz = GzipFile(str(target), mode='wb', mtime=mtime) tf = tarfile.TarFile(str(target), mode='w', fileobj=gz, format=tarfile.PAX_FORMAT) try: tf_dir = '{}-{}'.format(self.metadata.name, self.metadata.version) files_to_add = self.find_tracked_files() for relpath in files_to_add: path = self.srcdir / relpath ti = tf.gettarinfo(str(path), arcname=pjoin(tf_dir, relpath)) ti = clean_tarinfo(ti, mtime) if ti.isreg(): with path.open('rb') as f: tf.addfile(ti, f) else: tf.addfile(ti) # Symlinks & ? if 'setup.py' in files_to_add: log.warning("Using setup.py from repository, not generating setup.py") else: setup_py = self.make_setup_py() log.info("Writing generated setup.py") ti = tarfile.TarInfo(pjoin(tf_dir, 'setup.py')) ti.size = len(setup_py) tf.addfile(ti, io.BytesIO(setup_py)) pkg_info = PKG_INFO.format( name=self.metadata.name, version=self.metadata.version, summary=self.metadata.summary, home_page=self.metadata.home_page, author=self.metadata.author, author_email=self.metadata.author_email, ).encode('utf-8') ti = tarfile.TarInfo(pjoin(tf_dir, 'PKG-INFO')) ti.size = len(pkg_info) tf.addfile(ti, io.BytesIO(pkg_info)) finally: tf.close() gz.close() log.info("Built sdist: %s", target) return target PKoK:5Ayxxflit/tomlify.py"""Convert a flit.ini file to pyproject.toml """ import argparse from collections import OrderedDict import configparser import os from pathlib import Path import pytoml from .inifile import metadata_list_fields from .init import TEMPLATE class CaseSensitiveConfigParser(configparser.ConfigParser): optionxform = staticmethod(str) def convert(path): cp = configparser.ConfigParser() with path.open(encoding='utf-8') as f: cp.read_file(f) ep_file = Path('entry_points.txt') metadata = OrderedDict() for name, value in cp['metadata'].items(): if name in metadata_list_fields: metadata[name] = [l for l in value.splitlines() if l.strip()] elif name == 'entry-points-file': ep_file = Path(value) else: metadata[name] = value if 'scripts' in cp: scripts = OrderedDict(cp['scripts']) else: scripts = {} entrypoints = CaseSensitiveConfigParser() if ep_file.is_file(): with ep_file.open(encoding='utf-8') as f: entrypoints.read_file(f) written_entrypoints = False with Path('pyproject.toml').open('w', encoding='utf-8') as f: f.write(TEMPLATE.format(metadata=pytoml.dumps(metadata))) if scripts: f.write('\n[tool.flit.scripts]\n') pytoml.dump(scripts, f) for groupname, group in entrypoints.items(): if not dict(group): continue if '.' in groupname: groupname = '"{}"'.format(groupname) f.write('\n[tool.flit.entrypoints.{}]\n'.format(groupname)) pytoml.dump(OrderedDict(group), f) written_entrypoints = True print("Written 'pyproject.toml'") files = str(path) if written_entrypoints: files += ' and ' + str(ep_file) print("Please check the new file, then remove", files) def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument('-f', '--ini-file', type=Path, default='flit.ini') args = ap.parse_args(argv) os.chdir(str(args.ini_file.parent)) convert(Path(args.ini_file.name)) if __name__ == '__main__': main() PK6AN"D)""flit/upload.py"""Code to communicate with PyPI to register distributions and upload files. This is cribbed heavily from distutils.command.(upgrade|register), which as part of Python is under the PSF license. """ import configparser import getpass import hashlib import logging import os from pathlib import Path import requests import sys from urllib.parse import urlparse from .common import Metadata log = logging.getLogger(__name__) PYPI = "https://upload.pypi.org/legacy/" SWITCH_TO_HTTPS = ( "http://pypi.python.org/", "http://testpypi.python.org/", "http://upload.pypi.org/", "http://upload.pypi.io/", ) def get_repositories(file="~/.pypirc"): """Get the known repositories from a pypirc file. This returns a dict keyed by name, of dicts with keys 'url', 'username', 'password'. Username and password may be None. """ cp = configparser.ConfigParser() if isinstance(file, str): file = os.path.expanduser(file) if not os.path.isfile(file): return {'pypi': { 'url': PYPI, 'username': None, 'password': None, }} cp.read(file) else: cp.read_file(file) names = cp.get('distutils', 'index-servers', fallback='pypi').split() repos = {} for name in names: repos[name] = { 'url': cp.get(name, 'repository', fallback=PYPI), 'username': cp.get(name, 'username', fallback=None), 'password': cp.get(name, 'password', fallback=None), } return repos def get_repository(name=None, cfg_file="~/.pypirc"): """Get the url, username and password for one repository. Returns a dict with keys 'url', 'username', 'password'. There is a hierarchy of possible sources of information: Index URL: 1. Command line arg --repository (looked up in .pypirc) 2. $FLIT_INDEX_URL 3. Repository called 'pypi' from .pypirc 4. Default PyPI (hardcoded) Username: 1. Command line arg --repository (looked up in .pypirc) 2. $FLIT_USERNAME 3. Repository called 'pypi' from .pypirc 4. Terminal prompt (write to .pypirc if it doesn't exist yet) Password: 1. Command line arg --repository (looked up in .pypirc) 2. $FLIT_PASSWORD 3. Repository called 'pypi' from .pypirc 3. keyring 4. Terminal prompt (store to keyring if available) """ repos_cfg = get_repositories(cfg_file) if name is not None: repo = repos_cfg[name] elif 'FLIT_INDEX_URL' in os.environ: repo = {'url': os.environ['FLIT_INDEX_URL'], 'username': None, 'password': None} elif 'pypi' in repos_cfg: repo = repos_cfg['pypi'] if 'FLIT_PASSWORD' in os.environ: repo['password'] = os.environ['FLIT_PASSWORD'] else: repo = {'url': PYPI, 'username': None, 'password': None} if repo['url'].startswith(SWITCH_TO_HTTPS): # Use https for PyPI, even if an http URL was given repo['url'] = 'https' + repo['url'][4:] elif repo['url'].startswith('http://'): log.warning("Unencrypted connection - credentials may be visible on " "the network.") log.info("Using repository at %s", repo['url']) if ('FLIT_USERNAME' in os.environ) and ((name is None) or (not repo['username'])): repo['username'] = os.environ['FLIT_USERNAME'] if sys.stdin.isatty(): while not repo['username']: repo['username'] = input("Username: ") if repo['url'] == PYPI: write_pypirc(repo) elif not repo['username']: raise Exception("Could not find username for upload.") repo['password'] = get_password(repo, prefer_env=(name is None)) repo['is_warehouse'] = repo['url'].rstrip('/').endswith('/legacy') return repo def write_pypirc(repo, file="~/.pypirc"): """Write .pypirc if it doesn't already exist """ file = os.path.expanduser(file) if os.path.isfile(file): return with open(file, 'w', encoding='utf-8') as f: f.write("[pypi]\n" "username = %s\n" % repo['username']) def get_password(repo, prefer_env): if ('FLIT_PASSWORD' in os.environ) and (prefer_env or not repo['password']): return os.environ['FLIT_PASSWORD'] if repo['password']: return repo['password'] try: import keyring except ImportError: # pragma: no cover log.warning("Install keyring to store passwords securely") keyring = None else: stored_pw = keyring.get_password(repo['url'], repo['username']) if stored_pw is not None: return stored_pw if sys.stdin.isatty(): pw = None while not pw: print('Server :', repo['url']) print('Username:', repo['username']) pw = getpass.getpass('Password: ') else: raise Exception("Could not find password for upload.") if keyring is not None: keyring.set_password(repo['url'], repo['username'], pw) log.info("Stored password with keyring") return pw def build_post_data(action, metadata:Metadata): """Prepare the metadata needed for requests to PyPI. """ d = { ":action": action, "name": metadata.name, "version": metadata.version, # additional meta-data "metadata_version": '2.1', "summary": metadata.summary, "home_page": metadata.home_page, "author": metadata.author, "author_email": metadata.author_email, "maintainer": metadata.maintainer, "maintainer_email": metadata.maintainer_email, "license": metadata.license, "description": metadata.description, "keywords": metadata.keywords, "platform": metadata.platform, "classifiers": metadata.classifiers, "download_url": metadata.download_url, "supported_platform": metadata.supported_platform, # Metadata 1.1 (PEP 314) "provides": metadata.provides, "requires": metadata.requires, "obsoletes": metadata.obsoletes, # Metadata 1.2 (PEP 345) "project_urls": metadata.project_urls, "provides_dist": metadata.provides_dist, "obsoletes_dist": metadata.obsoletes_dist, "requires_dist": metadata.requires_dist, "requires_external": metadata.requires_external, "requires_python": metadata.requires_python, # Metadata 2.1 (PEP 566) "description_content_type": metadata.description_content_type, "provides_extra": metadata.provides_extra, } return {k:v for k,v in d.items() if v} def upload_file(file:Path, metadata:Metadata, repo): """Upload a file to an index server, given the index server details. """ data = build_post_data('file_upload', metadata) data['protocol_version'] = '1' if file.suffix == '.whl': data['filetype'] = 'bdist_wheel' py2_support = not (metadata.requires_python or '')\ .startswith(('3', '>3', '>=3')) data['pyversion'] = ('py2.' if py2_support else '') + 'py3' else: data['filetype'] = 'sdist' with file.open('rb') as f: content = f.read() files = {'content': (file.name, content)} data['md5_digest'] = hashlib.md5(content).hexdigest() log.info('Uploading %s...', file) resp = requests.post(repo['url'], data=data, files=files, auth=(repo['username'], repo['password']), ) resp.raise_for_status() def verify(metadata:Metadata, repo_name): """Verify the metadata with the PyPI server. """ repo = get_repository(repo_name) data = build_post_data('verify', metadata) resp = requests.post(repo['url'], data=data, auth=(repo['username'], repo['password']) ) resp.raise_for_status() log.info('Verification succeeded') def do_upload(file:Path, metadata:Metadata, repo_name=None): """Upload a file to an index server. """ repo = get_repository(repo_name) upload_file(file, metadata, repo) if repo['is_warehouse']: domain = urlparse(repo['url']).netloc if domain.startswith('upload.'): domain = domain[7:] log.info("Package is at https://%s/project/%s/", domain, metadata.name) else: log.info("Package is at %s/%s", repo['url'], metadata.name) def main(ini_path, repo_name, formats=None): """Build and upload wheel and sdist.""" from . import build built = build.main(ini_path, formats=formats) if built.wheel is not None: do_upload(built.wheel.file, built.wheel.builder.metadata, repo_name) if built.sdist is not None: do_upload(built.sdist.file, built.sdist.builder.metadata, repo_name) PKm=Mȁ22flit/validate.py"""Validate various pieces of packaging data""" import logging import os from pathlib import Path import re import requests import sys from .common import InvalidVersion log = logging.getLogger(__name__) def get_cache_dir() -> Path: """Locate a platform-appropriate cache directory for flit to use Does not ensure that the cache directory exists. """ # Linux, Unix, AIX, etc. if os.name == 'posix' and sys.platform != 'darwin': # use ~/.cache if empty OR not set xdg = os.environ.get("XDG_CACHE_HOME", None) \ or os.path.expanduser('~/.cache') return Path(xdg, 'flit') # Mac OS elif sys.platform == 'darwin': return Path(os.path.expanduser('~'), 'Library/Caches/flit') # Windows (hopefully) else: local = os.environ.get('LOCALAPPDATA', None) \ or os.path.expanduser('~\\AppData\\Local') return Path(local, 'flit') def _verify_classifiers_cached(classifiers): """Check classifiers against the downloaded list of known classifiers""" with (get_cache_dir() / 'classifiers.lst').open(encoding='utf-8') as f: valid_classifiers = set(l.strip() for l in f) invalid = classifiers - valid_classifiers return ["Unrecognised classifier: {!r}".format(c) for c in sorted(invalid)] def _download_classifiers(): """Get the list of valid trove classifiers from PyPI""" log.info('Fetching list of valid trove classifiers') resp = requests.get( 'https://pypi.org/pypi?%3Aaction=list_classifiers') resp.raise_for_status() cache_dir = get_cache_dir() try: cache_dir.mkdir(parents=True) except FileExistsError: pass with (get_cache_dir() / 'classifiers.lst').open('wb') as f: f.write(resp.content) def validate_classifiers(classifiers): """Verify trove classifiers from config file. Fetches and caches a list of known classifiers from PyPI. Setting the environment variable FLIT_NO_NETWORK=1 will skip this if the classifiers are not already cached. """ if not classifiers: return [] problems = [] classifiers = set(classifiers) try: problems = _verify_classifiers_cached(classifiers) except FileNotFoundError as e1: # We haven't yet got the classifiers cached pass else: if not problems: return [] # Either we don't have the list, or there were unexpected classifiers # which might have been added since we last fetched it. Fetch and cache. if os.environ.get('FLIT_NO_NETWORK', ''): log.warning( "Not checking classifiers, because FLIT_NO_NETWORK is set") return [] # Try to download up-to-date list of classifiers try: _download_classifiers() except requests.ConnectionError: # The error you get on a train, going through Oregon, without wifi log.warning( "Couldn't get list of valid classifiers to check against") return problems else: return _verify_classifiers_cached(classifiers) def validate_entrypoints(entrypoints): """Check that the loaded entrypoints are valid. Expects a dict of dicts, e.g.:: {'console_scripts': {'flit': 'flit:main'}} """ def _is_identifier_attr(s): return all(n.isidentifier() for n in s.split('.')) problems = [] for groupname, group in entrypoints.items(): for k, v in group.items(): if ':' in v: mod, obj = v.split(':', 1) valid = _is_identifier_attr(mod) and _is_identifier_attr(obj) else: valid = _is_identifier_attr(v) if not valid: problems.append('Invalid entry point in group {}: ' '{} = {}'.format(groupname, k, v)) return problems # Distribution name, not quite the same as a Python identifier NAME = re.compile(r'^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$', re.IGNORECASE) r'' VERSION_SPEC = re.compile(r'(~=|===?|!=|<=?|>=?)\s*[A-Z0-9\-_.*+!]+$', re.IGNORECASE) REQUIREMENT = re.compile(NAME.pattern[:-1] + # Trim '$' r"""\s*(?P\[.*\])? \s*(?P[(=~<>!][^;]*)? \s*(?P;.*)? $""", re.IGNORECASE | re.VERBOSE) MARKER_OP = re.compile(r'(~=|===?|!=|<=?|>=?|\s+in\s+|\s+not in\s+)') def validate_name(metadata): name = metadata.get('name', None) if name is None or NAME.match(name): return [] return ['Invalid name: {!r}'.format(name)] def _valid_version_specifier(s): for clause in s.split(','): if not VERSION_SPEC.match(clause.strip()): return False return True def validate_requires_python(metadata): spec = metadata.get('requires_python', None) if spec is None or _valid_version_specifier(spec): return [] return ['Invalid requires-python: {!r}'.format(spec)] MARKER_VARS = { 'python_version', 'python_full_version', 'os_name', 'sys_platform', 'platform_release', 'platform_system', 'platform_version', 'platform_machine', 'platform_python_implementation', 'implementation_name', 'implementation_version', 'extra', } def validate_environment_marker(em): clauses = re.split(r'\s+(?:and|or)\s+', em) problems = [] for c in clauses: # TODO: validate parentheses properly. They're allowed by PEP 508. parts = MARKER_OP.split(c.strip('()')) if len(parts) != 3: problems.append("Invalid expression in environment marker: {!r}".format(c)) continue l, op, r = parts for var in (l.strip(), r.strip()): if var[:1] in {'"', "'"}: if len(var) < 2 or var[-1:] != var[:1]: problems.append("Invalid string in environment marker: {}".format(var)) elif var not in MARKER_VARS: problems.append("Invalid variable name in environment marker: {!r}".format(var)) return problems def validate_requires_dist(metadata): probs = [] for req in metadata.get('requires_dist', []): m = REQUIREMENT.match(req) if not m: probs.append("Could not parse requirement: {!r}".format(req)) continue extras, version, envmark = m.group('extras', 'version', 'envmark') if not (extras is None or all(NAME.match(e.strip()) for e in extras[1:-1].split(','))): probs.append("Invalid extras in requirement: {!r}".format(req)) if version is not None: if version.startswith('(') and version.endswith(')'): version = version[1:-1] if not _valid_version_specifier(version): print((extras, version, envmark)) probs.append("Invalid version specifier {!r} in requirement {!r}" .format(version, req)) if envmark is not None: probs.extend(validate_environment_marker(envmark[1:])) return probs def validate_url(url): if url is None: return [] probs = [] if not url.startswith(('http://', 'https://')): probs.append("URL {!r} doesn't start with https:// or http://" .format(url)) elif not url.split('//', 1)[1]: probs.append("URL missing address") return probs def validate_project_urls(metadata): probs = [] for prurl in metadata.get('project_urls', []): name, url = prurl.split(',', 1) url = url.lstrip() if not name: probs.append("No name for project URL {!r}".format(url)) elif len(name) > 32: probs.append("Project URL name {!r} longer than 32 characters" .format(name)) probs.extend(validate_url(url)) return probs def validate_config(config_info): i = config_info problems = sum([ validate_classifiers(i['metadata'].get('classifiers')), validate_entrypoints(i['entrypoints']), validate_name(i['metadata']), validate_requires_python(i['metadata']), validate_requires_dist(i['metadata']), validate_url(i['metadata'].get('home_page', None)), validate_project_urls(i['metadata']), ], []) for p in problems: log.error(p) return problems # Regex below from packaging, via PEP 440. BSD License: # Copyright (c) Donald Stufft and individual contributors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. VERSION_PERMISSIVE = re.compile(r""" \s*v? (?: (?:(?P[0-9]+)!)? # epoch (?P[0-9]+(?:\.[0-9]+)*) # release segment (?P
                                          # pre-release
            [-_\.]?
            (?P(a|b|c|rc|alpha|beta|pre|preview))
            [-_\.]?
            (?P[0-9]+)?
        )?
        (?P                                         # post release
            (?:-(?P[0-9]+))
            |
            (?:
                [-_\.]?
                (?Ppost|rev|r)
                [-_\.]?
                (?P[0-9]+)?
            )
        )?
        (?P                                          # dev release
            [-_\.]?
            (?Pdev)
            [-_\.]?
            (?P[0-9]+)?
        )?
    )
    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
\s*$""", re.VERBOSE)

pre_spellings = {
    'a': 'a', 'alpha': 'a',
    'b': 'b', 'beta': 'b',
    'rc': 'rc', 'c': 'rc', 'pre': 'rc', 'preview': 'rc',
}

def normalise_version(orig_version):
    """Normalise version number according to rules in PEP 440

    Raises InvalidVersion if the version does not match PEP 440. This can be
    overridden with the FLIT_ALLOW_INVALID environment variable.

    https://www.python.org/dev/peps/pep-0440/#normalization
    """
    version = orig_version.lower()
    m = VERSION_PERMISSIVE.match(version)
    if not m:
        if os.environ.get('FLIT_ALLOW_INVALID'):
            log.warning("Invalid version number {!r} allowed by FLIT_ALLOW_INVALID"
                        .format(orig_version))
            return version
        else:
            raise InvalidVersion("Version number {!r} does not match PEP 440 rules"
                                 .format(orig_version))

    components = []
    add = components.append

    epoch, release = m.group('epoch', 'release')
    if epoch is not None:
        add(str(int(epoch)) + '!')
    add('.'.join(str(int(rp)) for rp in release.split('.')))

    pre_l, pre_n = m.group('pre_l', 'pre_n')
    if pre_l is not None:
        pre_l = pre_spellings[pre_l]
        pre_n = '0' if pre_n is None else str(int(pre_n))
        add(pre_l + pre_n)

    post_n1, post_l, post_n2 = m.group('post_n1', 'post_l', 'post_n2')
    if post_n1 is not None:
        add('.post' + str(int(post_n1)))
    elif post_l is not None:
        post_n = '0' if post_n2 is None else str(int(post_n2))
        add('.post' + str(int(post_n)))

    dev_l, dev_n = m.group('dev_l', 'dev_n')
    if dev_l is not None:
        dev_n = '0' if dev_n is None else str(int(dev_n))
        add('.dev' + dev_n)

    local = m.group('local')
    if local is not None:
        local = local.replace('-', '.').replace('_', '.')
        l = [str(int(c)) if c.isdigit() else c
             for c in local.split('.')]
        add('+' + '.'.join(l))

    version = ''.join(components)
    if version != orig_version:
        log.warning("Version number normalised: {!r} -> {!r} (see PEP 440)"
                    .format(orig_version, version))
    return version
PKRlM"p p 
flit/wheel.pyfrom base64 import urlsafe_b64encode
import contextlib
from datetime import datetime
import hashlib
import io
import logging
import os
import re
import stat
import sys
import tempfile
from types import SimpleNamespace

if sys.version_info >= (3, 6):
    import zipfile
else:
    import zipfile36 as zipfile

from flit import __version__
from . import common
from . import inifile

log = logging.getLogger(__name__)

wheel_file_template = """\
Wheel-Version: 1.0
Generator: flit {version}
Root-Is-Purelib: true
""".format(version=__version__)

def _write_wheel_file(f, *, supports_py2=False):
    f.write(wheel_file_template)
    if supports_py2:
        f.write("Tag: py2-none-any\n")
    f.write("Tag: py3-none-any\n")


class WheelBuilder:
    def __init__(self, ini_path, target_fp):
        """Build a wheel from a module/package
        """
        self.ini_path = ini_path
        self.directory = ini_path.parent

        self.ini_info = inifile.read_pkg_ini(ini_path)
        self.module = common.Module(self.ini_info['module'], ini_path.parent)
        self.metadata = common.make_metadata(self.module, self.ini_info)

        self.records = []
        try:
            # If SOURCE_DATE_EPOCH is set (e.g. by Debian), it's used for
            # timestamps inside the zip file.
            d = datetime.utcfromtimestamp(int(os.environ['SOURCE_DATE_EPOCH']))
            log.info("Zip timestamps will be from SOURCE_DATE_EPOCH: %s", d)
            # zipfile expects a 6-tuple, not a datetime object
            self.source_time_stamp = (d.year, d.month, d.day, d.hour, d.minute, d.second)
        except (KeyError, ValueError):
            # Otherwise, we'll use the mtime of files, and generated files will
            # default to 2016-1-1 00:00:00
            self.source_time_stamp = None

        # Open the zip file ready to write
        self.wheel_zip = zipfile.ZipFile(target_fp, 'w',
                             compression=zipfile.ZIP_DEFLATED)

    @property
    def dist_info(self):
        return common.dist_info_name(self.metadata.name, self.metadata.version)

    @property
    def wheel_filename(self):
        tag = ('py2.' if self.metadata.supports_py2 else '') + 'py3-none-any'
        return '{}-{}-{}.whl'.format(
                re.sub("[^\w\d.]+", "_", self.metadata.name, flags=re.UNICODE),
                re.sub("[^\w\d.]+", "_", self.metadata.version, flags=re.UNICODE),
                tag)

    def _include(self, path):
        name = os.path.basename(path)
        if (name == '__pycache__') or name.endswith('.pyc'):
            return False
        return True

    def _add_file(self, full_path, rel_path):
        log.debug("Adding %s to zip file", full_path)
        full_path, rel_path = str(full_path), str(rel_path)
        if os.sep != '/':
            # We always want to have /-separated paths in the zip file and in
            # RECORD
            rel_path = rel_path.replace(os.sep, '/')

        if self.source_time_stamp is None:
            zinfo = zipfile.ZipInfo.from_file(full_path, rel_path)
        else:
            # Set timestamps in zipfile for reproducible build
            zinfo = zipfile.ZipInfo(rel_path, self.source_time_stamp)

        # Normalize permission bits to either 755 (executable) or 644
        st_mode = os.stat(full_path).st_mode
        new_mode = common.normalize_file_permissions(st_mode)
        zinfo.external_attr = (new_mode & 0xFFFF) << 16      # Unix attributes

        if stat.S_ISDIR(st_mode):
            zinfo.external_attr |= 0x10  # MS-DOS directory flag

        hashsum = hashlib.sha256()
        with open(full_path, 'rb') as src, self.wheel_zip.open(zinfo, 'w') as dst:
            while True:
                buf = src.read(1024 * 8)
                if not buf:
                    break
                hashsum.update(buf)
                dst.write(buf)

        size = os.stat(full_path).st_size
        hash_digest = urlsafe_b64encode(hashsum.digest()).decode('ascii').rstrip('=')
        self.records.append((rel_path, hash_digest, size))

    @contextlib.contextmanager
    def _write_to_zip(self, rel_path):
        sio = io.StringIO()
        yield sio

        log.debug("Writing data to %s in zip file", rel_path)
        # The default is a fixed timestamp rather than the current time, so
        # that building a wheel twice on the same computer can automatically
        # give you the exact same result.
        date_time = self.source_time_stamp or (2016, 1, 1, 0, 0, 0)
        zi = zipfile.ZipInfo(rel_path, date_time)
        b = sio.getvalue().encode('utf-8')
        hashsum = hashlib.sha256(b)
        hash_digest = urlsafe_b64encode(hashsum.digest()).decode('ascii').rstrip('=')
        self.wheel_zip.writestr(zi, b, compress_type=zipfile.ZIP_DEFLATED)
        self.records.append((rel_path, hash_digest, len(b)))

    def copy_module(self):
        log.info('Copying package file(s) from %s', self.module.path)
        if self.module.is_package:
            # Walk the tree and compress it, sorting everything so the order
            # is stable.
            for dirpath, dirs, files in os.walk(str(self.module.path)):
                reldir = os.path.relpath(dirpath, str(self.directory))
                for file in sorted(files):
                    full_path = os.path.join(dirpath, file)
                    if self._include(full_path):
                        self._add_file(full_path, os.path.join(reldir, file))

                dirs[:] = [d for d in sorted(dirs) if self._include(d)]
        else:
            self._add_file(str(self.module.path), self.module.path.name)

    def write_metadata(self):
        log.info('Writing metadata files')

        if self.ini_info['entrypoints']:
            with self._write_to_zip(self.dist_info + '/entry_points.txt') as f:
                common.write_entry_points(self.ini_info['entrypoints'], f)

        for base in ('COPYING', 'LICENSE'):
            for path in sorted(self.directory.glob(base + '*')):
                self._add_file(path, '%s/%s' % (self.dist_info, path.name))

        with self._write_to_zip(self.dist_info + '/WHEEL') as f:
            _write_wheel_file(f, supports_py2=self.metadata.supports_py2)

        with self._write_to_zip(self.dist_info + '/METADATA') as f:
            self.metadata.write_metadata_file(f)

    def write_record(self):
        log.info('Writing the record of files')
        # Write a record of the files in the wheel
        with self._write_to_zip(self.dist_info + '/RECORD') as f:
            for path, hash, size in self.records:
                f.write('{},sha256={},{}\n'.format(path, hash, size))
            # RECORD itself is recorded with no hash or size
            f.write(self.dist_info + '/RECORD,,\n')

    def build(self):
        try:
            self.copy_module()
            self.write_metadata()
            self.write_record()
        finally:
            self.wheel_zip.close()

def make_wheel_in(ini_path, wheel_directory):
    # We don't know the final filename until metadata is loaded, so write to
    # a temporary_file, and rename it afterwards.
    (fd, temp_path) = tempfile.mkstemp(suffix='.whl', dir=str(wheel_directory))
    try:
        with open(fd, 'w+b') as fp:
            wb = WheelBuilder(ini_path, fp)
            wb.build()

        wheel_path = wheel_directory / wb.wheel_filename
        os.replace(temp_path, str(wheel_path))
    except:
        os.unlink(temp_path)
        raise

    log.info("Built wheel: %s", wheel_path)
    return SimpleNamespace(builder=wb, file=wheel_path)

def wheel_main(ini_path, upload=False, verify_metadata=False, repo='pypi'):
    """Build a wheel in the dist/ directory, and optionally upload it.
    """
    dist_dir = ini_path.parent / 'dist'
    try:
        dist_dir.mkdir()
    except FileExistsError:
        pass

    wheel_info = make_wheel_in(ini_path, dist_dir)

    if verify_metadata:
        from .upload import verify
        log.warning("'flit wheel --verify-metadata' is deprecated.")
        verify(wheel_info.builder.metadata, repo)

    if upload:
        from .upload import do_upload
        log.warning("'flit wheel --upload' is deprecated; use 'flit publish' instead.")
        do_upload(wheel_info.file, wheel_info.builder.metadata, repo)

    return wheel_info
PKSuzG$##flit/license_templates/apacheApache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

2. Grant of Copyright License.

Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

3. Grant of Patent License.

Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

4. Redistribution.

You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

    You must give any other recipients of the Work or Derivative Works a copy of this License; and
    You must cause any modified files to carry prominent notices stating that You changed the files; and
    You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
    If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.

You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

5. Submission of Contributions.

Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

6. Trademarks.

This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty.

Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

8. Limitation of Liability.

In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability.

While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS
PKSuzG
~~flit/license_templates/gpl3                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. 
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
PKSuzGS55flit/license_templates/mitThe MIT License (MIT)

Copyright (c) {year} {author}

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
PK;lMflit/vcs/__init__.pyfrom pathlib import Path

from flit.common import VCSError
from . import hg
from . import git

def identify_vcs(directory: Path):
    directory = directory.resolve()
    for p in [directory] + list(directory.parents):
        if (p / '.git').is_dir():
            return git
        if (p / '.hg').is_dir():
            return hg

    raise VCSError("Directory does not appear to be in a VCS", directory)
PKۓK\sflit/vcs/git.pyimport os
from subprocess import check_output

name = 'git'

def list_tracked_files(directory):
    outb = check_output(['git', 'ls-files'], cwd=str(directory))
    return [os.fsdecode(l) for l in outb.strip().splitlines()]

def list_untracked_deleted_files(directory):
    outb = check_output(['git', 'ls-files', '--deleted', '--others',
                         '--exclude-standard'],
                        cwd=str(directory))
    return [os.fsdecode(l) for l in outb.strip().splitlines()]
PKsMz	flit/vcs/hg.pyimport os
from subprocess import check_output

name = 'hg'

def find_repo_root(directory):
    for p in [directory] + list(directory.parents):
        if (p / '.hg').is_dir():
            return p

def _repo_paths_to_directory_paths(paths, directory):
    # 'hg status' gives paths from repo root, which may not be our directory.
    directory = directory.resolve()
    repo = find_repo_root(directory)
    if directory != repo:
        directory_in_repo = str(directory.relative_to(repo)) + os.sep
        ix = len(directory_in_repo)
        paths = [p[ix:] for p in paths
                 if os.path.normpath(p).startswith(directory_in_repo)]
    return paths


def list_tracked_files(directory):
    outb = check_output(['hg', 'status', '--clean', '--added', '--no-status'],
                        cwd=str(directory))
    paths = [os.fsdecode(l) for l in outb.strip().splitlines()]
    return _repo_paths_to_directory_paths(paths, directory)


def list_untracked_deleted_files(directory):
    outb = check_output(['hg', 'status', '--unknown', '--deleted', '--no-status'],
                        cwd=str(directory))
    paths = [os.fsdecode(l) for l in outb.strip().splitlines()]
    return _repo_paths_to_directory_paths(paths, directory)
PK[HKflit/vendorized/__init__.pyPK[HK"flit/vendorized/readme/__init__.pyPKSuzGNNflit/vendorized/readme/clean.py## shim readme clean to simplify vendorizing of readme.rst
clean = lambda x:x
PK.AN'Aflit/vendorized/readme/rst.py# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Copied from https://github.com/pypa/readme_renderer
# Commit 5b455a9c5bafc1732dafad9619bcbfa8e15432c9

from __future__ import absolute_import, division, print_function

import io
import os.path

from docutils.core import publish_parts
from docutils.writers.html4css1 import HTMLTranslator, Writer
from docutils.utils import SystemMessage

from .clean import clean


class ReadMeHTMLTranslator(HTMLTranslator):

    def depart_image(self, node):
        uri = node["uri"]
        ext = os.path.splitext(uri)[1].lower()
        # we need to swap RST's use of `object` with `img` tags
        # see http://git.io/5me3dA
        if ext == ".svg":
            # preserve essential attributes
            atts = {}
            for attribute, value in node.attributes.items():
                # we have no time for empty values
                if value:
                    if attribute == "uri":
                        atts["src"] = value
                    else:
                        atts[attribute] = value

            # toss off `object` tag
            self.body.pop()
            # add on `img` with attributes
            self.body.append(self.starttag(node, "img", **atts))


SETTINGS = {
    # Cloaking email addresses provides a small amount of additional
    # privacy protection for email addresses inside of a chunk of ReST.
    "cloak_email_addresses": True,

    # Prevent a lone top level heading from being promoted to document
    # title, and thus second level headings from being promoted to top
    # level.
    "doctitle_xform": True,

    # Prevent a lone subsection heading from being promoted to section
    # title, and thus second level headings from being promoted to top
    # level.
    "sectsubtitle_xform": True,

    # Set our initial header level
    "initial_header_level": 2,

    # Prevent local files from being included into the rendered output.
    # This is a security concern because people can insert files
    # that are part of the system, such as /etc/passwd.
    "file_insertion_enabled": False,

    # Halt rendering and throw an exception if there was any errors or
    # warnings from docutils.
    "halt_level": 2,

    # Output math blocks as LaTeX that can be interpreted by MathJax for
    # a prettier display of Math formulas.
    "math_output": "MathJax",

    # Disable raw html as enabling it is a security risk, we do not want
    # people to be able to include any old HTML in the final output.
    "raw_enabled": False,

    # Disable all system messages from being reported.
    "report_level": 5,

    # Use typographic quotes, and transform --, ---, and ... into their
    # typographic counterparts.
    "smart_quotes": True,

    # Strip all comments from the rendered output.
    "strip_comments": True,

    # Use the short form of syntax highlighting so that the generated
    # Pygments CSS can be used to style the output.
    "syntax_highlight": "short",
}


def render(raw, stream=None):
    if stream is None:
        # Use a io.StringIO as the warning stream to prevent warnings from
        # being printed to sys.stderr.
        stream = io.StringIO()

    settings = SETTINGS.copy()
    settings["warning_stream"] = stream

    writer = Writer()
    writer.translator_class = ReadMeHTMLTranslator

    try:
        parts = publish_parts(raw, writer=writer, settings_overrides=settings)
    except SystemMessage:
        rendered = None
    else:
        rendered = parts.get("fragment")

    if rendered:
        return clean(rendered)
    else:
        return None
PK!HΉ!"#flit-1.3.dist-info/entry_points.txtN+I/N.,()J,Vy\\PKowIpflit-1.3.dist-info/LICENSECopyright (c) 2015, Thomas Kluyver and contributors
All rights reserved.

BSD 3-clause license:

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
PK!HPOflit-1.3.dist-info/WHEELHM
K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UrPK!H)
flit-1.3.dist-info/METADATAVn6ϧ8"y
pٲK4
t-gHʎk'ܓRTkk MkxO~JfpK^,+X~NM[fp
VM%ZӺ6oMٯIgP:dlimx2ʢWo~d+mknUQsY˗ifVa^Lٙ7%?jrANܻ}bc?VZL!
8m)T.`63nG]$N
n#+W5AxժEH>Lߦou#s:KFXj|	_ȅF
;Zm%"gҺ);/t:Y7;{,e%>'t7΀T0SEm@0	0E=/VUCU4StpWl1Q`<~qr~N?S:f_y]	 d8*^R 26z"ԤdbB&6@o?mƽ>{wdH<i]T,o઀:jwu2v$||Ցd
I
lbD03LE_Sm6JR<ձZP)z5
nsJ1rѺrxEguDD+GEjh

^~t;F:2;eKd? $=x@^PJK]2݉Rye``o
cG)kH\cKL!Y4DRIE:[ԤL+=2F1.Y򟦐B$J٬#C~Fѩ^>>$_e/80
'0:=3vM B^Q0
ru(ޢsh
g6&oJ)gCN,@Wi%הi?	:c[*Ni_ 'p7FU_ d8_7;שѥ=CFK7^H.d0t2Mq/Xu>Xi$:'?0T,t00(@8kA+
A515/6A$$p:'մtue#xl}O1ly'idJ;31^kUW"6%=Lv2kJ8-;[gЪv$Bf6xE)}g#NB
V4ɋ4P}L(Eq*`| -Nu)eึه(2f̡P!iɓ=9GrPݜmv:RksZ䜑iGY(A4|SQ?&uW=~])(N.XJ"
>ouW65۟jUWn'7w-l4%3<=hs}p`u1LMC8.$y-Ǿr9NI~hGl( lw$ќe\flit/license_templates/mitPK;lMBflit/vcs/__init__.pyPKۓK\sYDflit/vcs/git.pyPKsMz	tFflit/vcs/hg.pyPK[HK|Kflit/vendorized/__init__.pyPK[HK"Kflit/vendorized/readme/__init__.pyPKSuzGNNKflit/vendorized/readme/clean.pyPK.AN'ALflit/vendorized/readme/rst.pyPK!HΉ!"#\flit-1.3.dist-info/entry_points.txtPKowIp5]flit-1.3.dist-info/LICENSEPK!HPObcflit-1.3.dist-info/WHEELPK!H)
cflit-1.3.dist-info/METADATAPK!H,Y	jflit-1.3.dist-info/RECORDPK  <o