text
stringlengths
81
112k
Returns a Basic Auth string. def _basic_auth_str(username, password): """Returns a Basic Auth string.""" # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to maintain backwards compatibility # for things like ints. This will be removed in 3.0.0. if not isinstance(username, basestring): warnings.warn( "Non-string usernames will no longer be supported in Requests " "3.0.0. Please convert the object you've passed in ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(username), category=DeprecationWarning, ) username = str(username) if not isinstance(password, basestring): warnings.warn( "Non-string passwords will no longer be supported in Requests " "3.0.0. Please convert the object you've passed in ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(password), category=DeprecationWarning, ) password = str(password) # -- End Removal -- if isinstance(username, str): username = username.encode('latin1') if isinstance(password, str): password = password.encode('latin1') authstr = 'Basic ' + to_native_string( b64encode(b':'.join((username, password))).strip() ) return authstr
Convert the package data into something usable by output_package_listing_columns. def format_for_columns(pkgs, options): """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs): header.append("Location") if options.verbose >= 1: header.append("Installer") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if options.verbose >= 1 or dist_is_editable(proj): row.append(proj.location) if options.verbose >= 1: row.append(get_installer(proj)) data.append(row) return data, header
Create a package finder appropriate to this list command. def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_all_prereleases=options.pre, trusted_hosts=options.trusted_hosts, session=session, )
Build a shebang line. In the simple case (on Windows, or a shebang line which is not too long or contains spaces) use a simple formulation for the shebang. Otherwise, use /bin/sh as the executable, with a contrived shebang which allows the script to run either under Python or sh, using suitable quoting. Thanks to Harald Nordgren for his input. See also: http://www.in-ulm.de/~mascheck/various/shebang/#length https://hg.mozilla.org/mozilla-central/file/tip/mach def _build_shebang(self, executable, post_interp): """ Build a shebang line. In the simple case (on Windows, or a shebang line which is not too long or contains spaces) use a simple formulation for the shebang. Otherwise, use /bin/sh as the executable, with a contrived shebang which allows the script to run either under Python or sh, using suitable quoting. Thanks to Harald Nordgren for his input. See also: http://www.in-ulm.de/~mascheck/various/shebang/#length https://hg.mozilla.org/mozilla-central/file/tip/mach """ if os.name != 'posix': simple_shebang = True else: # Add 3 for '#!' prefix and newline suffix. shebang_length = len(executable) + len(post_interp) + 3 if sys.platform == 'darwin': max_shebang_length = 512 else: max_shebang_length = 127 simple_shebang = ((b' ' not in executable) and (shebang_length <= max_shebang_length)) if simple_shebang: result = b'#!' + executable + post_interp + b'\n' else: result = b'#!/bin/sh\n' result += b"'''exec' " + executable + post_interp + b' "$0" "$@"\n' result += b"' '''" return result
Make a script. :param specification: The specification, which is either a valid export entry specification (to make a script from a callable) or a filename (to make a script by copying from a source location). :param options: A dictionary of options controlling script generation. :return: A list of all absolute pathnames written to. def make(self, specification, options=None): """ Make a script. :param specification: The specification, which is either a valid export entry specification (to make a script from a callable) or a filename (to make a script by copying from a source location). :param options: A dictionary of options controlling script generation. :return: A list of all absolute pathnames written to. """ filenames = [] entry = get_export_entry(specification) if entry is None: self._copy_script(specification, filenames) else: self._make_script(entry, filenames, options=options) return filenames
Take a list of specifications and make scripts from them, :param specifications: A list of specifications. :return: A list of all absolute pathnames written to, def make_multiple(self, specifications, options=None): """ Take a list of specifications and make scripts from them, :param specifications: A list of specifications. :return: A list of all absolute pathnames written to, """ filenames = [] for specification in specifications: filenames.extend(self.make(specification, options)) return filenames
Returns a generator that yields file paths under a *directory*, matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also supports *ignored* patterns. Args: directory (str): Path that serves as the root of the search. Yielded paths will include this as a prefix. patterns (str or list): A single pattern or list of glob-formatted patterns to find under *directory*. ignored (str or list): A single pattern or list of glob-formatted patterns to ignore. For example, finding Python files in the directory of this module: >>> files = set(iter_find_files(os.path.dirname(__file__), '*.py')) Or, Python files while ignoring emacs lockfiles: >>> filenames = iter_find_files('.', '*.py', ignored='.#*') .. _glob: https://en.wikipedia.org/wiki/Glob_%28programming%29 def iter_find_files(directory, patterns, ignored=None): """Returns a generator that yields file paths under a *directory*, matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also supports *ignored* patterns. Args: directory (str): Path that serves as the root of the search. Yielded paths will include this as a prefix. patterns (str or list): A single pattern or list of glob-formatted patterns to find under *directory*. ignored (str or list): A single pattern or list of glob-formatted patterns to ignore. For example, finding Python files in the directory of this module: >>> files = set(iter_find_files(os.path.dirname(__file__), '*.py')) Or, Python files while ignoring emacs lockfiles: >>> filenames = iter_find_files('.', '*.py', ignored='.#*') .. _glob: https://en.wikipedia.org/wiki/Glob_%28programming%29 """ if isinstance(patterns, basestring): patterns = [patterns] pats_re = re.compile('|'.join([fnmatch.translate(p) for p in patterns])) if not ignored: ignored = [] elif isinstance(ignored, basestring): ignored = [ignored] ign_re = re.compile('|'.join([fnmatch.translate(p) for p in ignored])) for root, dirs, files in os.walk(directory): for basename in files: if pats_re.match(basename): if ignored and ign_re.match(basename): continue filename = os.path.join(root, basename) yield filename return
Create a :class:`FilePerms` object from an integer. >>> FilePerms.from_int(0o644) # note the leading zero-oh for octal FilePerms(user='rw', group='r', other='r') def from_int(cls, i): """Create a :class:`FilePerms` object from an integer. >>> FilePerms.from_int(0o644) # note the leading zero-oh for octal FilePerms(user='rw', group='r', other='r') """ i &= FULL_PERMS key = ('', 'x', 'w', 'xw', 'r', 'rx', 'rw', 'rwx') parts = [] while i: parts.append(key[i & _SINGLE_FULL_PERM]) i >>= 3 parts.reverse() return cls(*parts)
Make a new :class:`FilePerms` object based on the permissions assigned to the file or directory at *path*. Args: path (str): Filesystem path of the target file. >>> from os.path import expanduser >>> 'r' in FilePerms.from_path(expanduser('~')).user # probably True def from_path(cls, path): """Make a new :class:`FilePerms` object based on the permissions assigned to the file or directory at *path*. Args: path (str): Filesystem path of the target file. >>> from os.path import expanduser >>> 'r' in FilePerms.from_path(expanduser('~')).user # probably True """ stat_res = os.stat(path) return cls.from_int(stat.S_IMODE(stat_res.st_mode))
Called on context manager entry (the :keyword:`with` statement), the ``setup()`` method creates the temporary file in the same directory as the destination file. ``setup()`` tests for a writable directory with rename permissions early, as the part file may not be written to immediately (not using :func:`os.access` because of the potential issues of effective vs. real privileges). If the caller is not using the :class:`AtomicSaver` as a context manager, this method should be called explicitly before writing. def setup(self): """Called on context manager entry (the :keyword:`with` statement), the ``setup()`` method creates the temporary file in the same directory as the destination file. ``setup()`` tests for a writable directory with rename permissions early, as the part file may not be written to immediately (not using :func:`os.access` because of the potential issues of effective vs. real privileges). If the caller is not using the :class:`AtomicSaver` as a context manager, this method should be called explicitly before writing. """ if os.path.lexists(self.dest_path): if not self.overwrite: raise OSError(errno.EEXIST, 'Overwrite disabled and file already exists', self.dest_path) if self.overwrite_part and os.path.lexists(self.part_path): os.unlink(self.part_path) self._open_part_file() return
Loads a pipfile from a given path. If none is provided, one will try to be found. def load(pipfile_path=None, inject_env=True): """Loads a pipfile from a given path. If none is provided, one will try to be found. """ if pipfile_path is None: pipfile_path = Pipfile.find() return Pipfile.load(filename=pipfile_path, inject_env=inject_env)
Recursively injects environment variables into TOML values def inject_environment_variables(self, d): """ Recursively injects environment variables into TOML values """ if not d: return d if isinstance(d, six.string_types): return os.path.expandvars(d) for k, v in d.items(): if isinstance(v, six.string_types): d[k] = os.path.expandvars(v) elif isinstance(v, dict): d[k] = self.inject_environment_variables(v) elif isinstance(v, list): d[k] = [self.inject_environment_variables(e) for e in v] return d
Returns the path of a Pipfile in parent directories. def find(max_depth=3): """Returns the path of a Pipfile in parent directories.""" i = 0 for c, d, f in walk_up(os.getcwd()): i += 1 if i < max_depth: if 'Pipfile': p = os.path.join(c, 'Pipfile') if os.path.isfile(p): return p raise RuntimeError('No Pipfile found!')
Load a Pipfile from a given filename. def load(klass, filename, inject_env=True): """Load a Pipfile from a given filename.""" p = PipfileParser(filename=filename) pipfile = klass(filename=filename) pipfile.data = p.parse(inject_env=inject_env) return pipfile
Returns the SHA256 of the pipfile's data. def hash(self): """Returns the SHA256 of the pipfile's data.""" content = json.dumps(self.data, sort_keys=True, separators=(",", ":")) return hashlib.sha256(content.encode("utf8")).hexdigest()
Returns a JSON representation of the Pipfile. def lock(self): """Returns a JSON representation of the Pipfile.""" data = self.data data['_meta']['hash'] = {"sha256": self.hash} data['_meta']['pipfile-spec'] = 6 return json.dumps(data, indent=4, separators=(',', ': '))
Asserts PEP 508 specifiers. def assert_requirements(self): """"Asserts PEP 508 specifiers.""" # Support for 508's implementation_version. if hasattr(sys, 'implementation'): implementation_version = format_full_version(sys.implementation.version) else: implementation_version = "0" # Default to cpython for 2.7. if hasattr(sys, 'implementation'): implementation_name = sys.implementation.name else: implementation_name = 'cpython' lookup = { 'os_name': os.name, 'sys_platform': sys.platform, 'platform_machine': platform.machine(), 'platform_python_implementation': platform.python_implementation(), 'platform_release': platform.release(), 'platform_system': platform.system(), 'platform_version': platform.version(), 'python_version': platform.python_version()[:3], 'python_full_version': platform.python_version(), 'implementation_name': implementation_name, 'implementation_version': implementation_version } # Assert each specified requirement. for marker, specifier in self.data['_meta']['requires'].items(): if marker in lookup: try: assert lookup[marker] == specifier except AssertionError: raise AssertionError('Specifier {!r} does not match {!r}.'.format(marker, specifier))
copy data from file-like object fsrc to file-like object fdst def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)
Copy data from src to dst def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass else: # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: copyfileobj(fsrc, fdst)
Copy mode bits from src to dst def copymode(src, dst): """Copy mode bits from src to dst""" if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode)
Copy all stat info (mode bits, atime, mtime, flags) from src to dst def copystat(src, dst): """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): try: os.chflags(dst, st.st_flags) except OSError as why: if (not hasattr(errno, 'EOPNOTSUPP') or why.errno != errno.EOPNOTSUPP): raise
Copy data and mode bits ("cp src dst"). The destination may be a directory. def copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst)
Copy data and all stat info ("cp -p src dst"). The destination may be a directory. def copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst)
Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. def rmtree(path, ignore_errors=False, onerror=None): """Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. """ if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise try: if os.path.islink(path): # symlinks to directories are forbidden, see bug #1669 raise OSError("Cannot call rmtree on a symbolic link") except OSError: onerror(os.path.islink, path, sys.exc_info()) # can't continue even if onerror hook returns return names = [] try: names = os.listdir(path) except os.error: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except os.error: mode = 0 if stat.S_ISDIR(mode): rmtree(fullname, ignore_errors, onerror) else: try: os.remove(fullname) except os.error: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) except os.error: onerror(os.rmdir, path, sys.exc_info())
Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. def move(src, dst): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ real_dst = dst if os.path.isdir(dst): if _samefile(src, dst): # We might be on a case insensitive filesystem, # perform the rename anyway. os.rename(src, dst) return real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path '%s' already exists" % real_dst) try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst)) copytree(src, real_dst, symlinks=True) rmtree(src) else: copy2(src, real_dst) os.unlink(src)
Returns a gid, given a group name. def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None
Returns an uid, given a user name. def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", or None. 'owner' and 'group' can be used to define an owner and a group for the archive that is being built. If not provided, the current owner and group will be used. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", or ".bz2"). Returns the output filename. def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", or None. 'owner' and 'group' can be used to define an owner and a group for the archive that is being built. If not provided, the current owner and group will be used. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", or ".bz2"). Returns the output filename. """ tar_compression = {'gzip': 'gz', None: ''} compress_ext = {'gzip': '.gz'} if _BZ2_SUPPORTED: tar_compression['bzip2'] = 'bz2' compress_ext['bzip2'] = '.bz2' # flags for compression program, each element of list will be an argument if compress is not None and compress not in compress_ext: raise ValueError("bad value for 'compress', or compression format not " "supported : {0}".format(compress)) archive_name = base_name + '.tar' + compress_ext.get(compress, '') archive_dir = os.path.dirname(archive_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # creating the tarball if logger is not None: logger.info('Creating tar archive') uid = _get_uid(owner) gid = _get_gid(group) def _set_uid_gid(tarinfo): if gid is not None: tarinfo.gid = gid tarinfo.gname = group if uid is not None: tarinfo.uid = uid tarinfo.uname = owner return tarinfo if not dry_run: tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress]) try: tar.add(base_dir, filter=_set_uid_gid) finally: tar.close() return archive_name
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. """ zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # If zipfile module is not available, try spawning an external 'zip' # command. try: import zipfile except ImportError: zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(base_dir): for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) if logger is not None: logger.info("adding '%s'", path) zip.close() return zip_filename
Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_archive_formats() function. def register_archive_format(name, function, extra_args=None, description=''): """Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_archive_formats() function. """ if extra_args is None: extra_args = [] if not isinstance(function, collections.Callable): raise TypeError('The %s object is not callable' % function) if not isinstance(extra_args, (tuple, list)): raise TypeError('extra_args needs to be a sequence') for element in extra_args: if not isinstance(element, (tuple, list)) or len(element) !=2: raise TypeError('extra_args elements are : (arg_name, value)') _ARCHIVE_FORMATS[name] = (function, extra_args, description)
Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. """ save_cwd = os.getcwd() if root_dir is not None: if logger is not None: logger.debug("changing into '%s'", root_dir) base_name = os.path.abspath(base_name) if not dry_run: os.chdir(root_dir) if base_dir is None: base_dir = os.curdir kwargs = {'dry_run': dry_run, 'logger': logger} try: format_info = _ARCHIVE_FORMATS[format] except KeyError: raise ValueError("unknown archive format '%s'" % format) func = format_info[0] for arg, val in format_info[1]: kwargs[arg] = val if format != 'zip': kwargs['owner'] = owner kwargs['group'] = group try: filename = func(base_name, base_dir, **kwargs) finally: if root_dir is not None: if logger is not None: logger.debug("changing back to '%s'", save_cwd) os.chdir(save_cwd) return filename
Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) def get_unpack_formats(): """Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) """ formats = [(name, info[0], info[3]) for name, info in _UNPACK_FORMATS.items()] formats.sort() return formats
Checks what gets registered as an unpacker. def _check_unpack_options(extensions, function, extra_args): """Checks what gets registered as an unpacker.""" # first make sure no other unpacker is registered for this extension existing_extensions = {} for name, info in _UNPACK_FORMATS.items(): for ext in info[0]: existing_extensions[ext] = name for extension in extensions: if extension in existing_extensions: msg = '%s is already registered for "%s"' raise RegistryError(msg % (extension, existing_extensions[extension])) if not isinstance(function, collections.Callable): raise TypeError('The registered function must be a callable')
Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unpack archives. The callable will receive archives to unpack. If it's unable to handle an archive, it needs to raise a ReadError exception. If provided, `extra_args` is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_unpack_formats() function. def register_unpack_format(name, extensions, function, extra_args=None, description=''): """Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unpack archives. The callable will receive archives to unpack. If it's unable to handle an archive, it needs to raise a ReadError exception. If provided, `extra_args` is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_unpack_formats() function. """ if extra_args is None: extra_args = [] _check_unpack_options(extensions, function, extra_args) _UNPACK_FORMATS[name] = extensions, function, extra_args, description
Ensure that the parent directory of `path` exists def _ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname)
Unpack zip `filename` to `extract_dir` def _unpack_zipfile(filename, extract_dir): """Unpack zip `filename` to `extract_dir` """ try: import zipfile except ImportError: raise ReadError('zlib not supported, cannot unpack this archive.') if not zipfile.is_zipfile(filename): raise ReadError("%s is not a zip file" % filename) zip = zipfile.ZipFile(filename) try: for info in zip.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name: continue target = os.path.join(extract_dir, *name.split('/')) if not target: continue _ensure_directory(target) if not name.endswith('/'): # file data = zip.read(info.filename) f = open(target, 'wb') try: f.write(data) finally: f.close() del data finally: zip.close()
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` def _unpack_tarfile(filename, extract_dir): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise ReadError( "%s is not a compressed or uncompressed tar file" % filename) try: tarobj.extractall(extract_dir) finally: tarobj.close()
Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. def unpack_archive(filename, extract_dir=None, format=None): """Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. """ if extract_dir is None: extract_dir = os.getcwd() if format is not None: try: format_info = _UNPACK_FORMATS[format] except KeyError: raise ValueError("Unknown unpack format '{0}'".format(format)) func = format_info[1] func(filename, extract_dir, **dict(format_info[2])) else: # we need to look at the registered unpackers supported extensions format = _find_unpack_format(filename) if format is None: raise ReadError("Unknown archive format '{0}'".format(filename)) func = _UNPACK_FORMATS[format][1] kwargs = dict(_UNPACK_FORMATS[format][2]) func(filename, extract_dir, **kwargs)
Parse an HTML fragment as a string or file-like object into a tree :arg doc: the fragment to parse as a string or file-like object :arg container: the container context to parse the fragment in :arg treebuilder: the treebuilder to use when parsing :arg namespaceHTMLElements: whether or not to namespace HTML elements :returns: parsed tree Example: >>> from html5lib.html5libparser import parseFragment >>> parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs): """Parse an HTML fragment as a string or file-like object into a tree :arg doc: the fragment to parse as a string or file-like object :arg container: the container context to parse the fragment in :arg treebuilder: the treebuilder to use when parsing :arg namespaceHTMLElements: whether or not to namespace HTML elements :returns: parsed tree Example: >>> from html5lib.html5libparser import parseFragment >>> parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> """ tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) return p.parseFragment(doc, container=container, **kwargs)
Parse a HTML document into a well-formed tree :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element). :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5parser import HTMLParser >>> parser = HTMLParser() >>> parser.parse('<html><body><p>This is a doc</p></body></html>') <Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> def parse(self, stream, *args, **kwargs): """Parse a HTML document into a well-formed tree :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element). :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5parser import HTMLParser >>> parser = HTMLParser() >>> parser.parse('<html><body><p>This is a doc</p></body></html>') <Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> """ self._parse(stream, False, None, *args, **kwargs) return self.tree.getDocument()
Parse a HTML fragment into a well-formed tree fragment :arg container: name of the element we're setting the innerHTML property if set to None, default to 'div' :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5libparser import HTMLParser >>> parser = HTMLParser() >>> parser.parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> def parseFragment(self, stream, *args, **kwargs): """Parse a HTML fragment into a well-formed tree fragment :arg container: name of the element we're setting the innerHTML property if set to None, default to 'div' :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5libparser import HTMLParser >>> parser = HTMLParser() >>> parser.parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> """ self._parse(stream, True, *args, **kwargs) return self.tree.getFragment()
Construct tree representation of the pkgs from the index. The keys of the dict representing the tree will be objects of type DistPackage and the values will be list of ReqPackage objects. :param dict index: dist index ie. index of pkgs by their keys :returns: tree of pkgs and their dependencies :rtype: dict def construct_tree(index): """Construct tree representation of the pkgs from the index. The keys of the dict representing the tree will be objects of type DistPackage and the values will be list of ReqPackage objects. :param dict index: dist index ie. index of pkgs by their keys :returns: tree of pkgs and their dependencies :rtype: dict """ return dict((p, [ReqPackage(r, index.get(r.key)) for r in p.requires()]) for p in index.values())
Sorts the dict representation of the tree The root packages as well as the intermediate packages are sorted in the alphabetical order of the package names. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: sorted tree :rtype: collections.OrderedDict def sorted_tree(tree): """Sorts the dict representation of the tree The root packages as well as the intermediate packages are sorted in the alphabetical order of the package names. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: sorted tree :rtype: collections.OrderedDict """ return OrderedDict(sorted([(k, sorted(v, key=attrgetter('key'))) for k, v in tree.items()], key=lambda kv: kv[0].key))
Find a root in a tree by it's key :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :param str key: key of the root node to find :returns: a root node if found else None :rtype: mixed def find_tree_root(tree, key): """Find a root in a tree by it's key :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :param str key: key of the root node to find :returns: a root node if found else None :rtype: mixed """ result = [p for p in tree.keys() if p.key == key] assert len(result) in [0, 1] return None if len(result) == 0 else result[0]
Reverse the dependency tree. ie. the keys of the resulting dict are objects of type ReqPackage and the values are lists of DistPackage objects. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: reversed tree :rtype: dict def reverse_tree(tree): """Reverse the dependency tree. ie. the keys of the resulting dict are objects of type ReqPackage and the values are lists of DistPackage objects. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: reversed tree :rtype: dict """ rtree = defaultdict(list) child_keys = set(c.key for c in flatten(tree.values())) for k, vs in tree.items(): for v in vs: node = find_tree_root(rtree, v.key) or v rtree[node].append(k.as_required_by(v)) if k.key not in child_keys: rtree[k.as_requirement()] = [] return rtree
Guess the version of a pkg when pip doesn't provide it :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string def guess_version(pkg_key, default='?'): """Guess the version of a pkg when pip doesn't provide it :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string """ try: m = import_module(pkg_key) except ImportError: return default else: return getattr(m, '__version__', default)
Convert tree to string representation :param dict tree: the package tree :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies :param set show_only: set of select packages to be shown in the output. This is optional arg, default: None. :param bool frozen: whether or not show the names of the pkgs in the output that's favourable to pip --freeze :param set exclude: set of select packages to be excluded from the output. This is optional arg, default: None. :returns: string representation of the tree :rtype: str def render_tree(tree, list_all=True, show_only=None, frozen=False, exclude=None): """Convert tree to string representation :param dict tree: the package tree :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies :param set show_only: set of select packages to be shown in the output. This is optional arg, default: None. :param bool frozen: whether or not show the names of the pkgs in the output that's favourable to pip --freeze :param set exclude: set of select packages to be excluded from the output. This is optional arg, default: None. :returns: string representation of the tree :rtype: str """ tree = sorted_tree(tree) branch_keys = set(r.key for r in flatten(tree.values())) nodes = tree.keys() use_bullets = not frozen key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) if show_only: nodes = [p for p in nodes if p.key in show_only or p.project_name in show_only] elif not list_all: nodes = [p for p in nodes if p.key not in branch_keys] def aux(node, parent=None, indent=0, chain=None): if exclude and (node.key in exclude or node.project_name in exclude): return [] if chain is None: chain = [node.project_name] node_str = node.render(parent, frozen) if parent: prefix = ' '*indent + ('- ' if use_bullets else '') node_str = prefix + node_str result = [node_str] children = [aux(c, node, indent=indent+2, chain=chain+[c.project_name]) for c in get_children(node) if c.project_name not in chain] result += list(flatten(children)) return result lines = flatten([aux(p) for p in nodes]) return '\n'.join(lines)
Converts the tree into a flat json representation. The json repr will be a list of hashes, each hash having 2 fields: - package - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str def render_json(tree, indent): """Converts the tree into a flat json representation. The json repr will be a list of hashes, each hash having 2 fields: - package - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str """ return json.dumps([{'package': k.as_dict(), 'dependencies': [v.as_dict() for v in vs]} for k, vs in tree.items()], indent=indent)
Converts the tree into a nested json representation. The json repr will be a list of hashes, each hash having the following fields: - package_name - key - required_version - installed_version - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str def render_json_tree(tree, indent): """Converts the tree into a nested json representation. The json repr will be a list of hashes, each hash having the following fields: - package_name - key - required_version - installed_version - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str """ tree = sorted_tree(tree) branch_keys = set(r.key for r in flatten(tree.values())) nodes = [p for p in tree.keys() if p.key not in branch_keys] key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) def aux(node, parent=None, chain=None): if chain is None: chain = [node.project_name] d = node.as_dict() if parent: d['required_version'] = node.version_spec if node.version_spec else 'Any' else: d['required_version'] = d['installed_version'] d['dependencies'] = [ aux(c, parent=node, chain=chain+[c.project_name]) for c in get_children(node) if c.project_name not in chain ] return d return json.dumps([aux(p) for p in nodes], indent=indent)
Output dependency graph as one of the supported GraphViz output formats. :param dict tree: dependency graph :param string output_format: output format :returns: representation of tree in the specified output format :rtype: str or binary representation depending on the output format def dump_graphviz(tree, output_format='dot'): """Output dependency graph as one of the supported GraphViz output formats. :param dict tree: dependency graph :param string output_format: output format :returns: representation of tree in the specified output format :rtype: str or binary representation depending on the output format """ try: from graphviz import backend, Digraph except ImportError: print('graphviz is not available, but necessary for the output ' 'option. Please install it.', file=sys.stderr) sys.exit(1) if output_format not in backend.FORMATS: print('{0} is not a supported output format.'.format(output_format), file=sys.stderr) print('Supported formats are: {0}'.format( ', '.join(sorted(backend.FORMATS))), file=sys.stderr) sys.exit(1) graph = Digraph(format=output_format) for package, deps in tree.items(): project_name = package.project_name label = '{0}\n{1}'.format(project_name, package.version) graph.node(project_name, label=label) for dep in deps: label = dep.version_spec if not label: label = 'any' graph.edge(project_name, dep.project_name, label=label) # Allow output of dot format, even if GraphViz isn't installed. if output_format == 'dot': return graph.source # As it's unknown if the selected output format is binary or not, try to # decode it as UTF8 and only print it out in binary if that's not possible. try: return graph.pipe().decode('utf-8') except UnicodeDecodeError: return graph.pipe()
Dump the data generated by GraphViz to stdout. :param dump_output: The output from dump_graphviz def print_graphviz(dump_output): """Dump the data generated by GraphViz to stdout. :param dump_output: The output from dump_graphviz """ if hasattr(dump_output, 'encode'): print(dump_output) else: with os.fdopen(sys.stdout.fileno(), 'wb') as bytestream: bytestream.write(dump_output)
Returns dependencies which are not present or conflict with the requirements of other packages. e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed :param tree: the requirements tree (dict) :returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage :rtype: dict def conflicting_deps(tree): """Returns dependencies which are not present or conflict with the requirements of other packages. e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed :param tree: the requirements tree (dict) :returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage :rtype: dict """ conflicting = defaultdict(list) for p, rs in tree.items(): for req in rs: if req.is_conflicting(): conflicting[p].append(req) return conflicting
Return cyclic dependencies as list of tuples :param list pkgs: pkg_resources.Distribution instances :param dict pkg_index: mapping of pkgs with their respective keys :returns: list of tuples representing cyclic dependencies :rtype: generator def cyclic_deps(tree): """Return cyclic dependencies as list of tuples :param list pkgs: pkg_resources.Distribution instances :param dict pkg_index: mapping of pkgs with their respective keys :returns: list of tuples representing cyclic dependencies :rtype: generator """ key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) cyclic = [] for p, rs in tree.items(): for req in rs: if p.key in map(attrgetter('key'), get_children(req)): cyclic.append((p, req, p)) return cyclic
If installed version conflicts with required version def is_conflicting(self): """If installed version conflicts with required version""" # unknown installed version is also considered conflicting if self.installed_version == self.UNKNOWN_VERSION: return True ver_spec = (self.version_spec if self.version_spec else '') req_version_str = '{0}{1}'.format(self.project_name, ver_spec) req_obj = pkg_resources.Requirement.parse(req_version_str) return self.installed_version not in req_obj
Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. def check_against_chunks(self, chunks): # type: (Iterator[bytes]) -> None """Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. """ gots = {} for hash_name in iterkeys(self._allowed): try: gots[hash_name] = hashlib.new(hash_name) except (ValueError, TypeError): raise InstallationError('Unknown hash name: %s' % hash_name) for chunk in chunks: for hash in itervalues(gots): hash.update(chunk) for hash_name, got in iteritems(gots): if got.hexdigest() in self._allowed[hash_name]: return self._raise(gots)
A converter that allows to replace ``None`` values by *default* or the result of *factory*. :param default: Value to be used if ``None`` is passed. Passing an instance of :class:`attr.Factory` is supported, however the ``takes_self`` option is *not*. :param callable factory: A callable that takes not parameters whose result is used if ``None`` is passed. :raises TypeError: If **neither** *default* or *factory* is passed. :raises TypeError: If **both** *default* and *factory* are passed. :raises ValueError: If an instance of :class:`attr.Factory` is passed with ``takes_self=True``. .. versionadded:: 18.2.0 def default_if_none(default=NOTHING, factory=None): """ A converter that allows to replace ``None`` values by *default* or the result of *factory*. :param default: Value to be used if ``None`` is passed. Passing an instance of :class:`attr.Factory` is supported, however the ``takes_self`` option is *not*. :param callable factory: A callable that takes not parameters whose result is used if ``None`` is passed. :raises TypeError: If **neither** *default* or *factory* is passed. :raises TypeError: If **both** *default* and *factory* are passed. :raises ValueError: If an instance of :class:`attr.Factory` is passed with ``takes_self=True``. .. versionadded:: 18.2.0 """ if default is NOTHING and factory is None: raise TypeError("Must pass either `default` or `factory`.") if default is not NOTHING and factory is not None: raise TypeError( "Must pass either `default` or `factory` but not both." ) if factory is not None: default = Factory(factory) if isinstance(default, Factory): if default.takes_self: raise ValueError( "`takes_self` is not supported by default_if_none." ) def default_if_none_converter(val): if val is not None: return val return default.factory() else: def default_if_none_converter(val): if val is not None: return val return default return default_if_none_converter
Removes nodes by index from an errorpath, relatively to the basepaths of self. :param errors: A list of :class:`errors.ValidationError` instances. :param dp_items: A list of integers, pointing at the nodes to drop from the :attr:`document_path`. :param sp_items: Alike ``dp_items``, but for :attr:`schema_path`. def _drop_nodes_from_errorpaths(self, _errors, dp_items, sp_items): """ Removes nodes by index from an errorpath, relatively to the basepaths of self. :param errors: A list of :class:`errors.ValidationError` instances. :param dp_items: A list of integers, pointing at the nodes to drop from the :attr:`document_path`. :param sp_items: Alike ``dp_items``, but for :attr:`schema_path`. """ dp_basedepth = len(self.document_path) sp_basedepth = len(self.schema_path) for error in _errors: for i in sorted(dp_items, reverse=True): error.document_path = \ drop_item_from_tuple(error.document_path, dp_basedepth + i) for i in sorted(sp_items, reverse=True): error.schema_path = \ drop_item_from_tuple(error.schema_path, sp_basedepth + i) if error.child_errors: self._drop_nodes_from_errorpaths(error.child_errors, dp_items, sp_items)
Searches for a field as defined by path. This method is used by the ``dependency`` evaluation logic. :param path: Path elements are separated by a ``.``. A leading ``^`` indicates that the path relates to the document root, otherwise it relates to the currently evaluated document, which is possibly a subdocument. The sequence ``^^`` at the start will be interpreted as a literal ``^``. :type path: :class:`str` :returns: Either the found field name and its value or :obj:`None` for both. :rtype: A two-value :class:`tuple`. def _lookup_field(self, path): """ Searches for a field as defined by path. This method is used by the ``dependency`` evaluation logic. :param path: Path elements are separated by a ``.``. A leading ``^`` indicates that the path relates to the document root, otherwise it relates to the currently evaluated document, which is possibly a subdocument. The sequence ``^^`` at the start will be interpreted as a literal ``^``. :type path: :class:`str` :returns: Either the found field name and its value or :obj:`None` for both. :rtype: A two-value :class:`tuple`. """ if path.startswith('^'): path = path[1:] context = self.document if path.startswith('^') \ else self.root_document else: context = self.document parts = path.split('.') for part in parts: if part not in context: return None, None context = context.get(part) return parts[-1], context
The constraints that can be used for the 'type' rule. Type: A tuple of strings. def types(cls): """ The constraints that can be used for the 'type' rule. Type: A tuple of strings. """ redundant_types = \ set(cls.types_mapping) & set(cls._types_from_methods) if redundant_types: warn("These types are defined both with a method and in the" "'types_mapping' property of this validator: %s" % redundant_types) return tuple(cls.types_mapping) + cls._types_from_methods
Drops rules from the queue of the rules that still need to be evaluated for the currently processed field. If no arguments are given, the whole queue is emptied. def _drop_remaining_rules(self, *rules): """ Drops rules from the queue of the rules that still need to be evaluated for the currently processed field. If no arguments are given, the whole queue is emptied. """ if rules: for rule in rules: try: self._remaining_rules.remove(rule) except ValueError: pass else: self._remaining_rules = []
Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param always_return_document: Return the document, even if an error occurred. Defaults to: ``False``. :type always_return_document: :class:`bool` :return: A normalized copy of the provided mapping or :obj:`None` if an error occurred during normalization. def normalized(self, document, schema=None, always_return_document=False): """ Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param always_return_document: Return the document, even if an error occurred. Defaults to: ``False``. :type always_return_document: :class:`bool` :return: A normalized copy of the provided mapping or :obj:`None` if an error occurred during normalization. """ self.__init_processing(document, schema) self.__normalize_mapping(self.document, self.schema) self.error_handler.end(self) if self._errors and not always_return_document: return None else: return self.document
{'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} def _normalize_coerce(self, mapping, schema): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ error = errors.COERCION_FAILED for field in mapping: if field in schema and 'coerce' in schema[field]: mapping[field] = self.__normalize_coerce( schema[field]['coerce'], field, mapping[field], schema[field].get('nullable', False), error) elif isinstance(self.allow_unknown, Mapping) and \ 'coerce' in self.allow_unknown: mapping[field] = self.__normalize_coerce( self.allow_unknown['coerce'], field, mapping[field], self.allow_unknown.get('nullable', False), error)
{'type': 'boolean'} def _normalize_purge_unknown(mapping, schema): """ {'type': 'boolean'} """ for field in tuple(mapping): if field not in schema: del mapping[field] return mapping
{'type': 'hashable'} def _normalize_rename(self, mapping, schema, field): """ {'type': 'hashable'} """ if 'rename' in schema[field]: mapping[schema[field]['rename']] = mapping[field] del mapping[field]
{'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} def _normalize_rename_handler(self, mapping, schema, field): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ if 'rename_handler' not in schema[field]: return new_name = self.__normalize_coerce( schema[field]['rename_handler'], field, field, False, errors.RENAMING_FAILED) if new_name != field: mapping[new_name] = mapping[field] del mapping[field]
{'oneof': [ {'type': 'callable'}, {'type': 'string'} ]} def _normalize_default_setter(self, mapping, schema, field): """ {'oneof': [ {'type': 'callable'}, {'type': 'string'} ]} """ if 'default_setter' in schema[field]: setter = schema[field]['default_setter'] if isinstance(setter, _str_type): setter = self.__get_rule_handler('normalize_default_setter', setter) mapping[field] = setter(mapping)
Normalizes and validates a mapping against a validation-schema of defined rules. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param update: If ``True``, required fields won't be checked. :type update: :class:`bool` :param normalize: If ``True``, normalize the document before validation. :type normalize: :class:`bool` :return: ``True`` if validation succeeds, otherwise ``False``. Check the :func:`errors` property for a list of processing errors. :rtype: :class:`bool` def validate(self, document, schema=None, update=False, normalize=True): """ Normalizes and validates a mapping against a validation-schema of defined rules. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param update: If ``True``, required fields won't be checked. :type update: :class:`bool` :param normalize: If ``True``, normalize the document before validation. :type normalize: :class:`bool` :return: ``True`` if validation succeeds, otherwise ``False``. Check the :func:`errors` property for a list of processing errors. :rtype: :class:`bool` """ self.update = update self._unrequired_by_excludes = set() self.__init_processing(document, schema) if normalize: self.__normalize_mapping(self.document, self.schema) for field in self.document: if self.ignore_none_values and self.document[field] is None: continue definitions = self.schema.get(field) if definitions is not None: self.__validate_definitions(definitions, field) else: self.__validate_unknown_fields(field) if not self.update: self.__validate_required_fields(self.document) self.error_handler.end(self) return not bool(self._errors)
Wrapper around :meth:`~cerberus.Validator.validate` that returns the normalized and validated document or :obj:`None` if validation failed. def validated(self, *args, **kwargs): """ Wrapper around :meth:`~cerberus.Validator.validate` that returns the normalized and validated document or :obj:`None` if validation failed. """ always_return_document = kwargs.pop('always_return_document', False) self.validate(*args, **kwargs) if self._errors and not always_return_document: return None else: return self.document
{'type': 'list'} def _validate_allowed(self, allowed_values, field, value): """ {'type': 'list'} """ if isinstance(value, Iterable) and not isinstance(value, _str_type): unallowed = set(value) - set(allowed_values) if unallowed: self._error(field, errors.UNALLOWED_VALUES, list(unallowed)) else: if value not in allowed_values: self._error(field, errors.UNALLOWED_VALUE, value)
{'type': 'boolean'} def _validate_empty(self, empty, field, value): """ {'type': 'boolean'} """ if isinstance(value, Iterable) and len(value) == 0: self._drop_remaining_rules( 'allowed', 'forbidden', 'items', 'minlength', 'maxlength', 'regex', 'validator') if not empty: self._error(field, errors.EMPTY_NOT_ALLOWED)
{'type': ('hashable', 'list'), 'schema': {'type': 'hashable'}} def _validate_excludes(self, excludes, field, value): """ {'type': ('hashable', 'list'), 'schema': {'type': 'hashable'}} """ if isinstance(excludes, Hashable): excludes = [excludes] # Save required field to be checked latter if 'required' in self.schema[field] and self.schema[field]['required']: self._unrequired_by_excludes.add(field) for exclude in excludes: if (exclude in self.schema and 'required' in self.schema[exclude] and self.schema[exclude]['required']): self._unrequired_by_excludes.add(exclude) if [True for key in excludes if key in self.document]: # Wrap each field in `excludes` list between quotes exclusion_str = ', '.join("'{0}'" .format(word) for word in excludes) self._error(field, errors.EXCLUDES_FIELD, exclusion_str)
{'type': 'list'} def _validate_forbidden(self, forbidden_values, field, value): """ {'type': 'list'} """ if isinstance(value, _str_type): if value in forbidden_values: self._error(field, errors.FORBIDDEN_VALUE, value) elif isinstance(value, Sequence): forbidden = set(value) & set(forbidden_values) if forbidden: self._error(field, errors.FORBIDDEN_VALUES, list(forbidden)) elif isinstance(value, int): if value in forbidden_values: self._error(field, errors.FORBIDDEN_VALUE, value)
Validates value against all definitions and logs errors according to the operator. def __validate_logical(self, operator, definitions, field, value): """ Validates value against all definitions and logs errors according to the operator. """ valid_counter = 0 _errors = errors.ErrorList() for i, definition in enumerate(definitions): schema = {field: definition.copy()} for rule in ('allow_unknown', 'type'): if rule not in schema[field] and rule in self.schema[field]: schema[field][rule] = self.schema[field][rule] if 'allow_unknown' not in schema[field]: schema[field]['allow_unknown'] = self.allow_unknown validator = self._get_child_validator( schema_crumb=(field, operator, i), schema=schema, allow_unknown=True) if validator(self.document, update=self.update, normalize=False): valid_counter += 1 else: self._drop_nodes_from_errorpaths(validator._errors, [], [3]) _errors.extend(validator._errors) return valid_counter, _errors
{'type': 'list', 'logical': 'anyof'} def _validate_anyof(self, definitions, field, value): """ {'type': 'list', 'logical': 'anyof'} """ valids, _errors = \ self.__validate_logical('anyof', definitions, field, value) if valids < 1: self._error(field, errors.ANYOF, _errors, valids, len(definitions))
{'type': 'list', 'logical': 'allof'} def _validate_allof(self, definitions, field, value): """ {'type': 'list', 'logical': 'allof'} """ valids, _errors = \ self.__validate_logical('allof', definitions, field, value) if valids < len(definitions): self._error(field, errors.ALLOF, _errors, valids, len(definitions))
{'type': 'list', 'logical': 'noneof'} def _validate_noneof(self, definitions, field, value): """ {'type': 'list', 'logical': 'noneof'} """ valids, _errors = \ self.__validate_logical('noneof', definitions, field, value) if valids > 0: self._error(field, errors.NONEOF, _errors, valids, len(definitions))
{'type': 'list', 'logical': 'oneof'} def _validate_oneof(self, definitions, field, value): """ {'type': 'list', 'logical': 'oneof'} """ valids, _errors = \ self.__validate_logical('oneof', definitions, field, value) if valids != 1: self._error(field, errors.ONEOF, _errors, valids, len(definitions))
{'nullable': False } def _validate_max(self, max_value, field, value): """ {'nullable': False } """ try: if value > max_value: self._error(field, errors.MAX_VALUE) except TypeError: pass
{'nullable': False } def _validate_min(self, min_value, field, value): """ {'nullable': False } """ try: if value < min_value: self._error(field, errors.MIN_VALUE) except TypeError: pass
{'type': 'integer'} def _validate_maxlength(self, max_length, field, value): """ {'type': 'integer'} """ if isinstance(value, Iterable) and len(value) > max_length: self._error(field, errors.MAX_LENGTH, len(value))
{'type': 'integer'} def _validate_minlength(self, min_length, field, value): """ {'type': 'integer'} """ if isinstance(value, Iterable) and len(value) < min_length: self._error(field, errors.MIN_LENGTH, len(value))
{'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} def _validate_keyschema(self, schema, field, value): """ {'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} """ if isinstance(value, Mapping): validator = self._get_child_validator( document_crumb=field, schema_crumb=(field, 'keyschema'), schema=dict(((k, schema) for k in value.keys()))) if not validator(dict(((k, k) for k in value.keys())), normalize=False): self._drop_nodes_from_errorpaths(validator._errors, [], [2, 4]) self._error(field, errors.KEYSCHEMA, validator._errors)
{'type': 'boolean'} def _validate_readonly(self, readonly, field, value): """ {'type': 'boolean'} """ if readonly: if not self._is_normalized: self._error(field, errors.READONLY_FIELD) # If the document was normalized (and therefore already been # checked for readonly fields), we still have to return True # if an error was filed. has_error = errors.READONLY_FIELD in \ self.document_error_tree.fetch_errors_from( self.document_path + (field,)) if self._is_normalized and has_error: self._drop_remaining_rules()
{'type': 'string'} def _validate_regex(self, pattern, field, value): """ {'type': 'string'} """ if not isinstance(value, _str_type): return if not pattern.endswith('$'): pattern += '$' re_obj = re.compile(pattern) if not re_obj.match(value): self._error(field, errors.REGEX_MISMATCH)
Validates that required fields are not missing. :param document: The document being validated. def __validate_required_fields(self, document): """ Validates that required fields are not missing. :param document: The document being validated. """ try: required = set(field for field, definition in self.schema.items() if self._resolve_rules_set(definition). get('required') is True) except AttributeError: if self.is_child and self.schema_path[-1] == 'schema': raise _SchemaRuleTypeError else: raise required -= self._unrequired_by_excludes missing = required - set(field for field in document if document.get(field) is not None or not self.ignore_none_values) for field in missing: self._error(field, errors.REQUIRED_FIELD) # At least on field from self._unrequired_by_excludes should be # present in document if self._unrequired_by_excludes: fields = set(field for field in document if document.get(field) is not None) if self._unrequired_by_excludes.isdisjoint(fields): for field in self._unrequired_by_excludes - fields: self._error(field, errors.REQUIRED_FIELD)
{'type': ['dict', 'string'], 'anyof': [{'validator': 'schema'}, {'validator': 'bulk_schema'}]} def _validate_schema(self, schema, field, value): """ {'type': ['dict', 'string'], 'anyof': [{'validator': 'schema'}, {'validator': 'bulk_schema'}]} """ if schema is None: return if isinstance(value, Sequence) and not isinstance(value, _str_type): self.__validate_schema_sequence(field, schema, value) elif isinstance(value, Mapping): self.__validate_schema_mapping(field, schema, value)
{'type': ['string', 'list'], 'validator': 'type'} def _validate_type(self, data_type, field, value): """ {'type': ['string', 'list'], 'validator': 'type'} """ if not data_type: return types = (data_type,) if isinstance(data_type, _str_type) else data_type for _type in types: # TODO remove this block on next major release # this implementation still supports custom type validation methods type_definition = self.types_mapping.get(_type) if type_definition is not None: matched = isinstance(value, type_definition.included_types) \ and not isinstance(value, type_definition.excluded_types) else: type_handler = self.__get_rule_handler('validate_type', _type) matched = type_handler(value) if matched: return # TODO uncomment this block on next major release # when _validate_type_* methods were deprecated: # type_definition = self.types_mapping[_type] # if isinstance(value, type_definition.included_types) \ # and not isinstance(value, type_definition.excluded_types): # noqa 501 # return self._error(field, errors.BAD_TYPE) self._drop_remaining_rules()
{'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} def _validate_validator(self, validator, field, value): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ if isinstance(validator, _str_type): validator = self.__get_rule_handler('validator', validator) validator(field, value) elif isinstance(validator, Iterable): for v in validator: self._validate_validator(v, field, value) else: validator(field, value, self._error)
{'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} def _validate_valueschema(self, schema, field, value): """ {'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} """ schema_crumb = (field, 'valueschema') if isinstance(value, Mapping): validator = self._get_child_validator( document_crumb=field, schema_crumb=schema_crumb, schema=dict((k, schema) for k in value)) validator(value, update=self.update, normalize=False) if validator._errors: self._drop_nodes_from_errorpaths(validator._errors, [], [2]) self._error(field, errors.VALUESCHEMA, validator._errors)
Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers. def make_attrgetter(environment, attribute, postprocess=None): """Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers. """ if attribute is None: attribute = [] elif isinstance(attribute, string_types): attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')] else: attribute = [attribute] def attrgetter(item): for part in attribute: item = environment.getitem(item, part) if postprocess is not None: item = postprocess(item) return item return attrgetter
Enforce HTML escaping. This will probably double escape variables. def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(text_type(value))
Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables. .. versionadded:: 2.7 def do_urlencode(value): """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables. .. versionadded:: 2.7 """ itemiter = None if isinstance(value, dict): itemiter = iteritems(value) elif not isinstance(value, string_types): try: itemiter = iter(value) except TypeError: pass if itemiter is None: return unicode_urlencode(value) return u'&'.join(unicode_urlencode(k) + '=' + unicode_urlencode(v, for_qs=True) for k, v in itemiter)
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. def do_title(s): """Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. """ return ''.join( [item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_unicode(s)) if item])
Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value: .. sourcecode:: jinja {% for item in mydict|dictsort %} sort the dict by key, case insensitive {% for item in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for item in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for item in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive def do_dictsort(value, case_sensitive=False, by='key', reverse=False): """Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value: .. sourcecode:: jinja {% for item in mydict|dictsort %} sort the dict by key, case insensitive {% for item in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for item in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for item in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive """ if by == 'key': pos = 0 elif by == 'value': pos = 1 else: raise FilterArgumentError( 'You can only sort by either "key" or "value"' ) def sort_func(item): value = item[pos] if not case_sensitive: value = ignore_case(value) return value return sorted(value.items(), key=sort_func, reverse=reverse)
Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the `attribute` parameter: .. sourcecode:: jinja {% for item in iterable|sort(attribute='date') %} ... {% endfor %} .. versionchanged:: 2.6 The `attribute` parameter was added. def do_sort( environment, value, reverse=False, case_sensitive=False, attribute=None ): """Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the `attribute` parameter: .. sourcecode:: jinja {% for item in iterable|sort(attribute='date') %} ... {% endfor %} .. versionchanged:: 2.6 The `attribute` parameter was added. """ key_func = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) return sorted(value, key=key_func, reverse=reverse)
Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. def do_unique(environment, value, case_sensitive=False, attribute=None): """Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. """ getter = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) seen = set() for item in value: key = getter(item) if key not in seen: seen.add(key) yield item
Return the smallest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|min }} -> 1 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. def do_min(environment, value, case_sensitive=False, attribute=None): """Return the smallest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|min }} -> 1 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. """ return _min_or_max(environment, value, min, case_sensitive, attribute)
Return the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. def do_max(environment, value, case_sensitive=False, attribute=None): """Return the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. """ return _min_or_max(environment, value, max, case_sensitive, attribute)
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added. def do_join(eval_ctx, value, d=u'', attribute=None): """Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added. """ if attribute is not None: value = imap(make_attrgetter(eval_ctx.environment, attribute), value) # no automatic escaping? joining is a lot eaiser then if not eval_ctx.autoescape: return text_type(d).join(imap(text_type, value)) # if the delimiter doesn't have an html representation we check # if any of the items has. If yes we do a coercion to Markup if not hasattr(d, '__html__'): value = list(value) do_escape = False for idx, item in enumerate(value): if hasattr(item, '__html__'): do_escape = True else: value[idx] = text_type(item) if do_escape: d = escape(d) else: d = text_type(d) return d.join(value) # no html involved, to normal joining return soft_unicode(d).join(imap(soft_unicode, value))