in bazel/pyc_wheel.py [0:0]
def convert_wheel(whl_file: Path, *, exclude=None, with_backup=False, quiet=False):
"""Generate a new whl with only pyc files."""
if whl_file.suffix != ".whl":
raise TypeError("File to convert must be a *.whl")
if exclude: exclude = re.compile(exclude)
dist_info = "-".join(whl_file.stem.split("-")[:-3])
whl_dir = tempfile.mkdtemp()
whl_path = Path(whl_dir)
try:
# Extract our zip file temporarily
with zipfile.ZipFile(str(whl_file), "r") as whl_zip:
whl_zip.extractall(whl_dir)
members = [member for member in whl_zip.infolist()
if member.is_dir() or not member.filename.endswith(".py")]
# Compile all py files
if not compileall.compile_dir(whl_dir, rx=exclude,
ddir="<{}>".format(dist_info),
quiet=int(quiet), force=True, legacy=True):
raise RuntimeError("Error compiling Python sources in wheel "
"{!s}".format(whl_file.name))
# Remove all original py files
for py_file in whl_path.glob("**/*.py"):
if py_file.is_file():
if exclude is None or not exclude.search(str(py_file)):
if not quiet: print("Deleting py file: {!s}".format(py_file))
py_file.chmod(stat.S_IWUSR)
py_file.unlink()
for root, dirs, files in os.walk(whl_dir):
for fname in files:
if fname.endswith(".py"):
py_file = Path(root)/fname
if exclude is None or not exclude.search(str(py_file)):
if not quiet: print("Removing file: {!s}".format(py_file))
py_file.chmod(stat.S_IWUSR)
py_file.unlink()
for member in members:
file_path = whl_path/member.filename
timestamp = datetime(*member.date_time).timestamp()
try:
os.utime(str(file_path), (timestamp, timestamp))
except Exception:
pass # ignore errors
# dist_info_path = whl_path/"{}.dist-info".format(dist_info)
# rewrite_dist_info(dist_info_path, exclude=exclude)
# Rezip the file with the new version info
whl_file_zip = whl_path.with_suffix(".zip")
if whl_file_zip.exists(): whl_file_zip.unlink()
shutil.make_archive(whl_dir, "zip", root_dir=whl_dir)
if with_backup:
whl_file.replace(whl_file.with_suffix(whl_file.suffix + ".bak"))
shutil.move(str(whl_file_zip), str(whl_file))
finally:
# Clean up original directory
shutil.rmtree(whl_dir, ignore_errors=True)