summaryrefslogtreecommitdiff
path: root/src/wheel/cli
diff options
context:
space:
mode:
authorAlex Grönholm <alex.gronholm@nextday.fi>2021-12-24 01:27:26 +0200
committerAlex Grönholm <alex.gronholm@nextday.fi>2021-12-24 01:45:01 +0200
commit5eb690c72ea59bc0f8a2fa34d3993ebe3dbe0d38 (patch)
treedff2a2103314f0fe6c5cc53b91a120f59edf78d3 /src/wheel/cli
parent64d0b8d779b5b41bacea2ef3b59f3e06f0e683ed (diff)
downloadwheel-git-5eb690c72ea59bc0f8a2fa34d3993ebe3dbe0d38.tar.gz
Adopted black and reformatted the codebase to match
Diffstat (limited to 'src/wheel/cli')
-rw-r--r--src/wheel/cli/__init__.py49
-rwxr-xr-xsrc/wheel/cli/convert.py95
-rw-r--r--src/wheel/cli/pack.py62
-rw-r--r--src/wheel/cli/unpack.py8
4 files changed, 121 insertions, 93 deletions
diff --git a/src/wheel/cli/__init__.py b/src/wheel/cli/__init__.py
index c8a3b35..31ac4c8 100644
--- a/src/wheel/cli/__init__.py
+++ b/src/wheel/cli/__init__.py
@@ -20,21 +20,25 @@ class WheelError(Exception):
def unpack_f(args):
from .unpack import unpack
+
unpack(args.wheelfile, args.dest)
def pack_f(args):
from .pack import pack
+
pack(args.directory, args.dest_dir, args.build_number)
def convert_f(args):
from .convert import convert
+
convert(args.files, args.dest_dir, args.verbose)
def version_f(args):
from .. import __version__
+
print("wheel %s" % __version__)
@@ -42,30 +46,41 @@ def parser():
p = argparse.ArgumentParser()
s = p.add_subparsers(help="commands")
- unpack_parser = s.add_parser('unpack', help='Unpack wheel')
- unpack_parser.add_argument('--dest', '-d', help='Destination directory',
- default='.')
- unpack_parser.add_argument('wheelfile', help='Wheel file')
+ unpack_parser = s.add_parser("unpack", help="Unpack wheel")
+ unpack_parser.add_argument(
+ "--dest", "-d", help="Destination directory", default="."
+ )
+ unpack_parser.add_argument("wheelfile", help="Wheel file")
unpack_parser.set_defaults(func=unpack_f)
- repack_parser = s.add_parser('pack', help='Repack wheel')
- repack_parser.add_argument('directory', help='Root directory of the unpacked wheel')
- repack_parser.add_argument('--dest-dir', '-d', default=os.path.curdir,
- help="Directory to store the wheel (default %(default)s)")
- repack_parser.add_argument('--build-number', help="Build tag to use in the wheel name")
+ repack_parser = s.add_parser("pack", help="Repack wheel")
+ repack_parser.add_argument("directory", help="Root directory of the unpacked wheel")
+ repack_parser.add_argument(
+ "--dest-dir",
+ "-d",
+ default=os.path.curdir,
+ help="Directory to store the wheel (default %(default)s)",
+ )
+ repack_parser.add_argument(
+ "--build-number", help="Build tag to use in the wheel name"
+ )
repack_parser.set_defaults(func=pack_f)
- convert_parser = s.add_parser('convert', help='Convert egg or wininst to wheel')
- convert_parser.add_argument('files', nargs='*', help='Files to convert')
- convert_parser.add_argument('--dest-dir', '-d', default=os.path.curdir,
- help="Directory to store wheels (default %(default)s)")
- convert_parser.add_argument('--verbose', '-v', action='store_true')
+ convert_parser = s.add_parser("convert", help="Convert egg or wininst to wheel")
+ convert_parser.add_argument("files", nargs="*", help="Files to convert")
+ convert_parser.add_argument(
+ "--dest-dir",
+ "-d",
+ default=os.path.curdir,
+ help="Directory to store wheels (default %(default)s)",
+ )
+ convert_parser.add_argument("--verbose", "-v", action="store_true")
convert_parser.set_defaults(func=convert_f)
- version_parser = s.add_parser('version', help='Print version and exit')
+ version_parser = s.add_parser("version", help="Print version and exit")
version_parser.set_defaults(func=version_f)
- help_parser = s.add_parser('help', help='Show this help')
+ help_parser = s.add_parser("help", help="Show this help")
help_parser.set_defaults(func=lambda args: p.print_help())
return p
@@ -74,7 +89,7 @@ def parser():
def main():
p = parser()
args = p.parse_args()
- if not hasattr(args, 'func'):
+ if not hasattr(args, "func"):
p.print_help()
else:
try:
diff --git a/src/wheel/cli/convert.py b/src/wheel/cli/convert.py
index 5c76d5f..b2f685f 100755
--- a/src/wheel/cli/convert.py
+++ b/src/wheel/cli/convert.py
@@ -10,11 +10,14 @@ from ..bdist_wheel import bdist_wheel
from ..wheelfile import WheelFile
from . import WheelError, require_pkgresources
-egg_info_re = re.compile(r'''
+egg_info_re = re.compile(
+ r"""
(?P<name>.+?)-(?P<ver>.+?)
(-(?P<pyver>py\d\.\d+)
(-(?P<arch>.+?))?
- )?.egg$''', re.VERBOSE)
+ )?.egg$""",
+ re.VERBOSE,
+)
class _bdist_wheel_tag(bdist_wheel):
@@ -37,7 +40,7 @@ def egg2wheel(egg_path, dest_dir):
filename = os.path.basename(egg_path)
match = egg_info_re.match(filename)
if not match:
- raise WheelError(f'Invalid egg file name: {filename}')
+ raise WheelError(f"Invalid egg file name: {filename}")
egg_info = match.groupdict()
dir = tempfile.mkdtemp(suffix="_e2w")
@@ -54,16 +57,16 @@ def egg2wheel(egg_path, dest_dir):
else:
shutil.copytree(src, os.path.join(dir, pth))
- pyver = egg_info['pyver']
+ pyver = egg_info["pyver"]
if pyver:
- pyver = egg_info['pyver'] = pyver.replace('.', '')
+ pyver = egg_info["pyver"] = pyver.replace(".", "")
- arch = (egg_info['arch'] or 'any').replace('.', '_').replace('-', '_')
+ arch = (egg_info["arch"] or "any").replace(".", "_").replace("-", "_")
# assume all binary eggs are for CPython
- abi = 'cp' + pyver[2:] if arch != 'any' else 'none'
+ abi = "cp" + pyver[2:] if arch != "any" else "none"
- root_is_purelib = egg_info['arch'] is None
+ root_is_purelib = egg_info["arch"] is None
if root_is_purelib:
bw = bdist_wheel(dist.Distribution())
else:
@@ -72,16 +75,16 @@ def egg2wheel(egg_path, dest_dir):
bw.root_is_pure = root_is_purelib
bw.python_tag = pyver
bw.plat_name_supplied = True
- bw.plat_name = egg_info['arch'] or 'any'
+ bw.plat_name = egg_info["arch"] or "any"
if not root_is_purelib:
bw.full_tag_supplied = True
bw.full_tag = (pyver, abi, arch)
- dist_info_dir = os.path.join(dir, '{name}-{ver}.dist-info'.format(**egg_info))
- bw.egg2dist(os.path.join(dir, 'EGG-INFO'), dist_info_dir)
- bw.write_wheelfile(dist_info_dir, generator='egg2wheel')
- wheel_name = '{name}-{ver}-{pyver}-{}-{}.whl'.format(abi, arch, **egg_info)
- with WheelFile(os.path.join(dest_dir, wheel_name), 'w') as wf:
+ dist_info_dir = os.path.join(dir, "{name}-{ver}.dist-info".format(**egg_info))
+ bw.egg2dist(os.path.join(dir, "EGG-INFO"), dist_info_dir)
+ bw.write_wheelfile(dist_info_dir, generator="egg2wheel")
+ wheel_name = "{name}-{ver}-{pyver}-{}-{}.whl".format(abi, arch, **egg_info)
+ with WheelFile(os.path.join(dest_dir, wheel_name), "w") as wf:
wf.write_files(dir)
shutil.rmtree(dir)
@@ -128,34 +131,34 @@ def parse_wininst_info(wininfo_name, egginfo_name):
# Parse the wininst filename
# 1. Distribution name (up to the first '-')
- w_name, sep, rest = wininfo_name.partition('-')
+ w_name, sep, rest = wininfo_name.partition("-")
if not sep:
raise ValueError(f"Installer filename {wininfo_name} is not valid")
# Strip '.exe'
rest = rest[:-4]
# 2. Python version (from the last '-', must start with 'py')
- rest2, sep, w_pyver = rest.rpartition('-')
- if sep and w_pyver.startswith('py'):
+ rest2, sep, w_pyver = rest.rpartition("-")
+ if sep and w_pyver.startswith("py"):
rest = rest2
- w_pyver = w_pyver.replace('.', '')
+ w_pyver = w_pyver.replace(".", "")
else:
# Not version specific - use py2.py3. While it is possible that
# pure-Python code is not compatible with both Python 2 and 3, there
# is no way of knowing from the wininst format, so we assume the best
# here (the user can always manually rename the wheel to be more
# restrictive if needed).
- w_pyver = 'py2.py3'
+ w_pyver = "py2.py3"
# 3. Version and architecture
- w_ver, sep, w_arch = rest.rpartition('.')
+ w_ver, sep, w_arch = rest.rpartition(".")
if not sep:
raise ValueError(f"Installer filename {wininfo_name} is not valid")
if egginfo:
- w_name = egginfo.group('name')
- w_ver = egginfo.group('ver')
+ w_name = egginfo.group("name")
+ w_ver = egginfo.group("ver")
- return {'name': w_name, 'ver': w_ver, 'arch': w_arch, 'pyver': w_pyver}
+ return {"name": w_name, "ver": w_ver, "arch": w_arch, "pyver": w_pyver}
def wininst2wheel(path, dest_dir):
@@ -163,7 +166,7 @@ def wininst2wheel(path, dest_dir):
# Search for egg-info in the archive
egginfo_name = None
for filename in bdw.namelist():
- if '.egg-info' in filename:
+ if ".egg-info" in filename:
egginfo_name = filename
break
@@ -171,13 +174,13 @@ def wininst2wheel(path, dest_dir):
root_is_purelib = True
for zipinfo in bdw.infolist():
- if zipinfo.filename.startswith('PLATLIB'):
+ if zipinfo.filename.startswith("PLATLIB"):
root_is_purelib = False
break
if root_is_purelib:
- paths = {'purelib': ''}
+ paths = {"purelib": ""}
else:
- paths = {'platlib': ''}
+ paths = {"platlib": ""}
dist_info = "%(name)s-%(ver)s" % info
datadir = "%s.data/" % dist_info
@@ -185,13 +188,13 @@ def wininst2wheel(path, dest_dir):
# rewrite paths to trick ZipFile into extracting an egg
# XXX grab wininst .ini - between .exe, padding, and first zip file.
members = []
- egginfo_name = ''
+ egginfo_name = ""
for zipinfo in bdw.infolist():
- key, basename = zipinfo.filename.split('/', 1)
+ key, basename = zipinfo.filename.split("/", 1)
key = key.lower()
basepath = paths.get(key, None)
if basepath is None:
- basepath = datadir + key.lower() + '/'
+ basepath = datadir + key.lower() + "/"
oldname = zipinfo.filename
newname = basepath + basename
zipinfo.filename = newname
@@ -202,27 +205,27 @@ def wininst2wheel(path, dest_dir):
members.append(newname)
# Remember egg-info name for the egg2dist call below
if not egginfo_name:
- if newname.endswith('.egg-info'):
+ if newname.endswith(".egg-info"):
egginfo_name = newname
- elif '.egg-info/' in newname:
- egginfo_name, sep, _ = newname.rpartition('/')
+ elif ".egg-info/" in newname:
+ egginfo_name, sep, _ = newname.rpartition("/")
dir = tempfile.mkdtemp(suffix="_b2w")
bdw.extractall(dir, members)
# egg2wheel
- abi = 'none'
- pyver = info['pyver']
- arch = (info['arch'] or 'any').replace('.', '_').replace('-', '_')
+ abi = "none"
+ pyver = info["pyver"]
+ arch = (info["arch"] or "any").replace(".", "_").replace("-", "_")
# Wininst installers always have arch even if they are not
# architecture-specific (because the format itself is).
# So, assume the content is architecture-neutral if root is purelib.
if root_is_purelib:
- arch = 'any'
+ arch = "any"
# If the installer is architecture-specific, it's almost certainly also
# CPython-specific.
- if arch != 'any':
- pyver = pyver.replace('py', 'cp')
- wheel_name = '-'.join((dist_info, pyver, abi, arch))
+ if arch != "any":
+ pyver = pyver.replace("py", "cp")
+ wheel_name = "-".join((dist_info, pyver, abi, arch))
if root_is_purelib:
bw = bdist_wheel(dist.Distribution())
else:
@@ -231,18 +234,18 @@ def wininst2wheel(path, dest_dir):
bw.root_is_pure = root_is_purelib
bw.python_tag = pyver
bw.plat_name_supplied = True
- bw.plat_name = info['arch'] or 'any'
+ bw.plat_name = info["arch"] or "any"
if not root_is_purelib:
bw.full_tag_supplied = True
bw.full_tag = (pyver, abi, arch)
- dist_info_dir = os.path.join(dir, '%s.dist-info' % dist_info)
+ dist_info_dir = os.path.join(dir, "%s.dist-info" % dist_info)
bw.egg2dist(os.path.join(dir, egginfo_name), dist_info_dir)
- bw.write_wheelfile(dist_info_dir, generator='wininst2wheel')
+ bw.write_wheelfile(dist_info_dir, generator="wininst2wheel")
wheel_path = os.path.join(dest_dir, wheel_name)
- with WheelFile(wheel_path, 'w') as wf:
+ with WheelFile(wheel_path, "w") as wf:
wf.write_files(dir)
shutil.rmtree(dir)
@@ -250,11 +253,11 @@ def wininst2wheel(path, dest_dir):
def convert(files, dest_dir, verbose):
# Only support wheel convert if pkg_resources is present
- require_pkgresources('wheel convert')
+ require_pkgresources("wheel convert")
for pat in files:
for installer in iglob(pat):
- if os.path.splitext(installer)[1] == '.egg':
+ if os.path.splitext(installer)[1] == ".egg":
conv = egg2wheel
else:
conv = wininst2wheel
diff --git a/src/wheel/cli/pack.py b/src/wheel/cli/pack.py
index 094eb67..349f722 100644
--- a/src/wheel/cli/pack.py
+++ b/src/wheel/cli/pack.py
@@ -5,7 +5,7 @@ from wheel.cli import WheelError
from wheel.wheelfile import WheelFile
DIST_INFO_RE = re.compile(r"^(?P<namever>(?P<name>.+?)-(?P<ver>\d.*?))\.dist-info$")
-BUILD_NUM_RE = re.compile(br'Build: (\d\w*)$')
+BUILD_NUM_RE = re.compile(br"Build: (\d\w*)$")
def pack(directory, dest_dir, build_number):
@@ -18,44 +18,54 @@ def pack(directory, dest_dir, build_number):
:param dest_dir: Destination directory (defaults to the current directory)
"""
# Find the .dist-info directory
- dist_info_dirs = [fn for fn in os.listdir(directory)
- if os.path.isdir(os.path.join(directory, fn)) and DIST_INFO_RE.match(fn)]
+ dist_info_dirs = [
+ fn
+ for fn in os.listdir(directory)
+ if os.path.isdir(os.path.join(directory, fn)) and DIST_INFO_RE.match(fn)
+ ]
if len(dist_info_dirs) > 1:
- raise WheelError(f'Multiple .dist-info directories found in {directory}')
+ raise WheelError(f"Multiple .dist-info directories found in {directory}")
elif not dist_info_dirs:
- raise WheelError(f'No .dist-info directories found in {directory}')
+ raise WheelError(f"No .dist-info directories found in {directory}")
# Determine the target wheel filename
dist_info_dir = dist_info_dirs[0]
- name_version = DIST_INFO_RE.match(dist_info_dir).group('namever')
+ name_version = DIST_INFO_RE.match(dist_info_dir).group("namever")
# Read the tags and the existing build number from .dist-info/WHEEL
existing_build_number = None
- wheel_file_path = os.path.join(directory, dist_info_dir, 'WHEEL')
+ wheel_file_path = os.path.join(directory, dist_info_dir, "WHEEL")
with open(wheel_file_path) as f:
tags = []
for line in f:
- if line.startswith('Tag: '):
- tags.append(line.split(' ')[1].rstrip())
- elif line.startswith('Build: '):
- existing_build_number = line.split(' ')[1].rstrip()
+ if line.startswith("Tag: "):
+ tags.append(line.split(" ")[1].rstrip())
+ elif line.startswith("Build: "):
+ existing_build_number = line.split(" ")[1].rstrip()
if not tags:
- raise WheelError('No tags present in {}/WHEEL; cannot determine target wheel filename'
- .format(dist_info_dir))
+ raise WheelError(
+ "No tags present in {}/WHEEL; cannot determine target wheel "
+ "filename".format(dist_info_dir)
+ )
# Set the wheel file name and add/replace/remove the Build tag in .dist-info/WHEEL
build_number = build_number if build_number is not None else existing_build_number
if build_number is not None:
if build_number:
- name_version += '-' + build_number
+ name_version += "-" + build_number
if build_number != existing_build_number:
- replacement = ('Build: %s\r\n' % build_number).encode('ascii') if build_number else b''
- with open(wheel_file_path, 'rb+') as f:
+ replacement = (
+ ("Build: %s\r\n" % build_number).encode("ascii")
+ if build_number
+ else b""
+ )
+ with open(wheel_file_path, "rb+") as f:
wheel_file_content = f.read()
- wheel_file_content, num_replaced = BUILD_NUM_RE.subn(replacement,
- wheel_file_content)
+ wheel_file_content, num_replaced = BUILD_NUM_RE.subn(
+ replacement, wheel_file_content
+ )
if not num_replaced:
wheel_file_content += replacement
@@ -64,15 +74,15 @@ def pack(directory, dest_dir, build_number):
f.write(wheel_file_content)
# Reassemble the tags for the wheel file
- impls = sorted({tag.split('-')[0] for tag in tags})
- abivers = sorted({tag.split('-')[1] for tag in tags})
- platforms = sorted({tag.split('-')[2] for tag in tags})
- tagline = '-'.join(['.'.join(impls), '.'.join(abivers), '.'.join(platforms)])
+ impls = sorted({tag.split("-")[0] for tag in tags})
+ abivers = sorted({tag.split("-")[1] for tag in tags})
+ platforms = sorted({tag.split("-")[2] for tag in tags})
+ tagline = "-".join([".".join(impls), ".".join(abivers), ".".join(platforms)])
# Repack the wheel
- wheel_path = os.path.join(dest_dir, f'{name_version}-{tagline}.whl')
- with WheelFile(wheel_path, 'w') as wf:
- print(f"Repacking wheel as {wheel_path}...", end='', flush=True)
+ wheel_path = os.path.join(dest_dir, f"{name_version}-{tagline}.whl")
+ with WheelFile(wheel_path, "w") as wf:
+ print(f"Repacking wheel as {wheel_path}...", end="", flush=True)
wf.write_files(directory)
- print('OK')
+ print("OK")
diff --git a/src/wheel/cli/unpack.py b/src/wheel/cli/unpack.py
index 3f3963c..ffd0e81 100644
--- a/src/wheel/cli/unpack.py
+++ b/src/wheel/cli/unpack.py
@@ -3,7 +3,7 @@ import os.path
from ..wheelfile import WheelFile
-def unpack(path, dest='.'):
+def unpack(path, dest="."):
"""Unpack a wheel.
Wheel content will be unpacked to {dest}/{name}-{ver}, where {name}
@@ -13,9 +13,9 @@ def unpack(path, dest='.'):
:param dest: Destination directory (default to current directory).
"""
with WheelFile(path) as wf:
- namever = wf.parsed_filename.group('namever')
+ namever = wf.parsed_filename.group("namever")
destination = os.path.join(dest, namever)
- print(f"Unpacking to: {destination}...", end='', flush=True)
+ print(f"Unpacking to: {destination}...", end="", flush=True)
wf.extractall(destination)
- print('OK')
+ print("OK")