| 1 |
#!/usr/bin/env python3 |
| 2 |
"""Check the MANIFEST.in file in a Python source package for completeness. |
| 3 |
|
| 4 |
This script works by building a source distribution archive (by running |
| 5 |
setup.py sdist), then checking the file list in the archive against the |
| 6 |
file list in version control (Subversion, Git, Mercurial, Bazaar are |
| 7 |
supported). |
| 8 |
|
| 9 |
Since the first check can fail to catch missing MANIFEST.in entries when |
| 10 |
you've got the right setuptools version control system support plugins |
| 11 |
installed, the script copies all the versioned files into a temporary |
| 12 |
directory and builds the source distribution again. This also avoids issues |
| 13 |
with stale egg-info/SOURCES.txt files that may cause files not mentioned in |
| 14 |
MANIFEST.in to be included nevertheless. |
| 15 |
""" |
| 16 |
|
| 17 |
from __future__ import annotations |
| 18 |
|
| 19 |
import argparse |
| 20 |
import codecs |
| 21 |
import configparser |
| 22 |
import fnmatch |
| 23 |
import locale |
| 24 |
import os |
| 25 |
import posixpath |
| 26 |
import re |
| 27 |
import shutil |
| 28 |
import stat |
| 29 |
import subprocess |
| 30 |
import sys |
| 31 |
import tarfile |
| 32 |
import tempfile |
| 33 |
import unicodedata |
| 34 |
import zipfile |
| 35 |
from contextlib import contextmanager |
| 36 |
from types import TracebackType |
| 37 |
from typing import ( |
| 38 |
Any, |
| 39 |
Callable, |
| 40 |
Collection, |
| 41 |
Generator, |
| 42 |
Iterable, |
| 43 |
Literal, |
| 44 |
TypedDict, |
| 45 |
overload, |
| 46 |
) |
| 47 |
from xml.etree import ElementTree as ET |
| 48 |
|
| 49 |
|
| 50 |
if sys.version_info >= (3, 11): |
| 51 |
import tomllib # pragma: nocover |
| 52 |
else: |
| 53 |
import tomli as tomllib # pragma: nocover |
| 54 |
|
| 55 |
from setuptools.command.egg_info import translate_pattern |
| 56 |
|
| 57 |
|
| 58 |
# import distutils after setuptools to avoid a warning |
| 59 |
from distutils.text_file import TextFile # isort:skip |
| 60 |
|
| 61 |
|
| 62 |
__version__ = '0.52.dev0' |
| 63 |
__author__ = 'Marius Gedminas <[email protected]>' |
| 64 |
__licence__ = 'MIT' |
| 65 |
__url__ = 'https://github.com/mgedmin/check-manifest' |
| 66 |
|
| 67 |
|
| 68 |
class Failure(Exception): |
| 69 |
"""An expected failure (as opposed to a bug in this script).""" |
| 70 |
|
| 71 |
|
| 72 |
# |
| 73 |
# User interface |
| 74 |
# |
| 75 |
|
| 76 |
class UI: |
| 77 |
|
| 78 |
def __init__(self, verbosity: int = 1) -> None: |
| 79 |
self.verbosity = verbosity |
| 80 |
self._to_be_continued = False |
| 81 |
self.stdout = sys.stdout |
| 82 |
self.stderr = sys.stderr |
| 83 |
|
| 84 |
@property |
| 85 |
def quiet(self) -> bool: |
| 86 |
return self.verbosity < 1 |
| 87 |
|
| 88 |
@property |
| 89 |
def verbose(self) -> bool: |
| 90 |
return self.verbosity >= 2 |
| 91 |
|
| 92 |
def _check_tbc(self) -> None: |
| 93 |
if self._to_be_continued: |
| 94 |
print(file=self.stdout) |
| 95 |
self._to_be_continued = False |
| 96 |
|
| 97 |
def info(self, message: str) -> None: |
| 98 |
if self.quiet: |
| 99 |
return |
| 100 |
self._check_tbc() |
| 101 |
print(message, file=self.stdout) |
| 102 |
|
| 103 |
def info_begin(self, message: str) -> None: |
| 104 |
if not self.verbose: |
| 105 |
return |
| 106 |
self._check_tbc() |
| 107 |
print(message, end="", file=self.stdout) |
| 108 |
self._to_be_continued = True |
| 109 |
|
| 110 |
def info_continue(self, message: str) -> None: |
| 111 |
if not self.verbose: |
| 112 |
return |
| 113 |
print(message, end="", file=self.stdout) |
| 114 |
self._to_be_continued = True |
| 115 |
|
| 116 |
def info_end(self, message: str) -> None: |
| 117 |
if not self.verbose: |
| 118 |
return |
| 119 |
print(message, file=self.stdout) |
| 120 |
self._to_be_continued = False |
| 121 |
|
| 122 |
def error(self, message: str) -> None: |
| 123 |
self._check_tbc() |
| 124 |
print(message, file=self.stderr) |
| 125 |
|
| 126 |
def warning(self, message: str) -> None: |
| 127 |
self._check_tbc() |
| 128 |
print(message, file=self.stderr) |
| 129 |
|
| 130 |
|
| 131 |
def format_list(list_of_strings: list[str]) -> str: |
| 132 |
return "\n".join(" " + s for s in list_of_strings) |
| 133 |
|
| 134 |
|
| 135 |
def format_missing( |
| 136 |
missing_from_a: Collection[str], |
| 137 |
missing_from_b: Collection[str], |
| 138 |
name_a: str, |
| 139 |
name_b: str, |
| 140 |
) -> str: |
| 141 |
res = [] |
| 142 |
if missing_from_a: |
| 143 |
res.append("missing from %s:\n%s" |
| 144 |
% (name_a, format_list(sorted(missing_from_a)))) |
| 145 |
if missing_from_b: |
| 146 |
res.append("missing from %s:\n%s" |
| 147 |
% (name_b, format_list(sorted(missing_from_b)))) |
| 148 |
return '\n'.join(res) |
| 149 |
|
| 150 |
|
| 151 |
# |
| 152 |
# Filesystem/OS utilities |
| 153 |
# |
| 154 |
|
| 155 |
class CommandFailed(Failure): |
| 156 |
def __init__(self, command: list[str], status: int, output: str) -> None: |
| 157 |
super().__init__("%s failed (status %s):\n%s" % ( |
| 158 |
command, status, output)) |
| 159 |
|
| 160 |
|
| 161 |
@overload |
| 162 |
def run( |
| 163 |
command: list[str], |
| 164 |
*, |
| 165 |
encoding: str | None = None, |
| 166 |
decode: Literal[True] = True, |
| 167 |
cwd: str | None = None, |
| 168 |
) -> str: |
| 169 |
... |
| 170 |
|
| 171 |
|
| 172 |
@overload |
| 173 |
def run( |
| 174 |
command: list[str], |
| 175 |
*, |
| 176 |
encoding: str | None = None, |
| 177 |
decode: Literal[False], |
| 178 |
cwd: str | None = None, |
| 179 |
) -> bytes: |
| 180 |
... |
| 181 |
|
| 182 |
|
| 183 |
def run( |
| 184 |
command: list[str], |
| 185 |
*, |
| 186 |
encoding: str | None = None, |
| 187 |
decode: bool = True, |
| 188 |
cwd: str | None = None, |
| 189 |
) -> str | bytes: |
| 190 |
"""Run a command [cmd, arg1, arg2, ...]. |
| 191 |
|
| 192 |
Returns the output (stdout only). |
| 193 |
|
| 194 |
Raises CommandFailed in cases of error. |
| 195 |
""" |
| 196 |
if not encoding: |
| 197 |
encoding = locale.getpreferredencoding() |
| 198 |
try: |
| 199 |
pipe = subprocess.Popen(command, stdin=subprocess.DEVNULL, |
| 200 |
stdout=subprocess.PIPE, |
| 201 |
stderr=subprocess.PIPE, cwd=cwd) |
| 202 |
except OSError as e: |
| 203 |
raise Failure(f"could not run {command}: {e}") |
| 204 |
output, stderr = pipe.communicate() |
| 205 |
status = pipe.wait() |
| 206 |
if status != 0: |
| 207 |
raise CommandFailed(command, status, |
| 208 |
(output + stderr).decode(encoding, 'replace')) |
| 209 |
if decode: |
| 210 |
return output.decode(encoding) |
| 211 |
return output |
| 212 |
|
| 213 |
|
| 214 |
@contextmanager |
| 215 |
def cd(directory: str) -> Generator[None, None, None]: |
| 216 |
"""Change the current working directory, temporarily. |
| 217 |
|
| 218 |
Use as a context manager: with cd(d): ... |
| 219 |
""" |
| 220 |
old_dir = os.getcwd() |
| 221 |
try: |
| 222 |
os.chdir(directory) |
| 223 |
yield |
| 224 |
finally: |
| 225 |
os.chdir(old_dir) |
| 226 |
|
| 227 |
|
| 228 |
@contextmanager |
| 229 |
def mkdtemp(hint: str = '') -> Generator[str, None, None]: |
| 230 |
"""Create a temporary directory, then clean it up. |
| 231 |
|
| 232 |
Use as a context manager: with mkdtemp('-purpose'): ... |
| 233 |
""" |
| 234 |
dirname = tempfile.mkdtemp(prefix='check-manifest-', suffix=hint) |
| 235 |
try: |
| 236 |
yield dirname |
| 237 |
finally: |
| 238 |
rmtree(dirname) |
| 239 |
|
| 240 |
|
| 241 |
def chmod_plus(path: str, add_bits: int) -> None: |
| 242 |
"""Change a file's mode by adding a few bits. |
| 243 |
|
| 244 |
Like chmod +<bits> <path> in a Unix shell. |
| 245 |
""" |
| 246 |
try: |
| 247 |
os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | add_bits) |
| 248 |
except OSError: # pragma: nocover |
| 249 |
pass # well, we tried |
| 250 |
|
| 251 |
|
| 252 |
ExcInfo = tuple[type[BaseException], BaseException, TracebackType] |
| 253 |
|
| 254 |
|
| 255 |
def rmtree(path: str) -> None: |
| 256 |
"""A version of rmtree that can deal with read-only files and directories. |
| 257 |
|
| 258 |
Needed because the stock shutil.rmtree() fails with an access error |
| 259 |
when there are read-only files in the directory on Windows, or when the |
| 260 |
directory itself is read-only on Unix. |
| 261 |
""" |
| 262 |
def onerror(func: Callable[..., Any], path: str, exc_info: ExcInfo) -> None: |
| 263 |
# Did you know what on Python 3.3 on Windows os.remove() and |
| 264 |
# os.unlink() are distinct functions? |
| 265 |
if func is os.remove or func is os.unlink or func is os.rmdir: |
| 266 |
if sys.platform != 'win32': |
| 267 |
chmod_plus(os.path.dirname(path), stat.S_IWUSR | stat.S_IXUSR) |
| 268 |
chmod_plus(path, stat.S_IWUSR) |
| 269 |
func(path) |
| 270 |
else: |
| 271 |
raise |
| 272 |
shutil.rmtree(path, onerror=onerror) |
| 273 |
|
| 274 |
|
| 275 |
def copy_files(filelist: list[str], destdir: str) -> None: |
| 276 |
"""Copy a list of files to destdir, preserving directory structure. |
| 277 |
|
| 278 |
File names should be relative to the current working directory. |
| 279 |
""" |
| 280 |
for filename in filelist: |
| 281 |
destfile = os.path.join(destdir, filename) |
| 282 |
# filename should not be absolute, but let's double-check |
| 283 |
assert destfile.startswith(destdir + os.path.sep) |
| 284 |
destfiledir = os.path.dirname(destfile) |
| 285 |
if not os.path.isdir(destfiledir): |
| 286 |
os.makedirs(destfiledir) |
| 287 |
if os.path.isdir(filename): |
| 288 |
os.mkdir(destfile) |
| 289 |
else: |
| 290 |
shutil.copy2(filename, destfile) |
| 291 |
|
| 292 |
|
| 293 |
def get_one_file_in(dirname: str) -> str: |
| 294 |
"""Return the pathname of the one file in a directory. |
| 295 |
|
| 296 |
Raises if the directory has no files or more than one file. |
| 297 |
""" |
| 298 |
files = os.listdir(dirname) |
| 299 |
if len(files) > 1: |
| 300 |
raise Failure('More than one file exists in %s:\n%s' % |
| 301 |
(dirname, '\n'.join(sorted(files)))) |
| 302 |
elif not files: |
| 303 |
raise Failure('No files found in %s' % dirname) |
| 304 |
return os.path.join(dirname, files[0]) |
| 305 |
|
| 306 |
|
| 307 |
# |
| 308 |
# File lists are a fundamental data structure here. We want them to have |
| 309 |
# the following properties: |
| 310 |
# |
| 311 |
# - contain Unicode filenames (normalized to NFC on OS X) |
| 312 |
# - be sorted |
| 313 |
# - use / as the directory separator |
| 314 |
# - list only files, but not directories |
| 315 |
# |
| 316 |
# We get these file lists from various sources (zip files, tar files, version |
| 317 |
# control systems) and we have to normalize them into our common format before |
| 318 |
# comparing. |
| 319 |
# |
| 320 |
|
| 321 |
|
| 322 |
def canonical_file_list(filelist: Iterable[str]) -> list[str]: |
| 323 |
"""Return the file list convered to a canonical form. |
| 324 |
|
| 325 |
This means: |
| 326 |
|
| 327 |
- converted to Unicode normal form C, when running on Mac OS X |
| 328 |
- sorted alphabetically |
| 329 |
- use / as the directory separator |
| 330 |
- list files but not directories |
| 331 |
|
| 332 |
Caveat: since it works on file lists taken from archives and such, it |
| 333 |
doesn't know whether a particular filename refers to a file or a directory, |
| 334 |
unless it finds annother filename that is inside the first one. In other |
| 335 |
words, canonical_file_list() will not remove the names of empty directories |
| 336 |
if those appear in the initial file list. |
| 337 |
""" |
| 338 |
names = set(normalize_names(filelist)) |
| 339 |
for name in list(names): |
| 340 |
while name: |
| 341 |
name = posixpath.dirname(name) |
| 342 |
names.discard(name) |
| 343 |
return sorted(names) |
| 344 |
|
| 345 |
|
| 346 |
def get_sdist_file_list(sdist_filename: str, ignore: IgnoreList) -> list[str]: |
| 347 |
"""Return the list of interesting files in a source distribution. |
| 348 |
|
| 349 |
Removes extra generated files like PKG-INFO and *.egg-info that are usually |
| 350 |
present only in the sdist, but not in the VCS. |
| 351 |
|
| 352 |
Supports .tar.gz and .zip sdists. |
| 353 |
""" |
| 354 |
return strip_sdist_extras( |
| 355 |
ignore, |
| 356 |
strip_toplevel_name(get_archive_file_list(sdist_filename))) |
| 357 |
|
| 358 |
|
| 359 |
def get_archive_file_list(archive_filename: str) -> list[str]: |
| 360 |
"""Return the list of files in an archive. |
| 361 |
|
| 362 |
Supports .tar.gz and .zip. |
| 363 |
""" |
| 364 |
filelist: Iterable[str] |
| 365 |
if archive_filename.endswith('.zip'): |
| 366 |
with zipfile.ZipFile(archive_filename) as zf: |
| 367 |
filelist = zf.namelist() |
| 368 |
elif archive_filename.endswith(('.tar.gz', '.tar.bz2', '.tar')): |
| 369 |
with tarfile.open(archive_filename) as tf: |
| 370 |
# XXX: is unicodify() necessary now that Py2 is no longer supported? |
| 371 |
filelist = map(unicodify, tf.getnames()) |
| 372 |
else: |
| 373 |
raise Failure('Unrecognized archive type: %s' |
| 374 |
% os.path.basename(archive_filename)) |
| 375 |
return canonical_file_list(filelist) |
| 376 |
|
| 377 |
|
| 378 |
def unicodify(filename: str | bytes) -> str: |
| 379 |
"""Make sure filename is Unicode. |
| 380 |
|
| 381 |
Because the tarfile module on Python 2 doesn't return Unicode. |
| 382 |
""" |
| 383 |
if isinstance(filename, bytes): |
| 384 |
# XXX: Ah, but is it right to use the locale encoding here, or should I |
| 385 |
# use sys.getfilesystemencoding()? A good question! |
| 386 |
return filename.decode(locale.getpreferredencoding()) |
| 387 |
else: |
| 388 |
return filename |
| 389 |
|
| 390 |
|
| 391 |
def strip_toplevel_name(filelist: list[str]) -> list[str]: |
| 392 |
"""Strip toplevel name from a file list. |
| 393 |
|
| 394 |
>>> strip_toplevel_name(['a', 'a/b', 'a/c', 'a/c/d']) |
| 395 |
['b', 'c', 'c/d'] |
| 396 |
|
| 397 |
>>> strip_toplevel_name(['a', 'a/', 'a/b', 'a/c', 'a/c/d']) |
| 398 |
['b', 'c', 'c/d'] |
| 399 |
|
| 400 |
>>> strip_toplevel_name(['a/b', 'a/c', 'a/c/d']) |
| 401 |
['b', 'c', 'c/d'] |
| 402 |
|
| 403 |
""" |
| 404 |
if not filelist: |
| 405 |
return filelist |
| 406 |
prefix = filelist[0] |
| 407 |
# so here's a function we assume / is the directory separator |
| 408 |
if '/' in prefix: |
| 409 |
prefix = prefix.partition('/')[0] + '/' |
| 410 |
names = filelist |
| 411 |
else: |
| 412 |
prefix = prefix + '/' |
| 413 |
names = filelist[1:] |
| 414 |
for name in names: |
| 415 |
if not name.startswith(prefix): |
| 416 |
raise Failure("File doesn't have the common prefix (%s): %s" |
| 417 |
% (name, prefix)) |
| 418 |
return [name[len(prefix):] for name in names if name != prefix] |
| 419 |
|
| 420 |
|
| 421 |
class VCS: |
| 422 |
|
| 423 |
metadata_name: str |
| 424 |
|
| 425 |
def __init__(self, ui: UI) -> None: |
| 426 |
self.ui = ui |
| 427 |
|
| 428 |
@classmethod |
| 429 |
def detect(cls, location: str) -> bool: |
| 430 |
return os.path.isdir(os.path.join(location, cls.metadata_name)) |
| 431 |
|
| 432 |
def get_versioned_files(self) -> list[str]: |
| 433 |
raise NotImplementedError('this is an abstract method') |
| 434 |
|
| 435 |
|
| 436 |
class Git(VCS): |
| 437 |
metadata_name = '.git' |
| 438 |
|
| 439 |
# Git for Windows uses UTF-8 instead of the locale encoding. |
| 440 |
# Git on POSIX systems uses the locale encoding. |
| 441 |
_encoding = 'UTF-8' if sys.platform == 'win32' else None |
| 442 |
|
| 443 |
@classmethod |
| 444 |
def detect(cls, location: str) -> bool: |
| 445 |
# .git can be a file for submodules |
| 446 |
return os.path.exists(os.path.join(location, cls.metadata_name)) |
| 447 |
|
| 448 |
def get_versioned_files(self) -> list[str]: |
| 449 |
"""List all files versioned by git in the current directory.""" |
| 450 |
output = run( |
| 451 |
["git", "ls-files", "-z", "--recurse-submodules"], |
| 452 |
encoding=self._encoding, |
| 453 |
) |
| 454 |
# -z tells git to use \0 as a line terminator; split() treats it as a |
| 455 |
# line separator, so we always get one empty line at the end, which we |
| 456 |
# drop with the [:-1] slice |
| 457 |
return output.split("\0")[:-1] |
| 458 |
|
| 459 |
|
| 460 |
class Mercurial(VCS): |
| 461 |
metadata_name = '.hg' |
| 462 |
|
| 463 |
def get_versioned_files(self) -> list[str]: |
| 464 |
"""List all files under Mercurial control in the current directory.""" |
| 465 |
output = run(['hg', 'status', '-ncamd', '.']) |
| 466 |
return output.splitlines() |
| 467 |
|
| 468 |
|
| 469 |
class Bazaar(VCS): |
| 470 |
metadata_name = '.bzr' |
| 471 |
|
| 472 |
@classmethod |
| 473 |
def _get_terminal_encoding(self) -> str | None: |
| 474 |
# Python 3.6 lets us name the OEM codepage directly, which is lucky |
| 475 |
# because it also breaks our old method of OEM codepage detection |
| 476 |
# (PEP-528 changed sys.stdout.encoding to UTF-8). |
| 477 |
try: |
| 478 |
codecs.lookup('oem') |
| 479 |
except LookupError: |
| 480 |
pass |
| 481 |
else: # pragma: nocover |
| 482 |
return 'oem' |
| 483 |
# Based on bzrlib.osutils.get_terminal_encoding() |
| 484 |
encoding = getattr(sys.stdout, 'encoding', None) |
| 485 |
if not encoding: |
| 486 |
encoding = getattr(sys.stdin, 'encoding', None) |
| 487 |
if encoding == 'cp0': # "no codepage" |
| 488 |
encoding = None |
| 489 |
# NB: bzrlib falls back on bzrlib.osutils.get_user_encoding(), |
| 490 |
# which is like locale.getpreferredencoding() on steroids, and |
| 491 |
# also includes a fallback from 'ascii' to 'utf-8' when |
| 492 |
# sys.platform is 'darwin'. This is probably something we might |
| 493 |
# want to do in run(), but I'll wait for somebody to complain |
| 494 |
# first, since I don't have a Mac OS X machine and cannot test. |
| 495 |
return encoding |
| 496 |
|
| 497 |
def get_versioned_files(self) -> list[str]: |
| 498 |
"""List all files versioned in Bazaar in the current directory.""" |
| 499 |
encoding = self._get_terminal_encoding() |
| 500 |
output = run(['bzr', 'ls', '-VR'], encoding=encoding) |
| 501 |
return output.splitlines() |
| 502 |
|
| 503 |
|
| 504 |
class Subversion(VCS): |
| 505 |
metadata_name = '.svn' |
| 506 |
|
| 507 |
def get_versioned_files(self) -> list[str]: |
| 508 |
"""List all files under SVN control in the current directory.""" |
| 509 |
output = run(['svn', 'st', '-vq', '--xml'], decode=False) |
| 510 |
tree = ET.XML(output) |
| 511 |
return sorted(entry.get('path') for entry in tree.findall('.//entry') # type: ignore |
| 512 |
if self.is_interesting(entry)) |
| 513 |
|
| 514 |
def is_interesting(self, entry: ET.Element) -> bool: |
| 515 |
"""Is this entry interesting? |
| 516 |
|
| 517 |
``entry`` is an XML node representing one entry of the svn status |
| 518 |
XML output. It looks like this:: |
| 519 |
|
| 520 |
<entry path="unchanged.txt"> |
| 521 |
<wc-status item="normal" revision="1" props="none"> |
| 522 |
<commit revision="1"> |
| 523 |
<author>mg</author> |
| 524 |
<date>2015-02-06T07:52:38.163516Z</date> |
| 525 |
</commit> |
| 526 |
</wc-status> |
| 527 |
</entry> |
| 528 |
|
| 529 |
<entry path="added-but-not-committed.txt"> |
| 530 |
<wc-status item="added" revision="-1" props="none"></wc-status> |
| 531 |
</entry> |
| 532 |
|
| 533 |
<entry path="ext"> |
| 534 |
<wc-status item="external" props="none"></wc-status> |
| 535 |
</entry> |
| 536 |
|
| 537 |
<entry path="unknown.txt"> |
| 538 |
<wc-status props="none" item="unversioned"></wc-status> |
| 539 |
</entry> |
| 540 |
|
| 541 |
""" |
| 542 |
if entry.get('path') == '.': |
| 543 |
return False |
| 544 |
status = entry.find('wc-status') |
| 545 |
if status is None: |
| 546 |
self.ui.warning( |
| 547 |
'svn status --xml parse error: <entry path="%s"> without' |
| 548 |
' <wc-status>' % entry.get('path') |
| 549 |
) |
| 550 |
return False |
| 551 |
# For SVN externals we get two entries: one mentioning the |
| 552 |
# existence of the external, and one about the status of the external. |
| 553 |
if status.get('item') in ('unversioned', 'external'): |
| 554 |
return False |
| 555 |
return True |
| 556 |
|
| 557 |
|
| 558 |
def detect_vcs(ui: UI) -> VCS: |
| 559 |
"""Detect the version control system used for the current directory.""" |
| 560 |
location = os.path.abspath('.') |
| 561 |
while True: |
| 562 |
for vcs in Git, Mercurial, Bazaar, Subversion: |
| 563 |
if vcs.detect(location): |
| 564 |
return vcs(ui) |
| 565 |
parent = os.path.dirname(location) |
| 566 |
if parent == location: |
| 567 |
raise Failure("Couldn't find version control data" |
| 568 |
" (git/hg/bzr/svn supported)") |
| 569 |
location = parent |
| 570 |
|
| 571 |
|
| 572 |
def get_vcs_files(ui: UI) -> list[str]: |
| 573 |
"""List all files under version control in the current directory.""" |
| 574 |
vcs = detect_vcs(ui) |
| 575 |
return canonical_file_list(vcs.get_versioned_files()) |
| 576 |
|
| 577 |
|
| 578 |
def normalize_names(names: Iterable[str]) -> list[str]: |
| 579 |
"""Normalize file names.""" |
| 580 |
return [normalize_name(name) for name in names] |
| 581 |
|
| 582 |
|
| 583 |
def normalize_name(name: str) -> str: |
| 584 |
"""Some VCS print directory names with trailing slashes. Strip them. |
| 585 |
|
| 586 |
Easiest is to normalize the path. |
| 587 |
|
| 588 |
And encodings may trip us up too, especially when comparing lists |
| 589 |
of files. Plus maybe lowercase versus uppercase. |
| 590 |
""" |
| 591 |
name = os.path.normpath(name).replace(os.path.sep, '/') |
| 592 |
name = unicodify(name) # XXX is this necessary? |
| 593 |
if sys.platform == 'darwin': |
| 594 |
# Mac OS X may have problems comparing non-ASCII filenames, so |
| 595 |
# we convert them. |
| 596 |
name = unicodedata.normalize('NFC', name) |
| 597 |
return name |
| 598 |
|
| 599 |
|
| 600 |
# |
| 601 |
# Packaging logic |
| 602 |
# |
| 603 |
|
| 604 |
class IgnoreList: |
| 605 |
|
| 606 |
def __init__(self) -> None: |
| 607 |
self._regexps: list[re.Pattern[str]] = [] |
| 608 |
|
| 609 |
@classmethod |
| 610 |
def default(cls) -> IgnoreList: |
| 611 |
return ( |
| 612 |
cls() |
| 613 |
# these are always generated |
| 614 |
.global_exclude('PKG-INFO') |
| 615 |
.global_exclude('*.egg-info/*') |
| 616 |
# setup.cfg is always generated, but sometimes also kept in source control |
| 617 |
.global_exclude('setup.cfg') |
| 618 |
# it's not a problem if the sdist is lacking these files: |
| 619 |
.global_exclude( |
| 620 |
'.hgtags', '.hgsigs', '.hgignore', '.gitignore', '.bzrignore', |
| 621 |
'.gitattributes', |
| 622 |
) |
| 623 |
# GitHub template files |
| 624 |
.prune('.github') |
| 625 |
# we can do without these in sdists |
| 626 |
.global_exclude('.circleci/config.yml') |
| 627 |
.global_exclude('.gitpod.yml') |
| 628 |
.global_exclude('.travis.yml') |
| 629 |
.global_exclude('Jenkinsfile') |
| 630 |
# It's convenient to ship compiled .mo files in sdists, but they |
| 631 |
# shouldn't be checked in, so don't complain that they're missing |
| 632 |
# from VCS |
| 633 |
.global_exclude('*.mo') |
| 634 |
) |
| 635 |
|
| 636 |
def clear(self) -> None: |
| 637 |
self._regexps = [] |
| 638 |
|
| 639 |
def __repr__(self) -> str: |
| 640 |
return 'IgnoreList(%r)' % ( |
| 641 |
[getattr(p, '_pattern', p) for p in self._regexps] |
| 642 |
) |
| 643 |
|
| 644 |
def __eq__(self, other: object) -> bool: |
| 645 |
return ( |
| 646 |
isinstance(other, IgnoreList) |
| 647 |
and len(self._regexps) == len(other._regexps) |
| 648 |
and all( |
| 649 |
getattr(a, '_pattern', a) == getattr(b, '_pattern', b) |
| 650 |
for a, b in zip(self._regexps, other._regexps) |
| 651 |
) |
| 652 |
) |
| 653 |
|
| 654 |
def __iadd__(self, other: IgnoreList) -> IgnoreList: |
| 655 |
assert isinstance(other, IgnoreList) |
| 656 |
self._regexps += other._regexps |
| 657 |
return self |
| 658 |
|
| 659 |
def _path(self, path: str) -> str: |
| 660 |
return path.replace('/', os.path.sep) |
| 661 |
|
| 662 |
def exclude(self, *patterns: str) -> IgnoreList: |
| 663 |
for pat in patterns: |
| 664 |
pat = self._path(pat) |
| 665 |
self._regexps.append(translate_pattern(pat)) |
| 666 |
return self |
| 667 |
|
| 668 |
def global_exclude(self, *patterns: str) -> IgnoreList: |
| 669 |
for pat in patterns: |
| 670 |
pat = os.path.join('**', self._path(pat)) |
| 671 |
self._regexps.append(translate_pattern(pat)) |
| 672 |
return self |
| 673 |
|
| 674 |
def recursive_exclude(self, dirname: str, *patterns: str) -> IgnoreList: |
| 675 |
dirname = self._path(dirname) |
| 676 |
for pat in patterns: |
| 677 |
pat = os.path.join(dirname, '**', self._path(pat)) |
| 678 |
self._regexps.append(translate_pattern(pat)) |
| 679 |
return self |
| 680 |
|
| 681 |
def prune(self, subdir: str) -> IgnoreList: |
| 682 |
pat = os.path.join(self._path(subdir), '**') |
| 683 |
self._regexps.append(translate_pattern(pat)) |
| 684 |
return self |
| 685 |
|
| 686 |
def filter(self, filelist: list[str]) -> list[str]: |
| 687 |
return [name for name in filelist |
| 688 |
if not any(rx.match(self._path(name)) for rx in self._regexps)] |
| 689 |
|
| 690 |
|
| 691 |
WARN_ABOUT_FILES_IN_VCS = [ |
| 692 |
# generated files should not be committed into the VCS |
| 693 |
'PKG-INFO', |
| 694 |
'*.egg-info', |
| 695 |
'*.mo', |
| 696 |
'*.py[co]', |
| 697 |
'*.so', |
| 698 |
'*.pyd', |
| 699 |
'*~', |
| 700 |
'.*.sw[po]', |
| 701 |
'.#*', |
| 702 |
] |
| 703 |
|
| 704 |
SUGGESTIONS = [(re.compile(pattern), suggestion) for pattern, suggestion in [ |
| 705 |
# regexp -> suggestion |
| 706 |
('^([^/]+[.](cfg|ini))$', r'include \1'), |
| 707 |
('^([.]travis[.]yml)$', r'include \1'), |
| 708 |
('^([.]coveragerc)$', r'include \1'), |
| 709 |
('^([A-Z]+)$', r'include \1'), |
| 710 |
('^(Makefile)$', r'include \1'), |
| 711 |
('^[^/]+[.](txt|rst|py)$', r'include *.\1'), |
| 712 |
('^([a-zA-Z_][a-zA-Z_0-9]*)/' |
| 713 |
'.*[.](py|zcml|pt|mako|xml|html|txt|rst|css|png|jpg|dot|po|pot|mo|ui|desktop|bat)$', |
| 714 |
r'recursive-include \1 *.\2'), |
| 715 |
('^([a-zA-Z_][a-zA-Z_0-9]*)(?:/.*)?/(Makefile)$', |
| 716 |
r'recursive-include \1 \2'), |
| 717 |
# catch-all rules that actually cover some of the above; somewhat |
| 718 |
# experimental: I fear false positives |
| 719 |
('^([a-zA-Z_0-9]+)$', r'include \1'), |
| 720 |
('^[^/]+[.]([a-zA-Z_0-9]+)$', r'include *.\1'), |
| 721 |
('^([a-zA-Z_][a-zA-Z_0-9]*)/.*[.]([a-zA-Z_0-9]+)$', |
| 722 |
r'recursive-include \1 *.\2'), |
| 723 |
]] |
| 724 |
|
| 725 |
CFG_SECTION_CHECK_MANIFEST = 'check-manifest' |
| 726 |
CFG_IGNORE_DEFAULT_RULES = (CFG_SECTION_CHECK_MANIFEST, 'ignore-default-rules') |
| 727 |
CFG_IGNORE = (CFG_SECTION_CHECK_MANIFEST, 'ignore') |
| 728 |
CFG_IGNORE_BAD_IDEAS = (CFG_SECTION_CHECK_MANIFEST, 'ignore-bad-ideas') |
| 729 |
|
| 730 |
|
| 731 |
def read_config() -> tuple[IgnoreList, IgnoreList]: |
| 732 |
"""Read configuration from file if possible. |
| 733 |
|
| 734 |
Returns two IgnoreLists: one to suppress warnings about files missing in |
| 735 |
VCS, and one to suppress warnings about files being added to VCS. |
| 736 |
""" |
| 737 |
ignore = IgnoreList.default() |
| 738 |
ignore_bad_ideas = IgnoreList() |
| 739 |
config = _load_config() |
| 740 |
if config.get(CFG_IGNORE_DEFAULT_RULES[1], False): |
| 741 |
ignore.clear() |
| 742 |
if CFG_IGNORE[1] in config: |
| 743 |
for p in config[CFG_IGNORE[1]]: # type: ignore |
| 744 |
if p: |
| 745 |
ignore.global_exclude(p) |
| 746 |
if CFG_IGNORE_BAD_IDEAS[1] in config: |
| 747 |
for p in config[CFG_IGNORE_BAD_IDEAS[1]]: # type: ignore |
| 748 |
if p: |
| 749 |
ignore_bad_ideas.global_exclude(p) |
| 750 |
return ignore, ignore_bad_ideas |
| 751 |
|
| 752 |
|
| 753 |
ConfigDict = TypedDict( |
| 754 |
'ConfigDict', |
| 755 |
{ |
| 756 |
'ignore-default-rules': bool, |
| 757 |
'ignore': list[str], |
| 758 |
'ignore-bad-ideas': list[str], |
| 759 |
}, |
| 760 |
total=False |
| 761 |
) |
| 762 |
|
| 763 |
|
| 764 |
def _load_config() -> ConfigDict: |
| 765 |
"""Searches for config files, reads them and returns a dictionary |
| 766 |
|
| 767 |
Looks for a ``check-manifest`` section in ``pyproject.toml``, |
| 768 |
``setup.cfg``, and ``tox.ini``, in that order. The first file |
| 769 |
that exists and has that section will be loaded and returned as a |
| 770 |
dictionary. |
| 771 |
|
| 772 |
""" |
| 773 |
if os.path.exists("pyproject.toml"): |
| 774 |
with open('pyproject.toml', 'rb') as f: |
| 775 |
config = tomllib.load(f) |
| 776 |
if CFG_SECTION_CHECK_MANIFEST in config.get("tool", {}): |
| 777 |
return config["tool"][CFG_SECTION_CHECK_MANIFEST] # type: ignore |
| 778 |
|
| 779 |
search_files = ['setup.cfg', 'tox.ini'] |
| 780 |
config_parser = configparser.ConfigParser() |
| 781 |
for filename in search_files: |
| 782 |
if (config_parser.read([filename]) |
| 783 |
and config_parser.has_section(CFG_SECTION_CHECK_MANIFEST)): |
| 784 |
config = {} |
| 785 |
|
| 786 |
if config_parser.has_option(*CFG_IGNORE_DEFAULT_RULES): |
| 787 |
ignore_defaults = config_parser.getboolean(*CFG_IGNORE_DEFAULT_RULES) |
| 788 |
config[CFG_IGNORE_DEFAULT_RULES[1]] = ignore_defaults |
| 789 |
|
| 790 |
if config_parser.has_option(*CFG_IGNORE): |
| 791 |
patterns = [ |
| 792 |
p.strip() |
| 793 |
for p in config_parser.get(*CFG_IGNORE).splitlines() |
| 794 |
] |
| 795 |
config[CFG_IGNORE[1]] = patterns |
| 796 |
|
| 797 |
if config_parser.has_option(*CFG_IGNORE_BAD_IDEAS): |
| 798 |
patterns = [ |
| 799 |
p.strip() |
| 800 |
for p in config_parser.get(*CFG_IGNORE_BAD_IDEAS).splitlines() |
| 801 |
] |
| 802 |
config[CFG_IGNORE_BAD_IDEAS[1]] = patterns |
| 803 |
|
| 804 |
return config # type: ignore |
| 805 |
|
| 806 |
return {} |
| 807 |
|
| 808 |
|
| 809 |
def read_manifest(ui: UI) -> IgnoreList: |
| 810 |
"""Read existing configuration from MANIFEST.in. |
| 811 |
|
| 812 |
We use that to ignore anything the MANIFEST.in ignores. |
| 813 |
""" |
| 814 |
if not os.path.isfile('MANIFEST.in'): |
| 815 |
return IgnoreList() |
| 816 |
return _get_ignore_from_manifest('MANIFEST.in', ui) |
| 817 |
|
| 818 |
|
| 819 |
LineNumber = int | tuple[int, int] | list[int] | None |
| 820 |
|
| 821 |
|
| 822 |
def _get_ignore_from_manifest(filename: str, ui: UI) -> IgnoreList: |
| 823 |
"""Gather the various ignore patterns from a MANIFEST.in. |
| 824 |
|
| 825 |
Returns an IgnoreList instance. |
| 826 |
""" |
| 827 |
|
| 828 |
class MyTextFile(TextFile): # type: ignore |
| 829 |
def error(self, msg: str, line: LineNumber = None) -> None: # pragma: nocover |
| 830 |
# (this is never called by TextFile in current versions of CPython) |
| 831 |
raise Failure(self.gen_error(msg, line)) |
| 832 |
|
| 833 |
def warn(self, msg: str, line: LineNumber = None) -> None: |
| 834 |
ui.warning(self.gen_error(msg, line)) |
| 835 |
|
| 836 |
template = MyTextFile(filename, |
| 837 |
strip_comments=True, |
| 838 |
skip_blanks=True, |
| 839 |
join_lines=True, |
| 840 |
lstrip_ws=True, |
| 841 |
rstrip_ws=True, |
| 842 |
collapse_join=True) |
| 843 |
try: |
| 844 |
lines = template.readlines() |
| 845 |
finally: |
| 846 |
template.close() |
| 847 |
return _get_ignore_from_manifest_lines(lines, ui) |
| 848 |
|
| 849 |
|
| 850 |
def _get_ignore_from_manifest_lines(lines: list[str], ui: UI) -> IgnoreList: |
| 851 |
"""Gather the various ignore patterns from a MANIFEST.in. |
| 852 |
|
| 853 |
'lines' should be a list of strings with comments removed |
| 854 |
and continuation lines joined. |
| 855 |
|
| 856 |
Returns an IgnoreList instance. |
| 857 |
""" |
| 858 |
ignore = IgnoreList() |
| 859 |
for line in lines: |
| 860 |
try: |
| 861 |
cmd, rest = line.split(None, 1) |
| 862 |
except ValueError: |
| 863 |
# no whitespace, so not interesting |
| 864 |
continue |
| 865 |
for part in rest.split(): |
| 866 |
# distutils enforces these warnings on Windows only |
| 867 |
if part.startswith('/'): |
| 868 |
ui.warning("ERROR: Leading slashes are not allowed in MANIFEST.in on Windows: %s" % part) |
| 869 |
if part.endswith('/'): |
| 870 |
ui.warning("ERROR: Trailing slashes are not allowed in MANIFEST.in on Windows: %s" % part) |
| 871 |
if cmd == 'exclude': |
| 872 |
ignore.exclude(*rest.split()) |
| 873 |
elif cmd == 'global-exclude': |
| 874 |
ignore.global_exclude(*rest.split()) |
| 875 |
elif cmd == 'recursive-exclude': |
| 876 |
try: |
| 877 |
dirname, patterns = rest.split(None, 1) |
| 878 |
except ValueError: |
| 879 |
# Wrong MANIFEST.in line. |
| 880 |
ui.warning( |
| 881 |
"You have a wrong line in MANIFEST.in: %r\n" |
| 882 |
"'recursive-exclude' expects <dir> <pattern1> <pattern2>..." |
| 883 |
% line |
| 884 |
) |
| 885 |
continue |
| 886 |
ignore.recursive_exclude(dirname, *patterns.split()) |
| 887 |
elif cmd == 'prune': |
| 888 |
ignore.prune(rest) |
| 889 |
# XXX: This ignores all 'include'/'global-include'/'recusive-include'/'graft' commands, |
| 890 |
# which is wrong! Quoting the documentation: |
| 891 |
# |
| 892 |
# The order of commands in the manifest template matters: initially, |
| 893 |
# we have the list of default files as described above, and each |
| 894 |
# command in the template adds to or removes from that list of |
| 895 |
# files. |
| 896 |
# -- https://docs.python.org/3.8/distutils/sourcedist.html#specifying-the-files-to-distribute |
| 897 |
return ignore |
| 898 |
|
| 899 |
|
| 900 |
def file_matches(filename: str, patterns: list[str]) -> bool: |
| 901 |
"""Does this filename match any of the patterns?""" |
| 902 |
return any(fnmatch.fnmatch(filename, pat) |
| 903 |
or fnmatch.fnmatch(os.path.basename(filename), pat) |
| 904 |
for pat in patterns) |
| 905 |
|
| 906 |
|
| 907 |
def strip_sdist_extras(ignore: IgnoreList, filelist: list[str]) -> list[str]: |
| 908 |
"""Strip generated files that are only present in source distributions. |
| 909 |
|
| 910 |
We also strip files that are ignored for other reasons, like |
| 911 |
command line arguments, setup.cfg rules or MANIFEST.in rules. |
| 912 |
""" |
| 913 |
return ignore.filter(filelist) |
| 914 |
|
| 915 |
|
| 916 |
def find_bad_ideas(filelist: Iterable[str]) -> list[str]: |
| 917 |
"""Find files matching WARN_ABOUT_FILES_IN_VCS patterns.""" |
| 918 |
return [name for name in filelist |
| 919 |
if file_matches(name, WARN_ABOUT_FILES_IN_VCS)] |
| 920 |
|
| 921 |
|
| 922 |
def find_suggestions(filelist: Iterable[str]) -> tuple[list[str], list[str]]: |
| 923 |
"""Suggest MANIFEST.in patterns for missing files. |
| 924 |
|
| 925 |
Returns two lists: one with suggested MANIGEST.in commands, and one with |
| 926 |
files for which no suggestions were offered. |
| 927 |
""" |
| 928 |
suggestions = set() |
| 929 |
unknowns = [] |
| 930 |
for filename in filelist: |
| 931 |
for pattern, suggestion in SUGGESTIONS: |
| 932 |
m = pattern.match(filename) |
| 933 |
if m is not None: |
| 934 |
suggestions.add(pattern.sub(suggestion, filename)) |
| 935 |
break |
| 936 |
else: |
| 937 |
unknowns.append(filename) |
| 938 |
return sorted(suggestions), unknowns |
| 939 |
|
| 940 |
|
| 941 |
def is_package(source_tree: str = '.') -> bool: |
| 942 |
"""Is the directory the root of a Python package? |
| 943 |
|
| 944 |
Note: the term "package" here refers to a collection of files |
| 945 |
with a setup.py/pyproject.toml, not to a directory with an __init__.py. |
| 946 |
""" |
| 947 |
return ( |
| 948 |
os.path.exists(os.path.join(source_tree, 'setup.py')) |
| 949 |
or os.path.exists(os.path.join(source_tree, 'pyproject.toml')) |
| 950 |
) |
| 951 |
|
| 952 |
|
| 953 |
def extract_version_from_filename(filename: str) -> str: |
| 954 |
"""Extract version number from sdist filename.""" |
| 955 |
filename = os.path.splitext(os.path.basename(filename))[0] |
| 956 |
if filename.endswith('.tar'): |
| 957 |
filename = os.path.splitext(filename)[0] |
| 958 |
return filename.split('-')[-1] |
| 959 |
|
| 960 |
|
| 961 |
def should_use_pep_517() -> bool: |
| 962 |
"""Check if the project uses PEP-517 builds.""" |
| 963 |
# https://www.python.org/dev/peps/pep-0517/#build-system-table says |
| 964 |
# "If the pyproject.toml file is absent, or the build-backend key is |
| 965 |
# missing, the source tree is not using this specification, and tools |
| 966 |
# should revert to the legacy behaviour of running setup.py". |
| 967 |
if not os.path.exists('pyproject.toml'): |
| 968 |
return False |
| 969 |
with open('pyproject.toml', 'rb') as f: |
| 970 |
config = tomllib.load(f) |
| 971 |
if "build-system" not in config: |
| 972 |
return False |
| 973 |
if "build-backend" not in config["build-system"]: |
| 974 |
return False |
| 975 |
return True |
| 976 |
|
| 977 |
|
| 978 |
def build_sdist(tempdir: str, python: str = sys.executable, build_isolation: bool = True) -> None: |
| 979 |
"""Build a source distribution in a temporary directory. |
| 980 |
|
| 981 |
Should be run with the current working directory inside the Python package |
| 982 |
you want to build. |
| 983 |
""" |
| 984 |
if should_use_pep_517(): |
| 985 |
# I could do this in-process with |
| 986 |
# import build.__main__ |
| 987 |
# build.__main__.build('.', tempdir) |
| 988 |
# but then it would print a bunch of things to stdout and I'd have to |
| 989 |
# worry about exceptions |
| 990 |
cmd = [python, '-m', 'build', '--sdist', '.', '--outdir', tempdir] |
| 991 |
if not build_isolation: |
| 992 |
cmd.append('--no-isolation') |
| 993 |
run(cmd) |
| 994 |
else: |
| 995 |
run([python, 'setup.py', 'sdist', '-d', tempdir]) |
| 996 |
|
| 997 |
|
| 998 |
def check_manifest( |
| 999 |
source_tree: str = '.', |
| 1000 |
create: bool = False, |
| 1001 |
update: bool = False, |
| 1002 |
python: str = sys.executable, |
| 1003 |
ui: UI | None = None, |
| 1004 |
extra_ignore: IgnoreList | None = None, |
| 1005 |
extra_ignore_bad_ideas: IgnoreList | None = None, |
| 1006 |
build_isolation: bool = True, |
| 1007 |
) -> bool: |
| 1008 |
"""Compare a generated source distribution with list of files in a VCS. |
| 1009 |
|
| 1010 |
Returns True if the manifest is fine. |
| 1011 |
""" |
| 1012 |
if ui is None: |
| 1013 |
ui = UI() |
| 1014 |
all_ok = True |
| 1015 |
if os.path.sep in python: |
| 1016 |
python = os.path.abspath(python) |
| 1017 |
with cd(source_tree): |
| 1018 |
if not is_package(): |
| 1019 |
raise Failure( |
| 1020 |
'This is not a Python project (no setup.py/pyproject.toml).') |
| 1021 |
ignore, ignore_bad_ideas = read_config() |
| 1022 |
ignore += read_manifest(ui) |
| 1023 |
if extra_ignore: |
| 1024 |
ignore += extra_ignore |
| 1025 |
if extra_ignore_bad_ideas: |
| 1026 |
ignore_bad_ideas += extra_ignore_bad_ideas |
| 1027 |
ui.info_begin("listing source files under version control") |
| 1028 |
all_source_files = get_vcs_files(ui) |
| 1029 |
source_files = strip_sdist_extras(ignore, all_source_files) |
| 1030 |
ui.info_continue(": %d files and directories" % len(source_files)) |
| 1031 |
if not all_source_files: |
| 1032 |
raise Failure('There are no files added to version control!') |
| 1033 |
ui.info_begin("building an sdist") |
| 1034 |
with mkdtemp('-sdist') as tempdir: |
| 1035 |
build_sdist(tempdir, python=python, build_isolation=build_isolation) |
| 1036 |
sdist_filename = get_one_file_in(tempdir) |
| 1037 |
ui.info_continue(": %s" % os.path.basename(sdist_filename)) |
| 1038 |
sdist_files = get_sdist_file_list(sdist_filename, ignore) |
| 1039 |
ui.info_continue(": %d files and directories" % len(sdist_files)) |
| 1040 |
version = extract_version_from_filename(sdist_filename) |
| 1041 |
existing_source_files = list(filter(os.path.exists, all_source_files)) |
| 1042 |
missing_source_files = sorted(set(all_source_files) - set(existing_source_files)) |
| 1043 |
if missing_source_files: |
| 1044 |
ui.warning("some files listed as being under source control are missing:\n%s" |
| 1045 |
% format_list(missing_source_files)) |
| 1046 |
ui.info_begin("copying source files to a temporary directory") |
| 1047 |
with mkdtemp('-sources') as tempsourcedir: |
| 1048 |
copy_files(existing_source_files, tempsourcedir) |
| 1049 |
for filename in 'MANIFEST.in', 'setup.py', 'pyproject.toml': |
| 1050 |
if filename not in source_files and os.path.exists(filename): |
| 1051 |
# See https://github.com/mgedmin/check-manifest/issues/7 |
| 1052 |
# and https://github.com/mgedmin/check-manifest/issues/46: |
| 1053 |
# if we do this, the user gets a warning about files |
| 1054 |
# missing from source control; if we don't do this, |
| 1055 |
# things get very confusing for the user! |
| 1056 |
copy_files([filename], tempsourcedir) |
| 1057 |
ui.info_begin("building a clean sdist") |
| 1058 |
with cd(tempsourcedir): |
| 1059 |
with mkdtemp('-sdist') as tempdir: |
| 1060 |
os.environ['SETUPTOOLS_SCM_PRETEND_VERSION'] = version |
| 1061 |
build_sdist(tempdir, python=python, build_isolation=build_isolation) |
| 1062 |
sdist_filename = get_one_file_in(tempdir) |
| 1063 |
ui.info_continue(": %s" % os.path.basename(sdist_filename)) |
| 1064 |
clean_sdist_files = get_sdist_file_list(sdist_filename, ignore) |
| 1065 |
ui.info_continue(": %d files and directories" % len(clean_sdist_files)) |
| 1066 |
missing_from_manifest = set(source_files) - set(clean_sdist_files) |
| 1067 |
missing_from_VCS = set(sdist_files + clean_sdist_files) - set(source_files) |
| 1068 |
if not missing_from_manifest and not missing_from_VCS: |
| 1069 |
ui.info("lists of files in version control and sdist match") |
| 1070 |
else: |
| 1071 |
ui.error( |
| 1072 |
"lists of files in version control and sdist do not match!\n%s" |
| 1073 |
% format_missing(missing_from_VCS, missing_from_manifest, "VCS", "sdist")) |
| 1074 |
suggestions, unknowns = find_suggestions(missing_from_manifest) |
| 1075 |
user_asked_for_help = update or (create and not |
| 1076 |
os.path.exists('MANIFEST.in')) |
| 1077 |
if 'MANIFEST.in' not in existing_source_files: |
| 1078 |
if suggestions and not user_asked_for_help: |
| 1079 |
ui.info("no MANIFEST.in found; you can run 'check-manifest -c' to create one") |
| 1080 |
else: |
| 1081 |
ui.info("no MANIFEST.in found") |
| 1082 |
if suggestions: |
| 1083 |
ui.info("suggested MANIFEST.in rules:\n%s" % format_list(suggestions)) |
| 1084 |
if user_asked_for_help: |
| 1085 |
existed = os.path.exists('MANIFEST.in') |
| 1086 |
with open('MANIFEST.in', 'a') as f: |
| 1087 |
if not existed: |
| 1088 |
ui.info("creating MANIFEST.in") |
| 1089 |
else: |
| 1090 |
ui.info("updating MANIFEST.in") |
| 1091 |
f.write('\n# added by check-manifest\n') |
| 1092 |
f.write('\n'.join(suggestions) + '\n') |
| 1093 |
if unknowns: |
| 1094 |
ui.info("don't know how to come up with rules matching\n%s" |
| 1095 |
% format_list(unknowns)) |
| 1096 |
elif user_asked_for_help: |
| 1097 |
ui.info("don't know how to come up with rules matching any of the files, sorry!") |
| 1098 |
all_ok = False |
| 1099 |
bad_ideas = find_bad_ideas(all_source_files) |
| 1100 |
filtered_bad_ideas = ignore_bad_ideas.filter(bad_ideas) |
| 1101 |
if filtered_bad_ideas: |
| 1102 |
ui.warning( |
| 1103 |
"you have %s in source control!\n" |
| 1104 |
"that's a bad idea: auto-generated files should not be versioned" |
| 1105 |
% filtered_bad_ideas[0]) |
| 1106 |
if len(filtered_bad_ideas) > 1: |
| 1107 |
ui.warning("this also applies to the following:\n%s" |
| 1108 |
% format_list(filtered_bad_ideas[1:])) |
| 1109 |
all_ok = False |
| 1110 |
return all_ok |
| 1111 |
|
| 1112 |
|
| 1113 |
# |
| 1114 |
# Main script |
| 1115 |
# |
| 1116 |
|
| 1117 |
def main() -> None: |
| 1118 |
parser = argparse.ArgumentParser( |
| 1119 |
description="Check a Python MANIFEST.in file for completeness") |
| 1120 |
parser.add_argument( |
| 1121 |
'source_tree', default='.', nargs='?', |
| 1122 |
help='location for the source tree (default: .)') |
| 1123 |
parser.add_argument( |
| 1124 |
'--version', action='version', |
| 1125 |
version='%(prog)s version ' + __version__) |
| 1126 |
parser.add_argument( |
| 1127 |
'-q', '--quiet', action='store_const', dest='quiet', |
| 1128 |
const=0, default=1, help='reduced output verbosity') |
| 1129 |
parser.add_argument( |
| 1130 |
'-v', '--verbose', action='store_const', dest='verbose', |
| 1131 |
const=1, default=0, help='more verbose output') |
| 1132 |
parser.add_argument( |
| 1133 |
'-c', '--create', action='store_true', |
| 1134 |
help='create a MANIFEST.in if missing (default: exit with an error)') |
| 1135 |
parser.add_argument( |
| 1136 |
'-u', '--update', action='store_true', |
| 1137 |
help='append suggestions to MANIFEST.in (implies --create)') |
| 1138 |
parser.add_argument( |
| 1139 |
'-p', '--python', default=sys.executable, |
| 1140 |
help=( |
| 1141 |
'use this Python interpreter for running setup.py sdist' |
| 1142 |
' (default: %(default)s)' |
| 1143 |
)) |
| 1144 |
parser.add_argument( |
| 1145 |
'--ignore', metavar='patterns', default=None, |
| 1146 |
help=( |
| 1147 |
'ignore files/directories matching these comma-separated' |
| 1148 |
' glob patterns' |
| 1149 |
)) |
| 1150 |
parser.add_argument( |
| 1151 |
'--ignore-bad-ideas', metavar='patterns', default=[], |
| 1152 |
help=( |
| 1153 |
'ignore bad idea files/directories matching these' |
| 1154 |
' comma-separated glob patterns' |
| 1155 |
)) |
| 1156 |
parser.add_argument( |
| 1157 |
'--no-build-isolation', dest='build_isolation', action='store_false', |
| 1158 |
help=( |
| 1159 |
'disable isolation when building a modern source distribution' |
| 1160 |
' (default: use build isolation).' |
| 1161 |
' Build dependencies specified by pyproject.toml must be already' |
| 1162 |
' installed if this option is used.' |
| 1163 |
)) |
| 1164 |
args = parser.parse_args() |
| 1165 |
|
| 1166 |
ignore = IgnoreList() |
| 1167 |
if args.ignore: |
| 1168 |
ignore.global_exclude(*args.ignore.split(',')) |
| 1169 |
|
| 1170 |
ignore_bad_ideas = IgnoreList() |
| 1171 |
if args.ignore_bad_ideas: |
| 1172 |
ignore_bad_ideas.global_exclude(*args.ignore_bad_ideas.split(',')) |
| 1173 |
|
| 1174 |
ui = UI(verbosity=args.quiet + args.verbose) |
| 1175 |
|
| 1176 |
try: |
| 1177 |
if not check_manifest(args.source_tree, create=args.create, |
| 1178 |
update=args.update, python=args.python, |
| 1179 |
ui=ui, extra_ignore=ignore, |
| 1180 |
extra_ignore_bad_ideas=ignore_bad_ideas, |
| 1181 |
build_isolation=args.build_isolation): |
| 1182 |
sys.exit(1) |
| 1183 |
except Failure as e: |
| 1184 |
ui.error(str(e)) |
| 1185 |
sys.exit(2) |
| 1186 |
|
| 1187 |
|
| 1188 |
# |
| 1189 |
# zest.releaser integration |
| 1190 |
# |
| 1191 |
|
| 1192 |
class DataDict(TypedDict): |
| 1193 |
workingdir: str |
| 1194 |
|
| 1195 |
|
| 1196 |
def zest_releaser_check(data: DataDict) -> None: |
| 1197 |
"""Check the completeness of MANIFEST.in before the release. |
| 1198 |
|
| 1199 |
This is an entry point for zest.releaser. See the documentation at |
| 1200 |
https://zestreleaser.readthedocs.io/en/latest/entrypoints.html |
| 1201 |
""" |
| 1202 |
from zest.releaser.utils import ask |
| 1203 |
source_tree = data['workingdir'] |
| 1204 |
if not is_package(source_tree): |
| 1205 |
# You can use zest.releaser on things that are not Python packages. |
| 1206 |
# It's pointless to run check-manifest in those circumstances. |
| 1207 |
# See https://github.com/mgedmin/check-manifest/issues/9 for details. |
| 1208 |
return |
| 1209 |
if not ask("Do you want to run check-manifest?"): |
| 1210 |
return |
| 1211 |
ui = UI() |
| 1212 |
try: |
| 1213 |
if not check_manifest(source_tree, ui=ui): |
| 1214 |
if not ask("MANIFEST.in has problems." |
| 1215 |
" Do you want to continue despite that?", default=False): |
| 1216 |
sys.exit(1) |
| 1217 |
except Failure as e: |
| 1218 |
ui.error(str(e)) |
| 1219 |
if not ask("Something bad happened." |
| 1220 |
" Do you want to continue despite that?", default=False): |
| 1221 |
sys.exit(2) |
| 1222 |
|
| 1223 |
|
| 1224 |
if __name__ == '__main__': |
| 1225 |
main() |