| 1 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 |
|
| 5 |
import bisect |
| 6 |
import codecs |
| 7 |
import errno |
| 8 |
import inspect |
| 9 |
import os |
| 10 |
import platform |
| 11 |
import shutil |
| 12 |
import stat |
| 13 |
import subprocess |
| 14 |
import uuid |
| 15 |
from collections import OrderedDict |
| 16 |
from io import BytesIO, StringIO |
| 17 |
from itertools import chain, takewhile |
| 18 |
from tarfile import TarFile, TarInfo |
| 19 |
from tempfile import NamedTemporaryFile, mkstemp |
| 20 |
|
| 21 |
from jsmin import JavascriptMinify |
| 22 |
|
| 23 |
import mozbuild.makeutil as makeutil |
| 24 |
import mozpack.path as mozpath |
| 25 |
from mozbuild.preprocessor import Preprocessor |
| 26 |
from mozbuild.util import FileAvoidWrite, ensure_unicode, memoize |
| 27 |
from mozpack.chrome.manifest import ManifestEntry, ManifestInterfaces |
| 28 |
from mozpack.errors import ErrorMessage, errors |
| 29 |
from mozpack.executables import elfhack, is_executable, may_elfhack, may_strip, strip |
| 30 |
from mozpack.mozjar import JarReader |
| 31 |
|
| 32 |
try: |
| 33 |
import hglib |
| 34 |
except ImportError: |
| 35 |
hglib = None |
| 36 |
|
| 37 |
|
| 38 |
# For clean builds, copying files on win32 using CopyFile through ctypes is |
| 39 |
# ~2x as fast as using shutil.copyfile. |
| 40 |
if platform.system() != "Windows": |
| 41 |
_copyfile = shutil.copyfile |
| 42 |
else: |
| 43 |
import ctypes |
| 44 |
|
| 45 |
_kernel32 = ctypes.windll.kernel32 |
| 46 |
_CopyFileA = _kernel32.CopyFileA |
| 47 |
_CopyFileW = _kernel32.CopyFileW |
| 48 |
|
| 49 |
def _copyfile(src, dest): |
| 50 |
# False indicates `dest` should be overwritten if it exists already. |
| 51 |
if isinstance(src, str) and isinstance(dest, str): |
| 52 |
_CopyFileW(src, dest, False) |
| 53 |
elif isinstance(src, str) and isinstance(dest, str): |
| 54 |
_CopyFileA(src, dest, False) |
| 55 |
else: |
| 56 |
raise TypeError("mismatched path types!") |
| 57 |
|
| 58 |
|
| 59 |
# Helper function; ensures we always open files with the correct encoding when |
| 60 |
# opening them in text mode. |
| 61 |
def _open(path, mode="r"): |
| 62 |
if "b" not in mode: |
| 63 |
return open(path, mode, encoding="utf-8") |
| 64 |
return open(path, mode) |
| 65 |
|
| 66 |
|
| 67 |
class Dest: |
| 68 |
""" |
| 69 |
Helper interface for BaseFile.copy. The interface works as follows: |
| 70 |
- read() and write() can be used to sequentially read/write from the underlying file. |
| 71 |
- a call to read() after a write() will re-open the underlying file and read from it. |
| 72 |
- a call to write() after a read() will re-open the underlying file, emptying it, and write to it. |
| 73 |
""" |
| 74 |
|
| 75 |
def __init__(self, path): |
| 76 |
self.file = None |
| 77 |
self.mode = None |
| 78 |
self.path = ensure_unicode(path) |
| 79 |
|
| 80 |
@property |
| 81 |
def name(self): |
| 82 |
return self.path |
| 83 |
|
| 84 |
def read(self, length=-1): |
| 85 |
if self.mode != "r": |
| 86 |
self.file = _open(self.path, mode="rb") |
| 87 |
self.mode = "r" |
| 88 |
return self.file.read(length) |
| 89 |
|
| 90 |
def write(self, data): |
| 91 |
if self.mode != "w": |
| 92 |
self.file = _open(self.path, mode="wb") |
| 93 |
self.mode = "w" |
| 94 |
if isinstance(data, str): |
| 95 |
data = data.encode() |
| 96 |
return self.file.write(data) |
| 97 |
|
| 98 |
def exists(self): |
| 99 |
return os.path.exists(self.path) |
| 100 |
|
| 101 |
def close(self): |
| 102 |
if self.mode: |
| 103 |
self.mode = None |
| 104 |
self.file.close() |
| 105 |
self.file = None |
| 106 |
|
| 107 |
|
| 108 |
class BaseFile: |
| 109 |
""" |
| 110 |
Base interface and helper for file copying. Derived class may implement |
| 111 |
their own copy function, or rely on BaseFile.copy using the open() member |
| 112 |
function and/or the path property. |
| 113 |
""" |
| 114 |
|
| 115 |
@staticmethod |
| 116 |
def is_older(first, second): |
| 117 |
""" |
| 118 |
Compares the modification time of two files, and returns whether the |
| 119 |
``first`` file is older than the ``second`` file. |
| 120 |
""" |
| 121 |
# os.path.getmtime returns a result in seconds with precision up to |
| 122 |
# the microsecond. But microsecond is too precise because |
| 123 |
# shutil.copystat only copies milliseconds, and seconds is not |
| 124 |
# enough precision. |
| 125 |
return int(os.path.getmtime(first) * 1000) <= int( |
| 126 |
os.path.getmtime(second) * 1000 |
| 127 |
) |
| 128 |
|
| 129 |
@staticmethod |
| 130 |
def any_newer(dest, inputs): |
| 131 |
""" |
| 132 |
Compares the modification time of ``dest`` to multiple input files, and |
| 133 |
returns whether any of the ``inputs`` is newer (has a later mtime) than |
| 134 |
``dest``. |
| 135 |
""" |
| 136 |
# os.path.getmtime returns a result in seconds with precision up to |
| 137 |
# the microsecond. But microsecond is too precise because |
| 138 |
# shutil.copystat only copies milliseconds, and seconds is not |
| 139 |
# enough precision. |
| 140 |
dest_mtime = int(os.path.getmtime(dest) * 1000) |
| 141 |
for input in inputs: |
| 142 |
try: |
| 143 |
src_mtime = int(os.path.getmtime(input) * 1000) |
| 144 |
except OSError as e: |
| 145 |
if e.errno == errno.ENOENT: |
| 146 |
# If an input file was removed, we should update. |
| 147 |
return True |
| 148 |
raise |
| 149 |
if dest_mtime < src_mtime: |
| 150 |
return True |
| 151 |
return False |
| 152 |
|
| 153 |
@staticmethod |
| 154 |
def normalize_mode(mode): |
| 155 |
# Normalize file mode: |
| 156 |
# - keep file type (e.g. S_IFREG) |
| 157 |
ret = stat.S_IFMT(mode) |
| 158 |
# - expand user read and execute permissions to everyone |
| 159 |
if mode & 0o0400: |
| 160 |
ret |= 0o0444 |
| 161 |
if mode & 0o0100: |
| 162 |
ret |= 0o0111 |
| 163 |
# - keep user write permissions |
| 164 |
if mode & 0o0200: |
| 165 |
ret |= 0o0200 |
| 166 |
# - leave away sticky bit, setuid, setgid |
| 167 |
return ret |
| 168 |
|
| 169 |
def copy(self, dest, skip_if_older=True): |
| 170 |
""" |
| 171 |
Copy the BaseFile content to the destination given as a string or a |
| 172 |
Dest instance. Avoids replacing existing files if the BaseFile content |
| 173 |
matches that of the destination, or in case of plain files, if the |
| 174 |
destination is newer than the original file. This latter behaviour is |
| 175 |
disabled when skip_if_older is False. |
| 176 |
Returns whether a copy was actually performed (True) or not (False). |
| 177 |
""" |
| 178 |
if isinstance(dest, str): |
| 179 |
dest = Dest(dest) |
| 180 |
else: |
| 181 |
assert isinstance(dest, Dest) |
| 182 |
|
| 183 |
can_skip_content_check = False |
| 184 |
if not dest.exists(): |
| 185 |
can_skip_content_check = True |
| 186 |
elif getattr(self, "path", None) and getattr(dest, "path", None): |
| 187 |
if skip_if_older and BaseFile.is_older(self.path, dest.path): |
| 188 |
return False |
| 189 |
elif os.path.getsize(self.path) != os.path.getsize(dest.path): |
| 190 |
can_skip_content_check = True |
| 191 |
|
| 192 |
if can_skip_content_check: |
| 193 |
if getattr(self, "path", None) and getattr(dest, "path", None): |
| 194 |
# The destination directory must exist, or CopyFile will fail. |
| 195 |
destdir = os.path.dirname(dest.path) |
| 196 |
os.makedirs(destdir, exist_ok=True) |
| 197 |
_copyfile(self.path, dest.path) |
| 198 |
shutil.copystat(self.path, dest.path) |
| 199 |
else: |
| 200 |
# Ensure the file is always created |
| 201 |
if not dest.exists(): |
| 202 |
dest.write(b"") |
| 203 |
shutil.copyfileobj(self.open(), dest) |
| 204 |
return True |
| 205 |
|
| 206 |
src = self.open() |
| 207 |
accumulated_src_content = [] |
| 208 |
while True: |
| 209 |
dest_content = dest.read(32768) |
| 210 |
src_content = src.read(32768) |
| 211 |
accumulated_src_content.append(src_content) |
| 212 |
if len(dest_content) == len(src_content) == 0: |
| 213 |
break |
| 214 |
# If the read content differs between origin and destination, |
| 215 |
# write what was read up to now, and copy the remainder. |
| 216 |
if dest_content != src_content: |
| 217 |
dest.write(b"".join(accumulated_src_content)) |
| 218 |
shutil.copyfileobj(src, dest) |
| 219 |
break |
| 220 |
if hasattr(self, "path") and hasattr(dest, "path"): |
| 221 |
shutil.copystat(self.path, dest.path) |
| 222 |
return True |
| 223 |
|
| 224 |
def open(self): |
| 225 |
""" |
| 226 |
Return a file-like object allowing to read() the content of the |
| 227 |
associated file. This is meant to be overloaded in subclasses to return |
| 228 |
a custom file-like object. |
| 229 |
""" |
| 230 |
assert self.path is not None |
| 231 |
return open(self.path, "rb") |
| 232 |
|
| 233 |
def read(self): |
| 234 |
raise NotImplementedError("BaseFile.read() not implemented. Bug 1170329.") |
| 235 |
|
| 236 |
def size(self): |
| 237 |
"""Returns size of the entry. |
| 238 |
|
| 239 |
Derived classes are highly encouraged to override this with a more |
| 240 |
optimal implementation. |
| 241 |
""" |
| 242 |
return len(self.read()) |
| 243 |
|
| 244 |
@property |
| 245 |
def mode(self): |
| 246 |
""" |
| 247 |
Return the file's unix mode, or None if it has no meaning. |
| 248 |
""" |
| 249 |
return None |
| 250 |
|
| 251 |
def inputs(self): |
| 252 |
""" |
| 253 |
Return an iterable of the input file paths that impact this output file. |
| 254 |
""" |
| 255 |
raise NotImplementedError("BaseFile.inputs() not implemented.") |
| 256 |
|
| 257 |
|
| 258 |
class File(BaseFile): |
| 259 |
""" |
| 260 |
File class for plain files. |
| 261 |
""" |
| 262 |
|
| 263 |
def __init__(self, path): |
| 264 |
self.path = ensure_unicode(path) |
| 265 |
|
| 266 |
@property |
| 267 |
def mode(self): |
| 268 |
""" |
| 269 |
Return the file's unix mode, as returned by os.stat().st_mode. |
| 270 |
""" |
| 271 |
if platform.system() == "Windows": |
| 272 |
return None |
| 273 |
assert self.path is not None |
| 274 |
mode = os.stat(self.path).st_mode |
| 275 |
return self.normalize_mode(mode) |
| 276 |
|
| 277 |
def read(self): |
| 278 |
"""Return the contents of the file.""" |
| 279 |
with open(self.path, "rb") as fh: |
| 280 |
return fh.read() |
| 281 |
|
| 282 |
def size(self): |
| 283 |
return os.stat(self.path).st_size |
| 284 |
|
| 285 |
def inputs(self): |
| 286 |
return (self.path,) |
| 287 |
|
| 288 |
|
| 289 |
class ExecutableFile(File): |
| 290 |
""" |
| 291 |
File class for executable and library files on OS/2, OS/X and ELF systems. |
| 292 |
(see mozpack.executables.is_executable documentation). |
| 293 |
""" |
| 294 |
|
| 295 |
def __init__(self, path): |
| 296 |
File.__init__(self, path) |
| 297 |
|
| 298 |
def copy(self, dest, skip_if_older=True): |
| 299 |
real_dest = dest |
| 300 |
if not isinstance(dest, str): |
| 301 |
fd, dest = mkstemp() |
| 302 |
os.close(fd) |
| 303 |
os.remove(dest) |
| 304 |
assert isinstance(dest, str) |
| 305 |
# If File.copy didn't actually copy because dest is newer, check the |
| 306 |
# file sizes. If dest is smaller, it means it is already stripped and |
| 307 |
# elfhacked, so we can skip. |
| 308 |
if not File.copy(self, dest, skip_if_older) and os.path.getsize( |
| 309 |
self.path |
| 310 |
) > os.path.getsize(dest): |
| 311 |
return False |
| 312 |
try: |
| 313 |
if may_strip(dest): |
| 314 |
strip(dest) |
| 315 |
if may_elfhack(dest): |
| 316 |
elfhack(dest) |
| 317 |
except ErrorMessage: |
| 318 |
os.remove(dest) |
| 319 |
raise |
| 320 |
|
| 321 |
if real_dest != dest: |
| 322 |
f = File(dest) |
| 323 |
ret = f.copy(real_dest, skip_if_older) |
| 324 |
os.remove(dest) |
| 325 |
return ret |
| 326 |
return True |
| 327 |
|
| 328 |
|
| 329 |
class AbsoluteSymlinkFile(File): |
| 330 |
"""File class that is copied by symlinking (if available). |
| 331 |
|
| 332 |
This class only works if the target path is absolute. |
| 333 |
""" |
| 334 |
|
| 335 |
def __init__(self, path): |
| 336 |
if not os.path.isabs(path): |
| 337 |
raise ValueError("Symlink target not absolute: %s" % path) |
| 338 |
|
| 339 |
File.__init__(self, path) |
| 340 |
|
| 341 |
def copy(self, dest, skip_if_older=True): |
| 342 |
assert isinstance(dest, str) |
| 343 |
|
| 344 |
# The logic in this function is complicated by the fact that symlinks |
| 345 |
# aren't universally supported. So, where symlinks aren't supported, we |
| 346 |
# fall back to file copying. Keep in mind that symlink support is |
| 347 |
# per-filesystem, not per-OS. |
| 348 |
|
| 349 |
# Handle the simple case where symlinks are definitely not supported by |
| 350 |
# falling back to file copy. |
| 351 |
if not hasattr(os, "symlink"): |
| 352 |
return File.copy(self, dest, skip_if_older=skip_if_older) |
| 353 |
|
| 354 |
# Always verify the symlink target path exists. |
| 355 |
if not os.path.exists(self.path): |
| 356 |
errors.fatal("Symlink target path does not exist: %s" % self.path) |
| 357 |
|
| 358 |
st = None |
| 359 |
|
| 360 |
try: |
| 361 |
st = os.lstat(dest) |
| 362 |
except OSError as ose: |
| 363 |
if ose.errno != errno.ENOENT: |
| 364 |
raise |
| 365 |
|
| 366 |
# If the dest is a symlink pointing to us, we have nothing to do. |
| 367 |
# If it's the wrong symlink, the filesystem must support symlinks, |
| 368 |
# so we replace with a proper symlink. |
| 369 |
if st and stat.S_ISLNK(st.st_mode): |
| 370 |
link = os.readlink(dest) |
| 371 |
if link == self.path: |
| 372 |
return False |
| 373 |
|
| 374 |
os.remove(dest) |
| 375 |
os.symlink(self.path, dest) |
| 376 |
return True |
| 377 |
|
| 378 |
# If the destination doesn't exist, we try to create a symlink. If that |
| 379 |
# fails, we fall back to copy code. |
| 380 |
if not st: |
| 381 |
try: |
| 382 |
os.symlink(self.path, dest) |
| 383 |
return True |
| 384 |
except OSError: |
| 385 |
return File.copy(self, dest, skip_if_older=skip_if_older) |
| 386 |
|
| 387 |
# Now the complicated part. If the destination exists, we could be |
| 388 |
# replacing a file with a symlink. Or, the filesystem may not support |
| 389 |
# symlinks. We want to minimize I/O overhead for performance reasons, |
| 390 |
# so we keep the existing destination file around as long as possible. |
| 391 |
# A lot of the system calls would be eliminated if we cached whether |
| 392 |
# symlinks are supported. However, even if we performed a single |
| 393 |
# up-front test of whether the root of the destination directory |
| 394 |
# supports symlinks, there's no guarantee that all operations for that |
| 395 |
# dest (or source) would be on the same filesystem and would support |
| 396 |
# symlinks. |
| 397 |
# |
| 398 |
# Our strategy is to attempt to create a new symlink with a random |
| 399 |
# name. If that fails, we fall back to copy mode. If that works, we |
| 400 |
# remove the old destination and move the newly-created symlink into |
| 401 |
# its place. |
| 402 |
|
| 403 |
temp_dest = os.path.join(os.path.dirname(dest), str(uuid.uuid4())) |
| 404 |
try: |
| 405 |
os.symlink(self.path, temp_dest) |
| 406 |
# TODO Figure out exactly how symlink creation fails and only trap |
| 407 |
# that. |
| 408 |
except OSError: |
| 409 |
return File.copy(self, dest, skip_if_older=skip_if_older) |
| 410 |
|
| 411 |
# If removing the original file fails, don't forget to clean up the |
| 412 |
# temporary symlink. |
| 413 |
try: |
| 414 |
os.remove(dest) |
| 415 |
except OSError: |
| 416 |
os.remove(temp_dest) |
| 417 |
raise |
| 418 |
|
| 419 |
os.rename(temp_dest, dest) |
| 420 |
return True |
| 421 |
|
| 422 |
|
| 423 |
class HardlinkFile(File): |
| 424 |
"""File class that is copied by hard linking (if available) |
| 425 |
|
| 426 |
This is similar to the AbsoluteSymlinkFile, but with hard links. The symlink |
| 427 |
implementation requires paths to be absolute, because they are resolved at |
| 428 |
read time, which makes relative paths messy. Hard links resolve paths at |
| 429 |
link-creation time, so relative paths are fine. |
| 430 |
""" |
| 431 |
|
| 432 |
def copy(self, dest, skip_if_older=True): |
| 433 |
assert isinstance(dest, str) |
| 434 |
|
| 435 |
if not hasattr(os, "link"): |
| 436 |
return super(HardlinkFile, self).copy(dest, skip_if_older=skip_if_older) |
| 437 |
|
| 438 |
try: |
| 439 |
path_st = os.stat(self.path) |
| 440 |
except OSError as e: |
| 441 |
if e.errno == errno.ENOENT: |
| 442 |
errors.fatal("Hard link target path does not exist: %s" % self.path) |
| 443 |
else: |
| 444 |
raise |
| 445 |
|
| 446 |
st = None |
| 447 |
try: |
| 448 |
st = os.lstat(dest) |
| 449 |
except OSError as e: |
| 450 |
if e.errno != errno.ENOENT: |
| 451 |
raise |
| 452 |
|
| 453 |
if st: |
| 454 |
# The dest already points to the right place. |
| 455 |
if st.st_dev == path_st.st_dev and st.st_ino == path_st.st_ino: |
| 456 |
return False |
| 457 |
# The dest exists and it points to the wrong place |
| 458 |
os.remove(dest) |
| 459 |
|
| 460 |
# At this point, either the dest used to exist and we just deleted it, |
| 461 |
# or it never existed. We can now safely create the hard link. |
| 462 |
try: |
| 463 |
os.link(self.path, dest) |
| 464 |
except OSError: |
| 465 |
# If we can't hard link, fall back to copying |
| 466 |
return super(HardlinkFile, self).copy(dest, skip_if_older=skip_if_older) |
| 467 |
return True |
| 468 |
|
| 469 |
|
| 470 |
class ExistingFile(BaseFile): |
| 471 |
""" |
| 472 |
File class that represents a file that may exist but whose content comes |
| 473 |
from elsewhere. |
| 474 |
|
| 475 |
This purpose of this class is to account for files that are installed via |
| 476 |
external means. It is typically only used in manifests or in registries to |
| 477 |
account for files. |
| 478 |
|
| 479 |
When asked to copy, this class does nothing because nothing is known about |
| 480 |
the source file/data. |
| 481 |
|
| 482 |
Instances of this class come in two flavors: required and optional. If an |
| 483 |
existing file is required, it must exist during copy() or an error is |
| 484 |
raised. |
| 485 |
""" |
| 486 |
|
| 487 |
def __init__(self, required): |
| 488 |
self.required = required |
| 489 |
|
| 490 |
def copy(self, dest, skip_if_older=True): |
| 491 |
if isinstance(dest, str): |
| 492 |
dest = Dest(dest) |
| 493 |
else: |
| 494 |
assert isinstance(dest, Dest) |
| 495 |
|
| 496 |
if not self.required: |
| 497 |
return |
| 498 |
|
| 499 |
if not dest.exists(): |
| 500 |
errors.fatal("Required existing file doesn't exist: %s" % dest.path) |
| 501 |
|
| 502 |
def inputs(self): |
| 503 |
return () |
| 504 |
|
| 505 |
|
| 506 |
class PreprocessedFile(BaseFile): |
| 507 |
""" |
| 508 |
File class for a file that is preprocessed. PreprocessedFile.copy() runs |
| 509 |
the preprocessor on the file to create the output. |
| 510 |
""" |
| 511 |
|
| 512 |
def __init__( |
| 513 |
self, |
| 514 |
path, |
| 515 |
depfile_path, |
| 516 |
marker, |
| 517 |
defines, |
| 518 |
extra_depends=None, |
| 519 |
silence_missing_directive_warnings=False, |
| 520 |
): |
| 521 |
self.path = ensure_unicode(path) |
| 522 |
self.depfile = ensure_unicode(depfile_path) |
| 523 |
self.marker = marker |
| 524 |
self.defines = defines |
| 525 |
self.extra_depends = list(extra_depends or []) |
| 526 |
self.silence_missing_directive_warnings = silence_missing_directive_warnings |
| 527 |
|
| 528 |
def inputs(self): |
| 529 |
pp = Preprocessor(defines=self.defines, marker=self.marker) |
| 530 |
pp.setSilenceDirectiveWarnings(self.silence_missing_directive_warnings) |
| 531 |
|
| 532 |
with _open(self.path, "r") as input: |
| 533 |
with _open(os.devnull, "w") as output: |
| 534 |
pp.processFile(input=input, output=output) |
| 535 |
|
| 536 |
# This always yields at least self.path. |
| 537 |
return pp.includes |
| 538 |
|
| 539 |
def copy(self, dest, skip_if_older=True): |
| 540 |
""" |
| 541 |
Invokes the preprocessor to create the destination file. |
| 542 |
""" |
| 543 |
if isinstance(dest, str): |
| 544 |
dest = Dest(dest) |
| 545 |
else: |
| 546 |
assert isinstance(dest, Dest) |
| 547 |
|
| 548 |
# We have to account for the case where the destination exists and is a |
| 549 |
# symlink to something. Since we know the preprocessor is certainly not |
| 550 |
# going to create a symlink, we can just remove the existing one. If the |
| 551 |
# destination is not a symlink, we leave it alone, since we're going to |
| 552 |
# overwrite its contents anyway. |
| 553 |
# If symlinks aren't supported at all, we can skip this step. |
| 554 |
if hasattr(os, "symlink") and os.path.islink(dest.path): |
| 555 |
os.remove(dest.path) |
| 556 |
|
| 557 |
pp_deps = set(self.extra_depends) |
| 558 |
|
| 559 |
# If a dependency file was specified, and it exists, add any |
| 560 |
# dependencies from that file to our list. |
| 561 |
if self.depfile and os.path.exists(self.depfile): |
| 562 |
target = mozpath.normpath(dest.name) |
| 563 |
with _open(self.depfile, "rt") as fileobj: |
| 564 |
for rule in makeutil.read_dep_makefile(fileobj): |
| 565 |
if target in rule.targets(): |
| 566 |
pp_deps.update(rule.dependencies()) |
| 567 |
|
| 568 |
skip = False |
| 569 |
if dest.exists() and skip_if_older: |
| 570 |
# If a dependency file was specified, and it doesn't exist, |
| 571 |
# assume that the preprocessor needs to be rerun. That will |
| 572 |
# regenerate the dependency file. |
| 573 |
if self.depfile and not os.path.exists(self.depfile): |
| 574 |
skip = False |
| 575 |
else: |
| 576 |
skip = not BaseFile.any_newer(dest.path, pp_deps) |
| 577 |
|
| 578 |
if skip: |
| 579 |
return False |
| 580 |
|
| 581 |
deps_out = None |
| 582 |
if self.depfile: |
| 583 |
deps_out = FileAvoidWrite(self.depfile) |
| 584 |
pp = Preprocessor(defines=self.defines, marker=self.marker) |
| 585 |
pp.setSilenceDirectiveWarnings(self.silence_missing_directive_warnings) |
| 586 |
|
| 587 |
with _open(self.path, "r") as input: |
| 588 |
pp.processFile(input=input, output=dest, depfile=deps_out) |
| 589 |
|
| 590 |
dest.close() |
| 591 |
if self.depfile: |
| 592 |
deps_out.close() |
| 593 |
|
| 594 |
return True |
| 595 |
|
| 596 |
|
| 597 |
class GeneratedFile(BaseFile): |
| 598 |
""" |
| 599 |
File class for content with no previous existence on the filesystem. |
| 600 |
""" |
| 601 |
|
| 602 |
def __init__(self, content): |
| 603 |
self._content = content |
| 604 |
|
| 605 |
@property |
| 606 |
def content(self): |
| 607 |
if inspect.isfunction(self._content): |
| 608 |
self._content = self._content() |
| 609 |
if isinstance(self._content, str): |
| 610 |
return self._content.encode() |
| 611 |
return self._content |
| 612 |
|
| 613 |
@content.setter |
| 614 |
def content(self, content): |
| 615 |
self._content = content |
| 616 |
|
| 617 |
def open(self): |
| 618 |
return BytesIO(self.content) |
| 619 |
|
| 620 |
def read(self): |
| 621 |
return self.content |
| 622 |
|
| 623 |
def size(self): |
| 624 |
return len(self.content) |
| 625 |
|
| 626 |
def inputs(self): |
| 627 |
return () |
| 628 |
|
| 629 |
|
| 630 |
class DeflatedFile(BaseFile): |
| 631 |
""" |
| 632 |
File class for members of a jar archive. DeflatedFile.copy() effectively |
| 633 |
extracts the file from the jar archive. |
| 634 |
""" |
| 635 |
|
| 636 |
def __init__(self, file): |
| 637 |
from mozpack.mozjar import JarFileReader |
| 638 |
|
| 639 |
assert isinstance(file, JarFileReader) |
| 640 |
self.file = file |
| 641 |
|
| 642 |
def open(self): |
| 643 |
self.file.seek(0) |
| 644 |
return self.file |
| 645 |
|
| 646 |
|
| 647 |
class ExtractedTarFile(GeneratedFile): |
| 648 |
""" |
| 649 |
File class for members of a tar archive. Contents of the underlying file |
| 650 |
are extracted immediately and stored in memory. |
| 651 |
""" |
| 652 |
|
| 653 |
def __init__(self, tar, info): |
| 654 |
assert isinstance(info, TarInfo) |
| 655 |
assert isinstance(tar, TarFile) |
| 656 |
GeneratedFile.__init__(self, tar.extractfile(info).read()) |
| 657 |
self._unix_mode = self.normalize_mode(info.mode) |
| 658 |
|
| 659 |
@property |
| 660 |
def mode(self): |
| 661 |
return self._unix_mode |
| 662 |
|
| 663 |
def read(self): |
| 664 |
return self.content |
| 665 |
|
| 666 |
|
| 667 |
class ManifestFile(BaseFile): |
| 668 |
""" |
| 669 |
File class for a manifest file. It takes individual manifest entries (using |
| 670 |
the add() and remove() member functions), and adjusts them to be relative |
| 671 |
to the base path for the manifest, given at creation. |
| 672 |
Example: |
| 673 |
There is a manifest entry "content foobar foobar/content/" relative |
| 674 |
to "foobar/chrome". When packaging, the entry will be stored in |
| 675 |
jar:foobar/omni.ja!/chrome/chrome.manifest, which means the entry |
| 676 |
will have to be relative to "chrome" instead of "foobar/chrome". This |
| 677 |
doesn't really matter when serializing the entry, since this base path |
| 678 |
is not written out, but it matters when moving the entry at the same |
| 679 |
time, e.g. to jar:foobar/omni.ja!/chrome.manifest, which we don't do |
| 680 |
currently but could in the future. |
| 681 |
""" |
| 682 |
|
| 683 |
def __init__(self, base, entries=None): |
| 684 |
self._base = base |
| 685 |
self._entries = [] |
| 686 |
self._interfaces = [] |
| 687 |
for e in entries or []: |
| 688 |
self.add(e) |
| 689 |
|
| 690 |
def add(self, entry): |
| 691 |
""" |
| 692 |
Add the given entry to the manifest. Entries are rebased at open() time |
| 693 |
instead of add() time so that they can be more easily remove()d. |
| 694 |
""" |
| 695 |
assert isinstance(entry, ManifestEntry) |
| 696 |
if isinstance(entry, ManifestInterfaces): |
| 697 |
self._interfaces.append(entry) |
| 698 |
else: |
| 699 |
self._entries.append(entry) |
| 700 |
|
| 701 |
def remove(self, entry): |
| 702 |
""" |
| 703 |
Remove the given entry from the manifest. |
| 704 |
""" |
| 705 |
assert isinstance(entry, ManifestEntry) |
| 706 |
if isinstance(entry, ManifestInterfaces): |
| 707 |
self._interfaces.remove(entry) |
| 708 |
else: |
| 709 |
self._entries.remove(entry) |
| 710 |
|
| 711 |
def open(self): |
| 712 |
""" |
| 713 |
Return a file-like object allowing to read() the serialized content of |
| 714 |
the manifest. |
| 715 |
""" |
| 716 |
content = "".join( |
| 717 |
"%s\n" % e.rebase(self._base) |
| 718 |
for e in chain(self._entries, self._interfaces) |
| 719 |
) |
| 720 |
return BytesIO(content.encode()) |
| 721 |
|
| 722 |
def __iter__(self): |
| 723 |
""" |
| 724 |
Iterate over entries in the manifest file. |
| 725 |
""" |
| 726 |
return chain(self._entries, self._interfaces) |
| 727 |
|
| 728 |
def isempty(self): |
| 729 |
""" |
| 730 |
Return whether there are manifest entries to write |
| 731 |
""" |
| 732 |
return len(self._entries) + len(self._interfaces) == 0 |
| 733 |
|
| 734 |
|
| 735 |
class MinifiedCommentStripped(BaseFile): |
| 736 |
""" |
| 737 |
File class for content minified by stripping comments. This wraps around a |
| 738 |
BaseFile instance, and removes lines starting with a # from its content. |
| 739 |
""" |
| 740 |
|
| 741 |
def __init__(self, file): |
| 742 |
assert isinstance(file, BaseFile) |
| 743 |
self._file = file |
| 744 |
|
| 745 |
def open(self): |
| 746 |
""" |
| 747 |
Return a file-like object allowing to read() the minified content of |
| 748 |
the underlying file. |
| 749 |
""" |
| 750 |
content = "".join( |
| 751 |
l |
| 752 |
for l in [s.decode() for s in self._file.open().readlines()] |
| 753 |
if not l.startswith("#") |
| 754 |
) |
| 755 |
return BytesIO(content.encode()) |
| 756 |
|
| 757 |
|
| 758 |
class MinifiedJavaScript(BaseFile): |
| 759 |
""" |
| 760 |
File class for minifying JavaScript files. |
| 761 |
""" |
| 762 |
|
| 763 |
def __init__(self, file, verify_command=None): |
| 764 |
assert isinstance(file, BaseFile) |
| 765 |
self._file = file |
| 766 |
self._verify_command = verify_command |
| 767 |
|
| 768 |
def open(self): |
| 769 |
output = StringIO() |
| 770 |
minify = JavascriptMinify( |
| 771 |
codecs.getreader("utf-8")(self._file.open()), output, quote_chars="'\"`" |
| 772 |
) |
| 773 |
minify.minify() |
| 774 |
output.seek(0) |
| 775 |
output_source = output.getvalue().encode() |
| 776 |
output = BytesIO(output_source) |
| 777 |
|
| 778 |
if not self._verify_command: |
| 779 |
return output |
| 780 |
|
| 781 |
input_source = self._file.open().read() |
| 782 |
|
| 783 |
with NamedTemporaryFile("wb+") as fh1, NamedTemporaryFile("wb+") as fh2: |
| 784 |
fh1.write(input_source) |
| 785 |
fh2.write(output_source) |
| 786 |
fh1.flush() |
| 787 |
fh2.flush() |
| 788 |
|
| 789 |
try: |
| 790 |
args = list(self._verify_command) |
| 791 |
args.extend([fh1.name, fh2.name]) |
| 792 |
subprocess.check_output( |
| 793 |
args, stderr=subprocess.STDOUT, universal_newlines=True |
| 794 |
) |
| 795 |
except subprocess.CalledProcessError as e: |
| 796 |
errors.warn( |
| 797 |
"JS minification verification failed for %s:" |
| 798 |
% (getattr(self._file, "path", "<unknown>")) |
| 799 |
) |
| 800 |
# Prefix each line with "Warning:" so mozharness doesn't |
| 801 |
# think these error messages are real errors. |
| 802 |
for line in e.output.splitlines(): |
| 803 |
errors.warn(line) |
| 804 |
|
| 805 |
return self._file.open() |
| 806 |
|
| 807 |
return output |
| 808 |
|
| 809 |
|
| 810 |
class BaseFinder: |
| 811 |
def __init__( |
| 812 |
self, base, minify=False, minify_js=False, minify_js_verify_command=None |
| 813 |
): |
| 814 |
""" |
| 815 |
Initializes the instance with a reference base directory. |
| 816 |
|
| 817 |
The optional minify argument specifies whether minification of code |
| 818 |
should occur. minify_js is an additional option to control minification |
| 819 |
of JavaScript. It requires minify to be True. |
| 820 |
|
| 821 |
minify_js_verify_command can be used to optionally verify the results |
| 822 |
of JavaScript minification. If defined, it is expected to be an iterable |
| 823 |
that will constitute the first arguments to a called process which will |
| 824 |
receive the filenames of the original and minified JavaScript files. |
| 825 |
The invoked process can then verify the results. If minification is |
| 826 |
rejected, the process exits with a non-0 exit code and the original |
| 827 |
JavaScript source is used. An example value for this argument is |
| 828 |
('/path/to/js', '/path/to/verify/script.js'). |
| 829 |
""" |
| 830 |
if minify_js and not minify: |
| 831 |
raise ValueError("minify_js requires minify.") |
| 832 |
|
| 833 |
self.base = mozpath.normsep(base) |
| 834 |
self._minify = minify |
| 835 |
self._minify_js = minify_js |
| 836 |
self._minify_js_verify_command = minify_js_verify_command |
| 837 |
|
| 838 |
def find(self, pattern): |
| 839 |
""" |
| 840 |
Yield path, BaseFile_instance pairs for all files under the base |
| 841 |
directory and its subdirectories that match the given pattern. See the |
| 842 |
mozpack.path.match documentation for a description of the handled |
| 843 |
patterns. |
| 844 |
""" |
| 845 |
while pattern.startswith("/"): |
| 846 |
pattern = pattern[1:] |
| 847 |
for p, f in self._find(pattern): |
| 848 |
yield p, self._minify_file(p, f) |
| 849 |
|
| 850 |
def get(self, path): |
| 851 |
"""Obtain a single file. |
| 852 |
|
| 853 |
Where ``find`` is tailored towards matching multiple files, this method |
| 854 |
is used for retrieving a single file. Use this method when performance |
| 855 |
is critical. |
| 856 |
|
| 857 |
Returns a ``BaseFile`` if at most one file exists or ``None`` otherwise. |
| 858 |
""" |
| 859 |
files = list(self.find(path)) |
| 860 |
if len(files) != 1: |
| 861 |
return None |
| 862 |
return files[0][1] |
| 863 |
|
| 864 |
def __iter__(self): |
| 865 |
""" |
| 866 |
Iterates over all files under the base directory (excluding files |
| 867 |
starting with a '.' and files at any level under a directory starting |
| 868 |
with a '.'). |
| 869 |
for path, file in finder: |
| 870 |
... |
| 871 |
""" |
| 872 |
return self.find("") |
| 873 |
|
| 874 |
def __contains__(self, pattern): |
| 875 |
raise RuntimeError( |
| 876 |
"'in' operator forbidden for %s. Use contains()." % self.__class__.__name__ |
| 877 |
) |
| 878 |
|
| 879 |
def contains(self, pattern): |
| 880 |
""" |
| 881 |
Return whether some files under the base directory match the given |
| 882 |
pattern. See the mozpack.path.match documentation for a description of |
| 883 |
the handled patterns. |
| 884 |
""" |
| 885 |
return any(self.find(pattern)) |
| 886 |
|
| 887 |
def _minify_file(self, path, file): |
| 888 |
""" |
| 889 |
Return an appropriate MinifiedSomething wrapper for the given BaseFile |
| 890 |
instance (file), according to the file type (determined by the given |
| 891 |
path), if the FileFinder was created with minification enabled. |
| 892 |
Otherwise, just return the given BaseFile instance. |
| 893 |
""" |
| 894 |
if not self._minify or isinstance(file, ExecutableFile): |
| 895 |
return file |
| 896 |
|
| 897 |
if path.endswith((".ftl", ".properties")): |
| 898 |
return MinifiedCommentStripped(file) |
| 899 |
|
| 900 |
if self._minify_js and path.endswith((".js", ".jsm", ".mjs")): |
| 901 |
return MinifiedJavaScript(file, self._minify_js_verify_command) |
| 902 |
|
| 903 |
return file |
| 904 |
|
| 905 |
def _find_helper(self, pattern, files, file_getter): |
| 906 |
"""Generic implementation of _find. |
| 907 |
|
| 908 |
A few *Finder implementations share logic for returning results. |
| 909 |
This function implements the custom logic. |
| 910 |
|
| 911 |
The ``file_getter`` argument is a callable that receives a path |
| 912 |
that is known to exist. The callable should return a ``BaseFile`` |
| 913 |
instance. |
| 914 |
""" |
| 915 |
if "*" in pattern: |
| 916 |
for p in files: |
| 917 |
if mozpath.match(p, pattern): |
| 918 |
yield p, file_getter(p) |
| 919 |
elif pattern == "": |
| 920 |
for p in files: |
| 921 |
yield p, file_getter(p) |
| 922 |
elif pattern in files: |
| 923 |
yield pattern, file_getter(pattern) |
| 924 |
else: |
| 925 |
for p in files: |
| 926 |
if mozpath.basedir(p, [pattern]) == pattern: |
| 927 |
yield p, file_getter(p) |
| 928 |
|
| 929 |
|
| 930 |
class FileFinder(BaseFinder): |
| 931 |
""" |
| 932 |
Helper to get appropriate BaseFile instances from the file system. |
| 933 |
""" |
| 934 |
|
| 935 |
def __init__( |
| 936 |
self, |
| 937 |
base, |
| 938 |
find_executables=False, |
| 939 |
ignore=(), |
| 940 |
ignore_broken_symlinks=False, |
| 941 |
find_dotfiles=False, |
| 942 |
**kargs |
| 943 |
): |
| 944 |
""" |
| 945 |
Create a FileFinder for files under the given base directory. |
| 946 |
|
| 947 |
The find_executables argument determines whether the finder needs to |
| 948 |
try to guess whether files are executables. Disabling this guessing |
| 949 |
when not necessary can speed up the finder significantly. |
| 950 |
|
| 951 |
``ignore`` accepts an iterable of patterns to ignore. Entries are |
| 952 |
strings that match paths relative to ``base`` using |
| 953 |
``mozpath.match()``. This means if an entry corresponds |
| 954 |
to a directory, all files under that directory will be ignored. If |
| 955 |
an entry corresponds to a file, that particular file will be ignored. |
| 956 |
``ignore_broken_symlinks`` is passed by the packager to work around an |
| 957 |
issue with the build system not cleaning up stale files in some common |
| 958 |
cases. See bug 1297381. |
| 959 |
""" |
| 960 |
BaseFinder.__init__(self, base, **kargs) |
| 961 |
self.find_dotfiles = find_dotfiles |
| 962 |
self.find_executables = find_executables |
| 963 |
self.ignore = tuple(mozpath.normsep(path) for path in ignore) |
| 964 |
self.ignore_broken_symlinks = ignore_broken_symlinks |
| 965 |
|
| 966 |
def _find(self, pattern): |
| 967 |
""" |
| 968 |
Actual implementation of FileFinder.find(), dispatching to specialized |
| 969 |
member functions depending on what kind of pattern was given. |
| 970 |
Note all files with a name starting with a '.' are ignored when |
| 971 |
scanning directories, but are not ignored when explicitely requested. |
| 972 |
""" |
| 973 |
if "*" in pattern: |
| 974 |
return self._find_glob("", mozpath.split(pattern)) |
| 975 |
elif os.path.isdir(os.path.join(self.base, pattern)): |
| 976 |
return self._find_dir(pattern) |
| 977 |
else: |
| 978 |
f = self.get(pattern) |
| 979 |
return ((pattern, f),) if f else () |
| 980 |
|
| 981 |
def _find_dir(self, path): |
| 982 |
""" |
| 983 |
Actual implementation of FileFinder.find() when the given pattern |
| 984 |
corresponds to an existing directory under the base directory. |
| 985 |
Ignores file names starting with a '.' under the given path. If the |
| 986 |
path itself has leafs starting with a '.', they are not ignored. |
| 987 |
""" |
| 988 |
for p in self.ignore: |
| 989 |
if mozpath.match(path, p): |
| 990 |
return |
| 991 |
|
| 992 |
# The sorted makes the output idempotent. Otherwise, we are |
| 993 |
# likely dependent on filesystem implementation details, such as |
| 994 |
# inode ordering. |
| 995 |
for p in sorted(os.listdir(os.path.join(self.base, path))): |
| 996 |
if p.startswith("."): |
| 997 |
if p in (".", ".."): |
| 998 |
continue |
| 999 |
if not self.find_dotfiles: |
| 1000 |
continue |
| 1001 |
for p_, f in self._find(mozpath.join(path, p)): |
| 1002 |
yield p_, f |
| 1003 |
|
| 1004 |
def get(self, path): |
| 1005 |
srcpath = os.path.join(self.base, path) |
| 1006 |
if not os.path.lexists(srcpath): |
| 1007 |
return None |
| 1008 |
|
| 1009 |
if self.ignore_broken_symlinks and not os.path.exists(srcpath): |
| 1010 |
return None |
| 1011 |
|
| 1012 |
for p in self.ignore: |
| 1013 |
if mozpath.match(path, p): |
| 1014 |
return None |
| 1015 |
|
| 1016 |
if self.find_executables and is_executable(srcpath): |
| 1017 |
return ExecutableFile(srcpath) |
| 1018 |
else: |
| 1019 |
return File(srcpath) |
| 1020 |
|
| 1021 |
def _find_glob(self, base, pattern): |
| 1022 |
""" |
| 1023 |
Actual implementation of FileFinder.find() when the given pattern |
| 1024 |
contains globbing patterns ('*' or '**'). This is meant to be an |
| 1025 |
equivalent of: |
| 1026 |
for p, f in self: |
| 1027 |
if mozpath.match(p, pattern): |
| 1028 |
yield p, f |
| 1029 |
but avoids scanning the entire tree. |
| 1030 |
""" |
| 1031 |
if not pattern: |
| 1032 |
for p, f in self._find(base): |
| 1033 |
yield p, f |
| 1034 |
elif pattern[0] == "**": |
| 1035 |
for p, f in self._find(base): |
| 1036 |
if mozpath.match(p, mozpath.join(*pattern)): |
| 1037 |
yield p, f |
| 1038 |
elif "*" in pattern[0]: |
| 1039 |
if not os.path.exists(os.path.join(self.base, base)): |
| 1040 |
return |
| 1041 |
|
| 1042 |
for p in self.ignore: |
| 1043 |
if mozpath.match(base, p): |
| 1044 |
return |
| 1045 |
|
| 1046 |
# See above comment w.r.t. sorted() and idempotent behavior. |
| 1047 |
for p in sorted(os.listdir(os.path.join(self.base, base))): |
| 1048 |
if p.startswith(".") and not pattern[0].startswith("."): |
| 1049 |
continue |
| 1050 |
if mozpath.match(p, pattern[0]): |
| 1051 |
for p_, f in self._find_glob(mozpath.join(base, p), pattern[1:]): |
| 1052 |
yield p_, f |
| 1053 |
else: |
| 1054 |
for p, f in self._find_glob(mozpath.join(base, pattern[0]), pattern[1:]): |
| 1055 |
yield p, f |
| 1056 |
|
| 1057 |
|
| 1058 |
class JarFinder(BaseFinder): |
| 1059 |
""" |
| 1060 |
Helper to get appropriate DeflatedFile instances from a JarReader. |
| 1061 |
""" |
| 1062 |
|
| 1063 |
def __init__(self, base, reader, **kargs): |
| 1064 |
""" |
| 1065 |
Create a JarFinder for files in the given JarReader. The base argument |
| 1066 |
is used as an indication of the Jar file location. |
| 1067 |
""" |
| 1068 |
assert isinstance(reader, JarReader) |
| 1069 |
BaseFinder.__init__(self, base, **kargs) |
| 1070 |
self._files = OrderedDict((f.filename, f) for f in reader) |
| 1071 |
|
| 1072 |
def _find(self, pattern): |
| 1073 |
""" |
| 1074 |
Actual implementation of JarFinder.find(), dispatching to specialized |
| 1075 |
member functions depending on what kind of pattern was given. |
| 1076 |
""" |
| 1077 |
return self._find_helper( |
| 1078 |
pattern, self._files, lambda x: DeflatedFile(self._files[x]) |
| 1079 |
) |
| 1080 |
|
| 1081 |
|
| 1082 |
class TarFinder(BaseFinder): |
| 1083 |
""" |
| 1084 |
Helper to get files from a TarFile. |
| 1085 |
""" |
| 1086 |
|
| 1087 |
def __init__(self, base, tar, **kargs): |
| 1088 |
""" |
| 1089 |
Create a TarFinder for files in the given TarFile. The base argument |
| 1090 |
is used as an indication of the Tar file location. |
| 1091 |
""" |
| 1092 |
assert isinstance(tar, TarFile) |
| 1093 |
self._tar = tar |
| 1094 |
BaseFinder.__init__(self, base, **kargs) |
| 1095 |
self._files = OrderedDict((f.name, f) for f in tar if f.isfile()) |
| 1096 |
|
| 1097 |
def _find(self, pattern): |
| 1098 |
""" |
| 1099 |
Actual implementation of TarFinder.find(), dispatching to specialized |
| 1100 |
member functions depending on what kind of pattern was given. |
| 1101 |
""" |
| 1102 |
return self._find_helper( |
| 1103 |
pattern, self._files, lambda x: ExtractedTarFile(self._tar, self._files[x]) |
| 1104 |
) |
| 1105 |
|
| 1106 |
|
| 1107 |
class ComposedFinder(BaseFinder): |
| 1108 |
""" |
| 1109 |
Composes multiple File Finders in some sort of virtual file system. |
| 1110 |
|
| 1111 |
A ComposedFinder is initialized from a dictionary associating paths |
| 1112 |
to `*Finder instances.` |
| 1113 |
|
| 1114 |
Note this could be optimized to be smarter than getting all the files |
| 1115 |
in advance. |
| 1116 |
""" |
| 1117 |
|
| 1118 |
def __init__(self, finders): |
| 1119 |
# Can't import globally, because of the dependency of mozpack.copier |
| 1120 |
# on this module. |
| 1121 |
from mozpack.copier import FileRegistry |
| 1122 |
|
| 1123 |
self.files = FileRegistry() |
| 1124 |
|
| 1125 |
for base, finder in sorted(finders.items()): |
| 1126 |
if self.files.contains(base): |
| 1127 |
self.files.remove(base) |
| 1128 |
for p, f in finder.find(""): |
| 1129 |
self.files.add(mozpath.join(base, p), f) |
| 1130 |
|
| 1131 |
def find(self, pattern): |
| 1132 |
for p in self.files.match(pattern): |
| 1133 |
yield p, self.files[p] |
| 1134 |
|
| 1135 |
|
| 1136 |
class MercurialFile(BaseFile): |
| 1137 |
"""File class for holding data from Mercurial.""" |
| 1138 |
|
| 1139 |
def __init__(self, client, rev, path): |
| 1140 |
self._content = client.cat([path.encode()], rev=rev.encode()) |
| 1141 |
|
| 1142 |
def open(self): |
| 1143 |
return BytesIO(self._content) |
| 1144 |
|
| 1145 |
def read(self): |
| 1146 |
return self._content |
| 1147 |
|
| 1148 |
|
| 1149 |
class MercurialRevisionFinder(BaseFinder): |
| 1150 |
"""A finder that operates on a specific Mercurial revision.""" |
| 1151 |
|
| 1152 |
def __init__(self, repo, rev=".", recognize_repo_paths=False, **kwargs): |
| 1153 |
"""Create a finder attached to a specific revision in a repository. |
| 1154 |
|
| 1155 |
If no revision is given, open the parent of the working directory. |
| 1156 |
|
| 1157 |
``recognize_repo_paths`` will enable a mode where ``.get()`` will |
| 1158 |
recognize full paths that include the repo's path. Typically Finder |
| 1159 |
instances are "bound" to a base directory and paths are relative to |
| 1160 |
that directory. This mode changes that. When this mode is activated, |
| 1161 |
``.find()`` will not work! This mode exists to support the moz.build |
| 1162 |
reader, which uses absolute paths instead of relative paths. The reader |
| 1163 |
should eventually be rewritten to use relative paths and this hack |
| 1164 |
should be removed (TODO bug 1171069). |
| 1165 |
""" |
| 1166 |
if not hglib: |
| 1167 |
raise Exception("hglib package not found") |
| 1168 |
|
| 1169 |
super(MercurialRevisionFinder, self).__init__(base=repo, **kwargs) |
| 1170 |
|
| 1171 |
self._root = mozpath.normpath(repo).rstrip("/") |
| 1172 |
self._recognize_repo_paths = recognize_repo_paths |
| 1173 |
|
| 1174 |
# We change directories here otherwise we have to deal with relative |
| 1175 |
# paths. |
| 1176 |
oldcwd = os.getcwd() |
| 1177 |
os.chdir(self._root) |
| 1178 |
try: |
| 1179 |
self._client = hglib.open(path=repo, encoding=b"utf-8") |
| 1180 |
finally: |
| 1181 |
os.chdir(oldcwd) |
| 1182 |
self._rev = rev if rev is not None else "." |
| 1183 |
self._files = OrderedDict() |
| 1184 |
|
| 1185 |
# Immediately populate the list of files in the repo since nearly every |
| 1186 |
# operation requires this list. |
| 1187 |
out = self._client.rawcommand( |
| 1188 |
[ |
| 1189 |
b"files", |
| 1190 |
b"--rev", |
| 1191 |
self._rev.encode(), |
| 1192 |
] |
| 1193 |
) |
| 1194 |
for relpath in out.splitlines(): |
| 1195 |
# Mercurial may use \ as path separator on Windows. So use |
| 1196 |
# normpath(). |
| 1197 |
self._files[mozpath.normpath(relpath).decode()] = None |
| 1198 |
|
| 1199 |
def _find(self, pattern): |
| 1200 |
if self._recognize_repo_paths: |
| 1201 |
raise NotImplementedError("cannot use find with recognize_repo_path") |
| 1202 |
|
| 1203 |
return self._find_helper(pattern, self._files, self._get) |
| 1204 |
|
| 1205 |
def get(self, path): |
| 1206 |
path = mozpath.normpath(path) |
| 1207 |
if self._recognize_repo_paths: |
| 1208 |
if not path.startswith(self._root): |
| 1209 |
raise ValueError( |
| 1210 |
"lookups in recognize_repo_paths mode must be " |
| 1211 |
"prefixed with repo path: %s" % path |
| 1212 |
) |
| 1213 |
path = path[len(self._root) + 1 :] |
| 1214 |
|
| 1215 |
try: |
| 1216 |
return self._get(path) |
| 1217 |
except KeyError: |
| 1218 |
return None |
| 1219 |
|
| 1220 |
def _get(self, path): |
| 1221 |
# We lazy populate self._files because potentially creating tens of |
| 1222 |
# thousands of MercurialFile instances for every file in the repo is |
| 1223 |
# inefficient. |
| 1224 |
f = self._files[path] |
| 1225 |
if not f: |
| 1226 |
f = MercurialFile(self._client, self._rev, path) |
| 1227 |
self._files[path] = f |
| 1228 |
|
| 1229 |
return f |
| 1230 |
|
| 1231 |
|
| 1232 |
class FileListFinder(BaseFinder): |
| 1233 |
"""Finder for a literal list of file names.""" |
| 1234 |
|
| 1235 |
def __init__(self, files): |
| 1236 |
self._files = sorted(files) |
| 1237 |
|
| 1238 |
@memoize |
| 1239 |
def _match(self, pattern): |
| 1240 |
"""Return a sorted list of all files matching the given pattern.""" |
| 1241 |
# We don't use the utility _find_helper method because it's not tuned |
| 1242 |
# for performance in the way that we would like this class to be. That's |
| 1243 |
# a possible avenue for refactoring here. |
| 1244 |
ret = [] |
| 1245 |
# We do this as an optimization to figure out where in the sorted list |
| 1246 |
# to search and where to stop searching. |
| 1247 |
components = pattern.split("/") |
| 1248 |
prefix = "/".join(takewhile(lambda s: "*" not in s, components)) |
| 1249 |
start = bisect.bisect_left(self._files, prefix) |
| 1250 |
for i in range(start, len(self._files)): |
| 1251 |
f = self._files[i] |
| 1252 |
if not f.startswith(prefix): |
| 1253 |
break |
| 1254 |
# Skip hidden files while scanning. |
| 1255 |
if "/." in f[len(prefix) :]: |
| 1256 |
continue |
| 1257 |
if mozpath.match(f, pattern): |
| 1258 |
ret.append(f) |
| 1259 |
return ret |
| 1260 |
|
| 1261 |
def find(self, pattern): |
| 1262 |
pattern = pattern.strip("/") |
| 1263 |
for path in self._match(pattern): |
| 1264 |
yield path, File(path) |