1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
|
# Copyright © 2013-2019 Piotr Ożarowski <piotr@debian.org>
#
# 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.
import difflib
import logging
import os
import re
import sys
from filecmp import cmp as cmpfile
from os.path import (lexists, exists, isdir, islink, join, realpath, split,
splitext)
from shutil import rmtree
from stat import ST_MODE, S_IXUSR, S_IXGRP, S_IXOTH
from dhpython import MULTIARCH_DIR_TPL
from dhpython.tools import fix_shebang, clean_egg_name
from dhpython.interpreter import Interpreter
log = logging.getLogger('dhpython')
def fix_locations(package, interpreter, versions, options):
"""Move files to the right location."""
# make a copy since we change version later
interpreter = Interpreter(interpreter)
for version in versions:
interpreter.version = version
dstdir = interpreter.sitedir(package)
for srcdir in interpreter.old_sitedirs(package):
if isdir(srcdir):
# TODO: what about relative symlinks?
log.debug('moving files from %s to %s', srcdir, dstdir)
share_files(srcdir, dstdir, interpreter, options)
try:
os.removedirs(srcdir)
except OSError:
pass
# do the same with debug locations
dstdir = interpreter.sitedir(package, gdb=True)
for srcdir in interpreter.old_sitedirs(package, gdb=True):
if isdir(srcdir):
log.debug('moving files from %s to %s', srcdir, dstdir)
share_files(srcdir, dstdir, interpreter, options)
try:
os.removedirs(srcdir)
except OSError:
pass
def share_files(srcdir, dstdir, interpreter, options):
"""Try to move as many files from srcdir to dstdir as possible."""
cleanup_actions = []
for i in os.listdir(srcdir):
fpath1 = join(srcdir, i)
if not lexists(fpath1): # removed in rename_ext
continue
if i.endswith('.pyc'): # f.e. when tests were invoked on installed files
os.remove(fpath1)
continue
if i == ".coverage": # from running tests with coverage
os.remove(fpath1)
continue
if not options.no_ext_rename and splitext(i)[-1] == '.so':
# try to rename extension here as well (in :meth:`scan` info about
# Python version is gone)
version = interpreter.parse_public_dir(srcdir)
if version and version is not True:
fpath1 = Scan.rename_ext(fpath1, interpreter, version)
i = split(fpath1)[-1]
if srcdir.endswith(".dist-info"):
if (i.startswith(('LICENCE', 'LICENSE', 'COPYING', 'NOTICE', 'AUTHORS'))
or i in ('licenses', 'license_files')):
if isdir(fpath1):
rmtree(fpath1)
else:
os.remove(fpath1)
continue
fpath2 = join(dstdir, i)
if not isdir(fpath1) and not exists(fpath2):
# do not rename directories here - all .so files have to be renamed first
os.renames(fpath1, fpath2)
continue
if islink(fpath1):
# move symlinks without changing them if they point to the same place
if not exists(fpath2):
os.renames(fpath1, fpath2)
elif realpath(fpath1) == realpath(fpath2):
os.remove(fpath1)
elif isdir(fpath1):
share_files(fpath1, fpath2, interpreter, options)
elif cmpfile(fpath1, fpath2, shallow=False):
os.remove(fpath1)
elif i.endswith(('.abi3.so', '.abi4.so')) and interpreter.parse_public_dir(srcdir):
log.warning('%s differs from previous one, removing anyway (%s)', i, srcdir)
os.remove(fpath1)
elif srcdir.endswith(".dist-info"):
# dist-info file that differs... try merging
if i == "WHEEL":
os.remove(fpath1)
elif i == "RECORD":
os.remove(fpath1)
else:
log.warning("No merge driver for dist-info file %s", i)
else:
# The files differed so we cannot collapse them.
log.warning('Paths differ: %s and %s', fpath1, fpath2)
if options.verbose and not i.endswith(('.so', '.a')):
with open(fpath1, encoding="UTF-8") as fp1:
fromlines = fp1.readlines()
with open(fpath2, encoding="UTF-8") as fp2:
tolines = fp2.readlines()
diff = difflib.unified_diff(fromlines, tolines, fpath1, fpath2)
sys.stderr.writelines(diff)
for action, args in cleanup_actions:
action(dstdir, *args)
try:
os.removedirs(srcdir)
except OSError:
pass
## Functions to merge parts of the .dist-info metadata directory together
def missing_lines(src, dst):
"""Find all the lines in the text file src that are not in dst"""
with open(dst, encoding="UTF-8") as fh:
current = {k: None for k in fh.readlines()}
missing = []
with open(src, encoding="UTF-8") as fh:
for line in fh.readlines():
if line not in current:
missing.append(line)
return missing
def merge_WHEEL(src, dst):
"""Merge the source .dist-info/WHEEL file into the destination
Note that after editing the WHEEL file, the sha256 included in
the .dist-info/RECORD file will be incorrect and will need fixing
using the fix_merged_RECORD() function.
"""
log.debug("Merging WHEEL file %s into %s", src, dst)
missing = missing_lines(src, dst)
with open(dst, "at", encoding="UTF-8") as fh:
for line in missing:
if line.startswith("Tag: "):
fh.write(line)
else:
log.warning("WHEEL merge discarded line %s", line)
return len(missing)
def write_INSTALLER(distdir):
"""Write 'debain' as the INSTALLER"""
log.debug("Writing INSTALLER in %s", distdir)
installer = join(distdir, "INSTALLER")
with open(installer, "w", encoding="UTF-8") as f:
f.write("debian\n")
def remove_RECORD(distdir):
"""Remove RECORD from a .dist-info.
Having this breaks multi-arch installation, as the contents differ.
"""
log.debug("Deleting RECORD in %s", distdir)
try:
os.remove(join(distdir, "RECORD"))
except FileNotFoundError:
pass
class Scan:
UNWANTED_DIRS = re.compile(r'.*/__pycache__(/.*)?$')
UNWANTED_FILES = re.compile(r'.*\.py[co]$')
def __init__(self, interpreter, package, dpath=None, options=None):
self.interpreter = interpreter
self.impl = interpreter.impl
self.package = package
if not dpath:
self.proot = "debian/%s" % self.package
else:
dpath = dpath.strip('/')
self.proot = join('debian', self.package, dpath)
self.dpath = dpath
del dpath
self.options = options
self.result = {'requires.txt': set(),
'egg-info': set(),
'dist-info': set(),
'nsp.txt': set(),
'shebangs': set(),
'public_vers': set(),
'private_dirs': {},
'compile': False,
'ext_vers': set(),
'ext_no_version': set()}
for root, dirs, file_names in os.walk(self.proot):
if interpreter.should_ignore(root):
del dirs[:]
continue
self.current_private_dir = self.current_pub_version = None
version = interpreter.parse_public_dir(root)
if version:
self.current_dir_is_public = True
if version is True:
version = None
else:
self.current_pub_version = version
else:
self.current_dir_is_public = False
if self.current_dir_is_public:
if root.endswith('-packages'):
if version is not None:
self.result['public_vers'].add(version)
for name in dirs[:]:
if name in ('test', 'tests') or name.startswith('.'):
log.debug('removing dist-packages/%s', name)
rmtree(join(root, name))
dirs.remove(name)
for name in file_names[:]:
if name.startswith('.'):
log.debug('removing dist-packages/%s', name)
os.remove(join(root, name))
file_names.remove(name)
else:
self.current_private_dir = self.check_private_dir(root)
if not self.current_private_dir:
# i.e. not a public dir and not a private dir
if self.is_bin_dir(root):
self.handle_bin_dir(root, file_names)
else: # not a public, private or bin directory
# continue with a subdirectory
continue
for name in dirs[:]:
dpath = join(root, name)
if self.is_unwanted_dir(dpath):
rmtree(dpath)
dirs.remove(name)
if self.is_dist_dir(root):
self.handle_dist_dir(root, file_names)
continue
if self.is_egg_dir(root):
self.handle_egg_dir(root, file_names)
continue
# check files
for fn in sorted(file_names):
# sorted() to make sure .so files are handled before .so.foo
fpath = join(root, fn)
if self.is_unwanted_file(fpath):
log.debug('removing unwanted: %s', fpath)
os.remove(fpath)
continue
if self.is_egg_file(fpath):
self.handle_egg_file(fpath)
continue
if not exists(fpath):
# possibly removed while handling .so symlinks
if islink(fpath) and '.so.' in split(fpath)[-1]:
# dangling symlink to (now removed/renamed) .so file
# which wasn't removed yet (see test203's quux.so.0)
log.info('removing dangling symlink: %s', fpath)
os.remove(fpath)
continue
fext = splitext(fn)[-1][1:]
if fext == 'so':
if not self.options.no_ext_rename:
fpath = self.rename_ext(fpath, interpreter, version)
ver = self.handle_ext(fpath) # pylint: disable=assignment-from-none
ver = ver or version
if ver:
self.current_result.setdefault('ext_vers', set()).add(ver)
else:
self.current_result.setdefault('ext_no_version', set()).add(fpath)
if self.current_private_dir:
if exists(fpath) and fext != 'so':
mode = os.stat(fpath)[ST_MODE]
if mode & S_IXUSR or mode & S_IXGRP or mode & S_IXOTH:
if (options.no_shebang_rewrite or
fix_shebang(fpath, self.options.shebang)) and \
not self.options.ignore_shebangs:
try:
res = Interpreter.from_file(fpath)
except Exception as e:
log.debug('cannot parse shebang %s: %s', fpath, e)
else:
self.current_result.setdefault('shebangs', set()).add(res)
if fext == 'py':
self.current_result['compile'] = True
if not dirs and not self.current_private_dir:
try:
os.removedirs(root)
except OSError:
pass
log.debug("package %s details = %s", package, self.result)
@property
def current_result(self):
if self.current_private_dir:
return self.result['private_dirs'].setdefault(self.current_private_dir, {})
return self.result
def is_unwanted_dir(self, dpath):
return self.__class__.UNWANTED_DIRS.match(dpath)
def is_unwanted_file(self, fpath):
if self.__class__.UNWANTED_FILES.match(fpath):
return True
if self.current_dir_is_public and self.is_dbg_package\
and self.options.clean_dbg_pkg\
and splitext(fpath)[-1][1:] not in ('so', 'h'):
return True
@property
def private_dirs_to_check(self):
if self.dpath:
# scan private directory *only*
return [self.dpath]
if self.dpath is False:
result = []
else:
result = [i % self.package for i in (
'usr/lib/%s',
'usr/lib/games/%s',
'usr/share/%s',
'usr/share/games/%s')]
return result
@property
def is_dbg_package(self):
#return self.interpreter.debug
return self.package.endswith('-dbg')
def check_private_dir(self, dpath):
"""Return private dir's root if it's a private dir."""
for i in self.private_dirs_to_check:
if dpath.startswith(join('debian', self.package, i)):
return '/' + i
@staticmethod
def rename_ext(fpath, interpreter, current_pub_version=None):
"""Add multiarch triplet, etc. Return new name.
This method is invoked for all .so files in public or private directories.
"""
# current_pub_version - version parsed from dist-packages (True if unversioned)
# i.e. if it's not None - it's a public dist-packages directory
path, fname = fpath.rsplit('/', 1)
if current_pub_version is not None and islink(fpath):
# replace symlinks with extensions in dist-packages directory
dstfpath = fpath
links = set()
while islink(dstfpath):
links.add(dstfpath)
dstfpath = join(path, os.readlink(dstfpath))
if exists(dstfpath) and '.so.' in split(dstfpath)[-1]:
# rename .so.$FOO symlinks, remove other ones
for lpath in links:
log.info('removing symlink: %s', lpath)
os.remove(lpath)
log.info('renaming %s to %s', dstfpath, fname)
os.rename(dstfpath, fpath)
if MULTIARCH_DIR_TPL.match(fpath):
# ignore /lib/i386-linux-gnu/, /usr/lib/x86_64-kfreebsd-gnu/, etc.
return fpath
new_fn = interpreter.check_extname(fname, current_pub_version)
if new_fn:
# TODO: what about symlinks pointing to this file
new_fpath = join(path, new_fn)
if exists(new_fpath):
log.warning('destination file exist, '
'cannot rename %s to %s', fname, new_fn)
else:
log.info('renaming %s to %s', fname, new_fn)
os.rename(fpath, new_fpath)
return new_fpath
return fpath
def handle_ext(self, fpath):
"""Handle .so file, return its version if detected."""
# pylint: disable=unused-argument
return None
def is_bin_dir(self, dpath):
"""Check if dir is one from PATH ones."""
# dname = debian/packagename/usr/games
spath = dpath.strip('/').split('/', 4)
if len(spath) > 4:
return False # assume bin directories don't have subdirectories
if dpath.endswith(('/sbin', '/bin', '/usr/games')):
# /(s)bin or /usr/(s)bin or /usr/games
return True
def handle_bin_dir(self, dpath, file_names):
if self.options.no_shebang_rewrite or self.options.ignore_shebangs:
return
for fn in file_names:
fpath = join(dpath, fn)
if fix_shebang(fpath, self.options.shebang):
try:
res = Interpreter.from_file(fpath)
except Exception as e:
log.debug('cannot parse shebang %s: %s', fpath, e)
else:
self.result['shebangs'].add(res)
def is_egg_dir(self, dname):
"""Check if given directory contains egg-info."""
return dname.endswith('.egg-info')
def handle_egg_dir(self, dpath, file_names):
path, dname = dpath.rsplit('/', 1)
if self.is_dbg_package and self.options.clean_dbg_pkg:
rmtree(dpath)
return
clean_name = clean_egg_name(dname)
if clean_name != dname:
if exists(join(path, clean_name)):
log.info('removing %s (%s is already available)', dname, clean_name)
rmtree(dpath)
return
else:
log.info('renaming %s to %s', dname, clean_name)
os.rename(dpath, join(path, clean_name))
dname = clean_name
dpath = join(path, dname)
if file_names:
if 'requires.txt' in file_names:
self.result['requires.txt'].add(join(dpath, 'requires.txt'))
if 'namespace_packages.txt' in file_names:
self.result['nsp.txt'].add(join(dpath, 'namespace_packages.txt'))
if 'PKG-INFO' in file_names:
self.result['egg-info'].add(join(dpath, 'PKG-INFO'))
if 'SOURCES.txt' in file_names:
os.remove(join(dpath, 'SOURCES.txt'))
file_names.remove('SOURCES.txt')
def is_egg_file(self, fpath):
"""Check if given file contains egg-info."""
return fpath.endswith('.egg-info')
def handle_egg_file(self, fpath):
root, name = fpath.rsplit('/', 1)
clean_name = clean_egg_name(name)
if clean_name != name:
if exists(join(root, clean_name)):
log.info('removing %s (%s is already available)',
name, clean_name)
os.remove(fpath)
else:
log.info('renaming %s to %s', name, clean_name)
os.rename(fpath, join(root, clean_name))
self.result['egg-info'].add(join(root, clean_name))
def is_dist_dir(self, dname):
"""Check if given directory contains dist-info."""
return dname.endswith('.dist-info')
def handle_dist_dir(self, dpath, file_names):
if self.is_dbg_package and self.options.clean_dbg_pkg:
rmtree(dpath)
return
if file_names:
write_INSTALLER(dpath)
remove_RECORD(dpath)
if 'METADATA' in file_names:
self.result['dist-info'].add(join(dpath, 'METADATA'))
def cleanup(self):
if self.is_dbg_package and self.options.clean_dbg_pkg:
# remove empty directories in -dbg packages
proot = self.proot + '/usr/lib'
for root, _, file_names in os.walk(proot, topdown=False):
if '-packages/' in root and not file_names:
try:
os.removedirs(root)
except Exception:
pass
|