id
stringlengths
23
25
content
stringlengths
1.16k
88k
max_stars_repo_path
stringlengths
12
48
codereval_python_data_101
Create, populate and return the VersioneerConfig() object. def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "src/prestoplot/_version.py" cfg.verbose = False return cfg # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.22 (https://github.com/python-versioneer/python-versioneer) """Git implementation of _version.py.""" import errno import functools import os import re import subprocess import sys from typing import Callable, Dict def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "src/prestoplot/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen( [command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs ) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return { "version": dirname[len(parentdir_prefix) :], "full-revisionid": None, "dirty": False, "error": None, "date": None, } rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print( "Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix) ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r"\d", r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix) :] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r"\d", r): continue if verbose: print("picking %s" % r) return { "version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date, } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return { "version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None, } @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") MATCH_ARGS = ["--match", "%s*" % tag_prefix] if tag_prefix else [] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner( GITS, ["describe", "--tags", "--dirty", "--always", "--long", *MATCH_ARGS], cwd=root, ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( full_tag, tag_prefix, ) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) else: rendered += ".post0.dev%d" % (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return { "version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None, } if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return { "version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date"), } def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: return { "version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None, } try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return { "version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None, }
src/prestoplot/_version.py
codereval_python_data_102
Create decorator to mark a method as the handler of a VCS. def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.22 (https://github.com/python-versioneer/python-versioneer) """Git implementation of _version.py.""" import errno import functools import os import re import subprocess import sys from typing import Callable, Dict def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "src/prestoplot/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen( [command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs ) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return { "version": dirname[len(parentdir_prefix) :], "full-revisionid": None, "dirty": False, "error": None, "date": None, } rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print( "Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix) ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r"\d", r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix) :] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r"\d", r): continue if verbose: print("picking %s" % r) return { "version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date, } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return { "version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None, } @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") MATCH_ARGS = ["--match", "%s*" % tag_prefix] if tag_prefix else [] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner( GITS, ["describe", "--tags", "--dirty", "--always", "--long", *MATCH_ARGS], cwd=root, ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( full_tag, tag_prefix, ) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) else: rendered += ".post0.dev%d" % (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return { "version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None, } if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return { "version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date"), } def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: return { "version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None, } try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return { "version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None, }
src/prestoplot/_version.py
codereval_python_data_103
Validate storage root hierarchy. Returns: num_objects - number of objects checked good_objects - number of objects checked that were found to be valid def validate_hierarchy(self, validate_objects=True, check_digests=True, show_warnings=False): """Validate storage root hierarchy. Returns: num_objects - number of objects checked good_objects - number of objects checked that were found to be valid """ num_objects = 0 good_objects = 0 for dirpath in self.object_paths(): if validate_objects: validator = Validator(check_digests=check_digests, lax_digests=self.lax_digests, show_warnings=show_warnings) if validator.validate(ocfl_opendir(self.root_fs, dirpath)): good_objects += 1 else: logging.info("Object at %s in INVALID", dirpath) messages = validator.status_str(prefix='[[' + dirpath + ']]') if messages != '': print(messages) num_objects += 1 return num_objects, good_objects """OCFL Storage Root library. This code uses PyFilesystem (import fs) exclusively for access to files. This should enable application beyond the operating system filesystem. """ import json import logging import re import fs from fs.copy import copy_dir from .disposition import get_dispositor from .namaste import find_namastes, Namaste from .object import Object from .pyfs import open_fs, ocfl_walk, ocfl_opendir from .validator import Validator from .validation_logger import ValidationLogger class StoreException(Exception): """Exception class for OCFL Storage Root.""" class Store(): """Class for handling OCFL Storage Root and include OCFL Objects.""" def __init__(self, root=None, disposition=None, lax_digests=False): """Initialize OCFL Storage Root.""" self.root = root self.disposition = disposition self.lax_digests = lax_digests self._dispositor = None # self.declaration_tvalue = 'ocfl_1.0' self.spec_file = 'ocfl_1.0.txt' self.layout_file = 'ocfl_layout.json' self.registered_extensions = [ # '0002-flat-direct-storage-layout', # not included because doesn't have config '0003-hash-and-id-n-tuple-storage-layout', '0004-hashed-n-tuple-storage-layout' ] # self.root_fs = None self.num_traversal_errors = 0 self.extension = None self.description = None self.log = None self.num_objects = 0 self.good_objects = 0 def open_root_fs(self, create=False): """Open pyfs filesystem for this OCFL storage root.""" try: self.root_fs = open_fs(self.root, create=create) except (fs.opener.errors.OpenerError, fs.errors.CreateFailed) as e: raise StoreException("Failed to open OCFL storage root filesystem '%s' (%s)" % (self.root, str(e))) @property def dispositor(self): """Instance of dispositor class. Lazily initialized. """ if not self._dispositor: self._dispositor = get_dispositor(disposition=self.disposition) return self._dispositor def traversal_error(self, code, **kwargs): """Record error traversing OCFL storage root.""" self.num_traversal_errors += 1 if self.log is None: # FIXME - What to do in non-validator context? args = ', '.join('{0}={1!r}'.format(k, v) for k, v in kwargs.items()) logging.error("Traversal error %s - %s", code, args) else: self.log.error(code, **kwargs) def object_path(self, identifier): """Path to OCFL object with given identifier relative to the OCFL storage root.""" return self.dispositor.identifier_to_path(identifier) def initialize(self): """Create and initialize a new OCFL storage root.""" (parent, root_dir) = fs.path.split(self.root) parent_fs = open_fs(parent) if parent_fs.exists(root_dir): raise StoreException("OCFL storage root %s already exists, aborting!" % (self.root)) self.root_fs = parent_fs.makedir(root_dir) logging.debug("Created OCFL storage root at %s", self.root) # Create root declaration Namaste(d=0, content=self.declaration_tvalue).write(pyfs=self.root_fs) # Create a layout declaration if self.disposition is not None: with self.root_fs.open(self.layout_file, 'w') as fh: layout = {'extension': self.disposition, 'description': "Non-standard layout from ocfl-py disposition -- FIXME"} json.dump(layout, fh, sort_keys=True, indent=2) logging.info("Created OCFL storage root %s", self.root) def check_root_structure(self): """Check the OCFL storage root structure. Assumed that self.root_fs filesystem is available. Raises StoreException if there is an error. """ # Storage root declaration namastes = find_namastes(0, pyfs=self.root_fs) if len(namastes) == 0: raise StoreException("Storage root %s lacks required 0= declaration file" % (self.root)) if len(namastes) > 1: raise StoreException("Storage root %s has more than one 0= style declaration file" % (self.root)) if namastes[0].tvalue != self.declaration_tvalue: raise StoreException("Storage root %s declaration file not as expected, got %s" % (self.root, namastes[0].filename)) if not namastes[0].content_ok(pyfs=self.root_fs): raise StoreException("Storage root %s required declaration file %s has invalid content" % (self.root, namastes[0].filename)) # Specification file and layout file if self.root_fs.exists(self.spec_file) and not self.root_fs.isfile(self.spec_file): raise StoreException("Storage root %s includes a specification entry that isn't a file" % (self.root)) self.extension, self.description = self.parse_layout_file() # Other files are allowed... return True def parse_layout_file(self): """Read and parse layout file in OCFL storage root. Returns: - (extension, description) strings on success, - (None, None) if there is now layout file (it is optional) - otherwise raises a StoreException. """ if self.root_fs.exists(self.layout_file): try: with self.root_fs.open(self.layout_file) as fh: layout = json.load(fh) if not isinstance(layout, dict): raise StoreException("Storage root %s has layout file that isn't a JSON object" % (self.root)) if ('extension' not in layout or not isinstance(layout['extension'], str) or 'description' not in layout or not isinstance(layout['description'], str)): raise StoreException("Storage root %s has layout file doesn't have required extension and description string entries" % (self.root)) return layout['extension'], layout['description'] except Exception as e: # FIXME - more specific? raise StoreException("OCFL storage root %s has layout file that can't be read (%s)" % (self.root, str(e))) else: return None, None def object_paths(self): """Generate object paths for every obect in the OCFL storage root. Yields (dirpath) that is the path to the directory for each object located, relative to the OCFL storage root and without a preceding /. Will log any errors seen while traversing the directory tree under the storage root. """ for (dirpath, dirs, files) in ocfl_walk(self.root_fs, is_storage_root=True): if dirpath == '/': if 'extensions' in dirs: self.validate_extensions_dir() dirs.remove('extensions') # Ignore any other files in storage root elif (len(dirs) + len(files)) == 0: self.traversal_error("E073", path=dirpath) elif len(files) == 0: pass # Just an intermediate directory else: # Is this directory an OCFL object? Look for any 0= file. zero_eqs = [file for file in files if file.startswith('0=')] if len(zero_eqs) > 1: self.traversal_error("E003d", path=dirpath) elif len(zero_eqs) == 1: declaration = zero_eqs[0] match = re.match(r'''0=ocfl_object_(\d+\.\d+)''', declaration) if match and match.group(1) == '1.0': yield dirpath.lstrip('/') elif match: self.traversal_error("E004a", path=dirpath, version=match.group(1)) else: self.traversal_error("E004b", path=dirpath, declaration=declaration) else: self.traversal_error("E072", path=dirpath) def validate_extensions_dir(self): """Validate content of extensions directory inside storage root. Validate the extensions directory by checking that there aren't any entries in the extensions directory that aren't directories themselves. Where there are extension directories they SHOULD be registered and this code relies up the registered_extensions property to list known storage root extensions. """ for entry in self.root_fs.scandir('extensions'): if entry.is_dir: if entry.name not in self.registered_extensions: self.log.warning('W901', entry=entry.name) # FIXME - No good warning code in spec else: self.traversal_error('E086', entry=entry.name) def list(self): """List contents of this OCFL storage root.""" self.open_root_fs() self.check_root_structure() self.num_objects = 0 for dirpath in self.object_paths(): with ocfl_opendir(self.root_fs, dirpath) as obj_fs: # Parse inventory to extract id identifier = Object(obj_fs=obj_fs).id_from_inventory() print("%s -- id=%s" % (dirpath, identifier)) self.num_objects += 1 # FIXME - maybe do some more stuff in here logging.info("Found %d OCFL Objects under root %s", self.num_objects, self.root) def validate_hierarchy(self, validate_objects=True, check_digests=True, show_warnings=False): """Validate storage root hierarchy. Returns: num_objects - number of objects checked good_objects - number of objects checked that were found to be valid """ num_objects = 0 good_objects = 0 for dirpath in self.object_paths(): if validate_objects: validator = Validator(check_digests=check_digests, lax_digests=self.lax_digests, show_warnings=show_warnings) if validator.validate(ocfl_opendir(self.root_fs, dirpath)): good_objects += 1 else: logging.info("Object at %s in INVALID", dirpath) messages = validator.status_str(prefix='[[' + dirpath + ']]') if messages != '': print(messages) num_objects += 1 return num_objects, good_objects def validate(self, validate_objects=True, check_digests=True, show_warnings=False, show_errors=True, lang='en'): """Validate OCFL storage root and optionally all objects.""" valid = True self.log = ValidationLogger(show_warnings=show_warnings, show_errors=show_errors, lang=lang) self.open_root_fs() try: self.check_root_structure() logging.info("Storage root structure is VALID") except StoreException as e: valid = False logging.info("Storage root structure is INVALID (%s)", str(e)) self.num_objects, self.good_objects = self.validate_hierarchy(validate_objects=validate_objects, check_digests=check_digests, show_warnings=show_warnings) if validate_objects: if self.good_objects == self.num_objects: logging.info("Objects checked: %d / %d are VALID", self.good_objects, self.num_objects) else: valid = False logging.info("Objects checked: %d / %d are INVALID", self.num_objects - self.good_objects, self.num_objects) else: logging.info("Not checking OCFL objects") print(str(self.log)) if self.num_traversal_errors > 0: valid = False logging.info("Encountered %d errors traversing storage root", self.num_traversal_errors) # FIXME - do some stuff in here if valid: logging.info("Storage root %s is VALID", self.root) else: logging.info("Storage root %s is INVALID", self.root) return valid def add(self, object_path): """Add pre-constructed object from object_path.""" self.open_root_fs() self.check_root_structure() # Sanity check o = Object() o.open_fs(object_path) inventory = o.parse_inventory() identifier = inventory['id'] # Now copy path = self.object_path(identifier) logging.info("Copying from %s to %s", object_path, fs.path.join(self.root, path)) try: copy_dir(o.obj_fs, '/', self.root_fs, path) logging.info("Copied") except Exception as e: logging.error("Copy failed: %s", str(e)) raise StoreException("Add object failed!")
ocfl/store.py
codereval_python_data_104
Create and initialize a new OCFL storage root. def initialize(self): """Create and initialize a new OCFL storage root.""" (parent, root_dir) = fs.path.split(self.root) parent_fs = open_fs(parent) if parent_fs.exists(root_dir): raise StoreException("OCFL storage root %s already exists, aborting!" % (self.root)) self.root_fs = parent_fs.makedir(root_dir) logging.debug("Created OCFL storage root at %s", self.root) # Create root declaration Namaste(d=0, content=self.declaration_tvalue).write(pyfs=self.root_fs) # Create a layout declaration if self.disposition is not None: with self.root_fs.open(self.layout_file, 'w') as fh: layout = {'extension': self.disposition, 'description': "Non-standard layout from ocfl-py disposition -- FIXME"} json.dump(layout, fh, sort_keys=True, indent=2) logging.info("Created OCFL storage root %s", self.root) """OCFL Storage Root library. This code uses PyFilesystem (import fs) exclusively for access to files. This should enable application beyond the operating system filesystem. """ import json import logging import re import fs from fs.copy import copy_dir from .disposition import get_dispositor from .namaste import find_namastes, Namaste from .object import Object from .pyfs import open_fs, ocfl_walk, ocfl_opendir from .validator import Validator from .validation_logger import ValidationLogger class StoreException(Exception): """Exception class for OCFL Storage Root.""" class Store(): """Class for handling OCFL Storage Root and include OCFL Objects.""" def __init__(self, root=None, disposition=None, lax_digests=False): """Initialize OCFL Storage Root.""" self.root = root self.disposition = disposition self.lax_digests = lax_digests self._dispositor = None # self.declaration_tvalue = 'ocfl_1.0' self.spec_file = 'ocfl_1.0.txt' self.layout_file = 'ocfl_layout.json' self.registered_extensions = [ # '0002-flat-direct-storage-layout', # not included because doesn't have config '0003-hash-and-id-n-tuple-storage-layout', '0004-hashed-n-tuple-storage-layout' ] # self.root_fs = None self.num_traversal_errors = 0 self.extension = None self.description = None self.log = None self.num_objects = 0 self.good_objects = 0 def open_root_fs(self, create=False): """Open pyfs filesystem for this OCFL storage root.""" try: self.root_fs = open_fs(self.root, create=create) except (fs.opener.errors.OpenerError, fs.errors.CreateFailed) as e: raise StoreException("Failed to open OCFL storage root filesystem '%s' (%s)" % (self.root, str(e))) @property def dispositor(self): """Instance of dispositor class. Lazily initialized. """ if not self._dispositor: self._dispositor = get_dispositor(disposition=self.disposition) return self._dispositor def traversal_error(self, code, **kwargs): """Record error traversing OCFL storage root.""" self.num_traversal_errors += 1 if self.log is None: # FIXME - What to do in non-validator context? args = ', '.join('{0}={1!r}'.format(k, v) for k, v in kwargs.items()) logging.error("Traversal error %s - %s", code, args) else: self.log.error(code, **kwargs) def object_path(self, identifier): """Path to OCFL object with given identifier relative to the OCFL storage root.""" return self.dispositor.identifier_to_path(identifier) def initialize(self): """Create and initialize a new OCFL storage root.""" (parent, root_dir) = fs.path.split(self.root) parent_fs = open_fs(parent) if parent_fs.exists(root_dir): raise StoreException("OCFL storage root %s already exists, aborting!" % (self.root)) self.root_fs = parent_fs.makedir(root_dir) logging.debug("Created OCFL storage root at %s", self.root) # Create root declaration Namaste(d=0, content=self.declaration_tvalue).write(pyfs=self.root_fs) # Create a layout declaration if self.disposition is not None: with self.root_fs.open(self.layout_file, 'w') as fh: layout = {'extension': self.disposition, 'description': "Non-standard layout from ocfl-py disposition -- FIXME"} json.dump(layout, fh, sort_keys=True, indent=2) logging.info("Created OCFL storage root %s", self.root) def check_root_structure(self): """Check the OCFL storage root structure. Assumed that self.root_fs filesystem is available. Raises StoreException if there is an error. """ # Storage root declaration namastes = find_namastes(0, pyfs=self.root_fs) if len(namastes) == 0: raise StoreException("Storage root %s lacks required 0= declaration file" % (self.root)) if len(namastes) > 1: raise StoreException("Storage root %s has more than one 0= style declaration file" % (self.root)) if namastes[0].tvalue != self.declaration_tvalue: raise StoreException("Storage root %s declaration file not as expected, got %s" % (self.root, namastes[0].filename)) if not namastes[0].content_ok(pyfs=self.root_fs): raise StoreException("Storage root %s required declaration file %s has invalid content" % (self.root, namastes[0].filename)) # Specification file and layout file if self.root_fs.exists(self.spec_file) and not self.root_fs.isfile(self.spec_file): raise StoreException("Storage root %s includes a specification entry that isn't a file" % (self.root)) self.extension, self.description = self.parse_layout_file() # Other files are allowed... return True def parse_layout_file(self): """Read and parse layout file in OCFL storage root. Returns: - (extension, description) strings on success, - (None, None) if there is now layout file (it is optional) - otherwise raises a StoreException. """ if self.root_fs.exists(self.layout_file): try: with self.root_fs.open(self.layout_file) as fh: layout = json.load(fh) if not isinstance(layout, dict): raise StoreException("Storage root %s has layout file that isn't a JSON object" % (self.root)) if ('extension' not in layout or not isinstance(layout['extension'], str) or 'description' not in layout or not isinstance(layout['description'], str)): raise StoreException("Storage root %s has layout file doesn't have required extension and description string entries" % (self.root)) return layout['extension'], layout['description'] except Exception as e: # FIXME - more specific? raise StoreException("OCFL storage root %s has layout file that can't be read (%s)" % (self.root, str(e))) else: return None, None def object_paths(self): """Generate object paths for every obect in the OCFL storage root. Yields (dirpath) that is the path to the directory for each object located, relative to the OCFL storage root and without a preceding /. Will log any errors seen while traversing the directory tree under the storage root. """ for (dirpath, dirs, files) in ocfl_walk(self.root_fs, is_storage_root=True): if dirpath == '/': if 'extensions' in dirs: self.validate_extensions_dir() dirs.remove('extensions') # Ignore any other files in storage root elif (len(dirs) + len(files)) == 0: self.traversal_error("E073", path=dirpath) elif len(files) == 0: pass # Just an intermediate directory else: # Is this directory an OCFL object? Look for any 0= file. zero_eqs = [file for file in files if file.startswith('0=')] if len(zero_eqs) > 1: self.traversal_error("E003d", path=dirpath) elif len(zero_eqs) == 1: declaration = zero_eqs[0] match = re.match(r'''0=ocfl_object_(\d+\.\d+)''', declaration) if match and match.group(1) == '1.0': yield dirpath.lstrip('/') elif match: self.traversal_error("E004a", path=dirpath, version=match.group(1)) else: self.traversal_error("E004b", path=dirpath, declaration=declaration) else: self.traversal_error("E072", path=dirpath) def validate_extensions_dir(self): """Validate content of extensions directory inside storage root. Validate the extensions directory by checking that there aren't any entries in the extensions directory that aren't directories themselves. Where there are extension directories they SHOULD be registered and this code relies up the registered_extensions property to list known storage root extensions. """ for entry in self.root_fs.scandir('extensions'): if entry.is_dir: if entry.name not in self.registered_extensions: self.log.warning('W901', entry=entry.name) # FIXME - No good warning code in spec else: self.traversal_error('E086', entry=entry.name) def list(self): """List contents of this OCFL storage root.""" self.open_root_fs() self.check_root_structure() self.num_objects = 0 for dirpath in self.object_paths(): with ocfl_opendir(self.root_fs, dirpath) as obj_fs: # Parse inventory to extract id identifier = Object(obj_fs=obj_fs).id_from_inventory() print("%s -- id=%s" % (dirpath, identifier)) self.num_objects += 1 # FIXME - maybe do some more stuff in here logging.info("Found %d OCFL Objects under root %s", self.num_objects, self.root) def validate_hierarchy(self, validate_objects=True, check_digests=True, show_warnings=False): """Validate storage root hierarchy. Returns: num_objects - number of objects checked good_objects - number of objects checked that were found to be valid """ num_objects = 0 good_objects = 0 for dirpath in self.object_paths(): if validate_objects: validator = Validator(check_digests=check_digests, lax_digests=self.lax_digests, show_warnings=show_warnings) if validator.validate(ocfl_opendir(self.root_fs, dirpath)): good_objects += 1 else: logging.info("Object at %s in INVALID", dirpath) messages = validator.status_str(prefix='[[' + dirpath + ']]') if messages != '': print(messages) num_objects += 1 return num_objects, good_objects def validate(self, validate_objects=True, check_digests=True, show_warnings=False, show_errors=True, lang='en'): """Validate OCFL storage root and optionally all objects.""" valid = True self.log = ValidationLogger(show_warnings=show_warnings, show_errors=show_errors, lang=lang) self.open_root_fs() try: self.check_root_structure() logging.info("Storage root structure is VALID") except StoreException as e: valid = False logging.info("Storage root structure is INVALID (%s)", str(e)) self.num_objects, self.good_objects = self.validate_hierarchy(validate_objects=validate_objects, check_digests=check_digests, show_warnings=show_warnings) if validate_objects: if self.good_objects == self.num_objects: logging.info("Objects checked: %d / %d are VALID", self.good_objects, self.num_objects) else: valid = False logging.info("Objects checked: %d / %d are INVALID", self.num_objects - self.good_objects, self.num_objects) else: logging.info("Not checking OCFL objects") print(str(self.log)) if self.num_traversal_errors > 0: valid = False logging.info("Encountered %d errors traversing storage root", self.num_traversal_errors) # FIXME - do some stuff in here if valid: logging.info("Storage root %s is VALID", self.root) else: logging.info("Storage root %s is INVALID", self.root) return valid def add(self, object_path): """Add pre-constructed object from object_path.""" self.open_root_fs() self.check_root_structure() # Sanity check o = Object() o.open_fs(object_path) inventory = o.parse_inventory() identifier = inventory['id'] # Now copy path = self.object_path(identifier) logging.info("Copying from %s to %s", object_path, fs.path.join(self.root, path)) try: copy_dir(o.obj_fs, '/', self.root_fs, path) logging.info("Copied") except Exception as e: logging.error("Copy failed: %s", str(e)) raise StoreException("Add object failed!")
ocfl/store.py
codereval_python_data_105
Next version identifier following existing pattern. Must deal with both zero-prefixed and non-zero prefixed versions. def next_version(version): """Next version identifier following existing pattern. Must deal with both zero-prefixed and non-zero prefixed versions. """ m = re.match(r'''v((\d)\d*)$''', version) if not m: raise ObjectException("Bad version '%s'" % version) next_n = int(m.group(1)) + 1 if m.group(2) == '0': # Zero-padded version next_v = ('v0%0' + str(len(version) - 2) + 'd') % next_n if len(next_v) != len(version): raise ObjectException("Version number overflow for zero-padded version %d to %d" % (version, next_v)) return next_v # Not zero-padded return 'v' + str(next_n) # -*- coding: utf-8 -*- """Utility functions to support the OCFL Object library.""" import re import sys import fs import fs.path from ._version import __version__ from .namaste import find_namastes from .pyfs import open_fs NORMALIZATIONS = ['uri', 'md5'] # Must match possibilities in map_filepaths() class ObjectException(Exception): """Exception class for OCFL Object.""" def add_object_args(parser): """Add Object settings to argparse or argument group instance parser.""" # Disk scanning parser.add_argument('--skip', action='append', default=['README.md', '.DS_Store'], help='directories and files to ignore') parser.add_argument('--normalization', '--norm', default=None, help='filepath normalization strategy (None, %s)' % (', '.join(NORMALIZATIONS))) # Versioning strategy settings parser.add_argument('--no-forward-delta', action='store_true', help='do not use forward deltas') parser.add_argument('--no-dedupe', '--no-dedup', action='store_true', help='do not use deduplicate files within a version') # Validation settings parser.add_argument('--lax-digests', action='store_true', help='allow use of any known digest') # Object files parser.add_argument('--objdir', '--obj', help='read from or write to OCFL object directory objdir') def add_shared_args(parser): """Add arguments to be shared by any ocfl-py scripts.""" parser.add_argument('--verbose', '-v', action='store_true', help="be more verbose") parser.add_argument('--version', action='store_true', help='Show version number and exit') def check_shared_args(args): """Check arguments set with add_shared_args.""" if args.version: print("%s is part of ocfl-py version %s" % (fs.path.basename(sys.argv[0]), __version__)) sys.exit(0) def next_version(version): """Next version identifier following existing pattern. Must deal with both zero-prefixed and non-zero prefixed versions. """ m = re.match(r'''v((\d)\d*)$''', version) if not m: raise ObjectException("Bad version '%s'" % version) next_n = int(m.group(1)) + 1 if m.group(2) == '0': # Zero-padded version next_v = ('v0%0' + str(len(version) - 2) + 'd') % next_n if len(next_v) != len(version): raise ObjectException("Version number overflow for zero-padded version %d to %d" % (version, next_v)) return next_v # Not zero-padded return 'v' + str(next_n) def remove_first_directory(path): """Remove first directory from input path. The return value will not have a trailing parh separator, even if the input path does. Will return an empty string if the input path has just one path segment. """ # FIXME - how to do this efficiently? Current code does complete # split and rejoins, excluding the first directory rpath = '' while True: (head, tail) = fs.path.split(path) if path in (head, tail): break path = head rpath = tail if rpath == '' else fs.path.join(tail, rpath) return rpath def make_unused_filepath(filepath, used, separator='__'): """Find filepath with string appended that makes it disjoint from those in used.""" n = 1 while True: n += 1 f = filepath + separator + str(n) if f not in used: return f def find_path_type(path): """Return a string indicating the type of thing at the given path. Return values: 'root' - looks like an OCFL Storage Root 'object' - looks like an OCFL Object 'file' - a file, might be an inventory other string explains error description Looks only at "0=*" Namaste files to determine the directory type. """ try: pyfs = open_fs(path, create=False) except (fs.opener.errors.OpenerError, fs.errors.CreateFailed): # Failed to open path as a filesystem, try enclosing directory # in case path is a file (parent, filename) = fs.path.split(path) try: pyfs = open_fs(parent, create=False) except (fs.opener.errors.OpenerError, fs.errors.CreateFailed) as e: return "path cannot be opened, and nor can parent (" + str(e) + ")" # Can open parent, is filename a file there? try: info = pyfs.getinfo(filename) except fs.errors.ResourceNotFound: return "path does not exist" if info.is_dir: return "directory that could not be opened as a filesystem, this should not happen" # pragma: no cover return 'file' namastes = find_namastes(0, pyfs=pyfs) if len(namastes) == 0: return "no 0= declaration file" # Look at the first 0= Namaste file that is of OCFL form to determine type, if there are # multiple declarations this will be caught later for namaste in namastes: m = re.match(r'''ocfl(_object)?_(\d+\.\d+)$''', namaste.tvalue) if m: return 'root' if m.group(1) is None else 'object' return "unrecognized 0= declaration file or files (first is %s)" % (namastes[0].tvalue)
ocfl/object_utils.py
codereval_python_data_106
Each version SHOULD have an inventory up to that point. Also keep a record of any content digests different from those in the root inventory so that we can also check them when validating the content. version_dirs is an array of version directory names and is assumed to be in version sequence (1, 2, 3...). def validate_version_inventories(self, version_dirs): """Each version SHOULD have an inventory up to that point. Also keep a record of any content digests different from those in the root inventory so that we can also check them when validating the content. version_dirs is an array of version directory names and is assumed to be in version sequence (1, 2, 3...). """ prior_manifest_digests = {} # file -> algorithm -> digest -> [versions] prior_fixity_digests = {} # file -> algorithm -> digest -> [versions] if len(version_dirs) == 0: return prior_manifest_digests, prior_fixity_digests last_version = version_dirs[-1] prev_version_dir = "NONE" # will be set for first directory with inventory prev_spec_version = '1.0' # lowest version for version_dir in version_dirs: inv_file = fs.path.join(version_dir, 'inventory.json') if not self.obj_fs.exists(inv_file): self.log.warning('W010', where=version_dir) continue # There is an inventory file for this version directory, check it if version_dir == last_version: # Don't validate in this case. Per the spec the inventory in the last version # MUST be identical to the copy in the object root, just check that root_inv_file = 'inventory.json' if not ocfl_files_identical(self.obj_fs, inv_file, root_inv_file): self.log.error('E064', root_inv_file=root_inv_file, inv_file=inv_file) else: # We could also just compare digest files but this gives a more helpful error for # which file has the incorrect digest if they don't match self.validate_inventory_digest(inv_file, self.digest_algorithm, where=version_dir) self.inventory_digest_files[version_dir] = 'inventory.json.' + self.digest_algorithm this_spec_version = self.spec_version else: # Note that inventories in prior versions may use different digest algorithms # from the current invenotory. Also, # an may accord with the same or earlier versions of the specification version_inventory, inv_validator = self.validate_inventory(inv_file, where=version_dir, extract_spec_version=True) this_spec_version = inv_validator.spec_version digest_algorithm = inv_validator.digest_algorithm self.validate_inventory_digest(inv_file, digest_algorithm, where=version_dir) self.inventory_digest_files[version_dir] = 'inventory.json.' + digest_algorithm if self.id and 'id' in version_inventory: if version_inventory['id'] != self.id: self.log.error('E037b', where=version_dir, root_id=self.id, version_id=version_inventory['id']) if 'manifest' in version_inventory: # Check that all files listed in prior inventories are in manifest not_seen = set(prior_manifest_digests.keys()) for digest in version_inventory['manifest']: for filepath in version_inventory['manifest'][digest]: # We rely on the validation to check that anything present is OK if filepath in not_seen: not_seen.remove(filepath) if len(not_seen) > 0: self.log.error('E023b', where=version_dir, missing_filepaths=', '.join(sorted(not_seen))) # Record all prior digests for unnormalized_digest in version_inventory['manifest']: digest = normalized_digest(unnormalized_digest, digest_type=digest_algorithm) for filepath in version_inventory['manifest'][unnormalized_digest]: if filepath not in prior_manifest_digests: prior_manifest_digests[filepath] = {} if digest_algorithm not in prior_manifest_digests[filepath]: prior_manifest_digests[filepath][digest_algorithm] = {} if digest not in prior_manifest_digests[filepath][digest_algorithm]: prior_manifest_digests[filepath][digest_algorithm][digest] = [] prior_manifest_digests[filepath][digest_algorithm][digest].append(version_dir) # Is this inventory an appropriate prior version of the object root inventory? if self.root_inv_validator is not None: self.root_inv_validator.validate_as_prior_version(inv_validator) # Fixity blocks are independent in each version. Record all values and the versions # they occur in for later checks against content if 'fixity' in version_inventory: for digest_algorithm in version_inventory['fixity']: for unnormalized_digest in version_inventory['fixity'][digest_algorithm]: digest = normalized_digest(unnormalized_digest, digest_type=digest_algorithm) for filepath in version_inventory['fixity'][digest_algorithm][unnormalized_digest]: if filepath not in prior_fixity_digests: prior_fixity_digests[filepath] = {} if digest_algorithm not in prior_fixity_digests[filepath]: prior_fixity_digests[filepath][digest_algorithm] = {} if digest not in prior_fixity_digests[filepath][digest_algorithm]: prior_fixity_digests[filepath][digest_algorithm][digest] = [] prior_fixity_digests[filepath][digest_algorithm][digest].append(version_dir) # We are validating the inventories in sequence and each new version must # follow the same or later spec version to previous inventories if prev_spec_version > this_spec_version: self.log.error('E103', where=version_dir, this_spec_version=this_spec_version, prev_version_dir=prev_version_dir, prev_spec_version=prev_spec_version) prev_version_dir = version_dir prev_spec_version = this_spec_version return prior_manifest_digests, prior_fixity_digests """OCFL Validator. Philosophy of this code is to keep it separate from the implementations of Store, Object and Version used to build and manipulate OCFL data, but to leverage lower level functions such as digest creation etc.. Code style is plain/verbose with detailed and specific validation errors that might help someone debug an implementation. This code uses PyFilesystem (import fs) exclusively for access to files. This should enable application beyond the operating system filesystem. """ import json import re import fs from .digest import file_digest, normalized_digest from .inventory_validator import InventoryValidator from .namaste import find_namastes from .pyfs import open_fs, ocfl_walk, ocfl_files_identical from .validation_logger import ValidationLogger class ValidatorAbortException(Exception): """Exception class to bail out of validation.""" class Validator(): """Class for OCFL Validator.""" def __init__(self, log=None, show_warnings=False, show_errors=True, check_digests=True, lax_digests=False, lang='en'): """Initialize OCFL validator.""" self.log = log self.check_digests = check_digests self.lax_digests = lax_digests if self.log is None: self.log = ValidationLogger(show_warnings=show_warnings, show_errors=show_errors, lang=lang) self.registered_extensions = [ '0001-digest-algorithms', '0002-flat-direct-storage-layout', '0003-hash-and-id-n-tuple-storage-layout', '0004-hashed-n-tuple-storage-layout', '0005-mutable-head' ] # The following actually initialized in initialize() method self.id = None self.spec_version = None self.digest_algorithm = None self.content_directory = None self.inventory_digest_files = None self.root_inv_validator = None self.obj_fs = None self.initialize() def initialize(self): """Initialize object state. Must be called between attempts to validate objects. """ self.id = None self.spec_version = '1.0' # default to latest published version self.digest_algorithm = 'sha512' self.content_directory = 'content' self.inventory_digest_files = {} # index by version_dir, algorithms may differ self.root_inv_validator = None self.obj_fs = None def status_str(self, prefix=''): """Return string representation of validation log, with optional prefix.""" return self.log.status_str(prefix=prefix) def __str__(self): """Return string representation of validation log.""" return self.status_str() def validate(self, path): """Validate OCFL object at path or pyfs root. Returns True if valid (warnings permitted), False otherwise. """ self.initialize() try: if isinstance(path, str): self.obj_fs = open_fs(path) else: self.obj_fs = path path = self.obj_fs.desc('') except fs.errors.CreateFailed: self.log.error('E003e', path=path) return False # Object declaration, set spec version number. If there are multiple declarations, # look for the lastest object version then report any others as errors namastes = find_namastes(0, pyfs=self.obj_fs) if len(namastes) == 0: self.log.error('E003a', assumed_version=self.spec_version) else: spec_version = None for namaste in namastes: # Extract and check spec version number this_file_version = None for version in ('1.1', '1.0'): if namaste.filename == '0=ocfl_object_' + version: this_file_version = version break if this_file_version is None: self.log.error('E006', filename=namaste.filename) elif spec_version is None or this_file_version > spec_version: spec_version = this_file_version if not namaste.content_ok(pyfs=self.obj_fs): self.log.error('E007', filename=namaste.filename) if spec_version is None: self.log.error('E003c', assumed_version=self.spec_version) else: self.spec_version = spec_version if len(namastes) > 1: self.log.error('E003b', files=len(namastes), using_version=self.spec_version) # Object root inventory file inv_file = 'inventory.json' if not self.obj_fs.exists(inv_file): self.log.error('E063') return False try: inventory, inv_validator = self.validate_inventory(inv_file) inventory_is_valid = self.log.num_errors == 0 self.root_inv_validator = inv_validator all_versions = inv_validator.all_versions self.id = inv_validator.id self.content_directory = inv_validator.content_directory self.digest_algorithm = inv_validator.digest_algorithm self.validate_inventory_digest(inv_file, self.digest_algorithm) # Object root self.validate_object_root(all_versions, already_checked=[namaste.filename for namaste in namastes]) # Version inventory files (prior_manifest_digests, prior_fixity_digests) = self.validate_version_inventories(all_versions) if inventory_is_valid: # Object content self.validate_content(inventory, all_versions, prior_manifest_digests, prior_fixity_digests) except ValidatorAbortException: pass return self.log.num_errors == 0 def validate_inventory(self, inv_file, where='root', extract_spec_version=False): """Validate a given inventory file, record errors with self.log.error(). Returns inventory object for use in later validation of object content. Does not look at anything else in the object itself. where - used for reporting messages of where inventory is in object extract_spec_version - if set True will attempt to take spec_version from the inventory itself instead of using the spec_version provided """ try: with self.obj_fs.openbin(inv_file, 'r') as fh: inventory = json.load(fh) except json.decoder.JSONDecodeError as e: self.log.error('E033', where=where, explanation=str(e)) raise ValidatorAbortException inv_validator = InventoryValidator(log=self.log, where=where, lax_digests=self.lax_digests, spec_version=self.spec_version) inv_validator.validate(inventory, extract_spec_version=extract_spec_version) return inventory, inv_validator def validate_inventory_digest(self, inv_file, digest_algorithm, where="root"): """Validate the appropriate inventory digest file in path.""" inv_digest_file = inv_file + '.' + digest_algorithm if not self.obj_fs.exists(inv_digest_file): self.log.error('E058a', where=where, path=inv_digest_file) else: self.validate_inventory_digest_match(inv_file, inv_digest_file) def validate_inventory_digest_match(self, inv_file, inv_digest_file): """Validate a given inventory digest for a given inventory file. On error throws exception with debugging string intended to be presented to a user. """ if not self.check_digests: return m = re.match(r'''.*\.(\w+)$''', inv_digest_file) if m: digest_algorithm = m.group(1) try: digest_recorded = self.read_inventory_digest(inv_digest_file) digest_actual = file_digest(inv_file, digest_algorithm, pyfs=self.obj_fs) if digest_actual != digest_recorded: self.log.error("E060", inv_file=inv_file, actual=digest_actual, recorded=digest_recorded, inv_digest_file=inv_digest_file) except Exception as e: # pylint: disable=broad-except self.log.error("E061", description=str(e)) else: self.log.error("E058b", inv_digest_file=inv_digest_file) def validate_object_root(self, version_dirs, already_checked): """Validate object root. All expected_files must be present and no other files. All expected_dirs must be present and no other dirs. """ expected_files = ['0=ocfl_object_' + self.spec_version, 'inventory.json', 'inventory.json.' + self.digest_algorithm] for entry in self.obj_fs.scandir(''): if entry.is_file: if entry.name not in expected_files and entry.name not in already_checked: self.log.error('E001a', file=entry.name) elif entry.is_dir: if entry.name in version_dirs: pass elif entry.name == 'extensions': self.validate_extensions_dir() elif re.match(r'''v\d+$''', entry.name): # Looks like a version directory so give more specific error self.log.error('E046b', dir=entry.name) else: # Simply an unexpected directory self.log.error('E001b', dir=entry.name) else: self.log.error('E001c', entry=entry.name) def validate_extensions_dir(self): """Validate content of extensions directory inside object root. Validate the extensions directory by checking that there aren't any entries in the extensions directory that aren't directories themselves. Where there are extension directories they SHOULD be registered and this code relies up the registered_extensions property to list known extensions. """ for entry in self.obj_fs.scandir('extensions'): if entry.is_dir: if entry.name not in self.registered_extensions: self.log.warning('W013', entry=entry.name) else: self.log.error('E067', entry=entry.name) def validate_version_inventories(self, version_dirs): """Each version SHOULD have an inventory up to that point. Also keep a record of any content digests different from those in the root inventory so that we can also check them when validating the content. version_dirs is an array of version directory names and is assumed to be in version sequence (1, 2, 3...). """ prior_manifest_digests = {} # file -> algorithm -> digest -> [versions] prior_fixity_digests = {} # file -> algorithm -> digest -> [versions] if len(version_dirs) == 0: return prior_manifest_digests, prior_fixity_digests last_version = version_dirs[-1] prev_version_dir = "NONE" # will be set for first directory with inventory prev_spec_version = '1.0' # lowest version for version_dir in version_dirs: inv_file = fs.path.join(version_dir, 'inventory.json') if not self.obj_fs.exists(inv_file): self.log.warning('W010', where=version_dir) continue # There is an inventory file for this version directory, check it if version_dir == last_version: # Don't validate in this case. Per the spec the inventory in the last version # MUST be identical to the copy in the object root, just check that root_inv_file = 'inventory.json' if not ocfl_files_identical(self.obj_fs, inv_file, root_inv_file): self.log.error('E064', root_inv_file=root_inv_file, inv_file=inv_file) else: # We could also just compare digest files but this gives a more helpful error for # which file has the incorrect digest if they don't match self.validate_inventory_digest(inv_file, self.digest_algorithm, where=version_dir) self.inventory_digest_files[version_dir] = 'inventory.json.' + self.digest_algorithm this_spec_version = self.spec_version else: # Note that inventories in prior versions may use different digest algorithms # from the current invenotory. Also, # an may accord with the same or earlier versions of the specification version_inventory, inv_validator = self.validate_inventory(inv_file, where=version_dir, extract_spec_version=True) this_spec_version = inv_validator.spec_version digest_algorithm = inv_validator.digest_algorithm self.validate_inventory_digest(inv_file, digest_algorithm, where=version_dir) self.inventory_digest_files[version_dir] = 'inventory.json.' + digest_algorithm if self.id and 'id' in version_inventory: if version_inventory['id'] != self.id: self.log.error('E037b', where=version_dir, root_id=self.id, version_id=version_inventory['id']) if 'manifest' in version_inventory: # Check that all files listed in prior inventories are in manifest not_seen = set(prior_manifest_digests.keys()) for digest in version_inventory['manifest']: for filepath in version_inventory['manifest'][digest]: # We rely on the validation to check that anything present is OK if filepath in not_seen: not_seen.remove(filepath) if len(not_seen) > 0: self.log.error('E023b', where=version_dir, missing_filepaths=', '.join(sorted(not_seen))) # Record all prior digests for unnormalized_digest in version_inventory['manifest']: digest = normalized_digest(unnormalized_digest, digest_type=digest_algorithm) for filepath in version_inventory['manifest'][unnormalized_digest]: if filepath not in prior_manifest_digests: prior_manifest_digests[filepath] = {} if digest_algorithm not in prior_manifest_digests[filepath]: prior_manifest_digests[filepath][digest_algorithm] = {} if digest not in prior_manifest_digests[filepath][digest_algorithm]: prior_manifest_digests[filepath][digest_algorithm][digest] = [] prior_manifest_digests[filepath][digest_algorithm][digest].append(version_dir) # Is this inventory an appropriate prior version of the object root inventory? if self.root_inv_validator is not None: self.root_inv_validator.validate_as_prior_version(inv_validator) # Fixity blocks are independent in each version. Record all values and the versions # they occur in for later checks against content if 'fixity' in version_inventory: for digest_algorithm in version_inventory['fixity']: for unnormalized_digest in version_inventory['fixity'][digest_algorithm]: digest = normalized_digest(unnormalized_digest, digest_type=digest_algorithm) for filepath in version_inventory['fixity'][digest_algorithm][unnormalized_digest]: if filepath not in prior_fixity_digests: prior_fixity_digests[filepath] = {} if digest_algorithm not in prior_fixity_digests[filepath]: prior_fixity_digests[filepath][digest_algorithm] = {} if digest not in prior_fixity_digests[filepath][digest_algorithm]: prior_fixity_digests[filepath][digest_algorithm][digest] = [] prior_fixity_digests[filepath][digest_algorithm][digest].append(version_dir) # We are validating the inventories in sequence and each new version must # follow the same or later spec version to previous inventories if prev_spec_version > this_spec_version: self.log.error('E103', where=version_dir, this_spec_version=this_spec_version, prev_version_dir=prev_version_dir, prev_spec_version=prev_spec_version) prev_version_dir = version_dir prev_spec_version = this_spec_version return prior_manifest_digests, prior_fixity_digests def validate_content(self, inventory, version_dirs, prior_manifest_digests, prior_fixity_digests): """Validate file presence and content against inventory. The root inventory in `inventory` is assumed to be valid and safe to use for construction of file paths etc.. """ files_seen = set() # Check files in each version directory for version_dir in version_dirs: try: # Check contents of version directory except content_directory for entry in self.obj_fs.listdir(version_dir): if ((entry == 'inventory.json') or (version_dir in self.inventory_digest_files and entry == self.inventory_digest_files[version_dir])): pass elif entry == self.content_directory: # Check content_directory content_path = fs.path.join(version_dir, self.content_directory) num_content_files_in_version = 0 for dirpath, dirs, files in ocfl_walk(self.obj_fs, content_path): if dirpath != '/' + content_path and (len(dirs) + len(files)) == 0: self.log.error("E024", where=version_dir, path=dirpath) for file in files: files_seen.add(fs.path.join(dirpath, file).lstrip('/')) num_content_files_in_version += 1 if num_content_files_in_version == 0: self.log.warning("W003", where=version_dir) elif self.obj_fs.isdir(fs.path.join(version_dir, entry)): self.log.warning("W002", where=version_dir, entry=entry) else: self.log.error("E015", where=version_dir, entry=entry) except (fs.errors.ResourceNotFound, fs.errors.DirectoryExpected): self.log.error('E046a', version_dir=version_dir) # Extract any digests in fixity and organize by filepath fixity_digests = {} if 'fixity' in inventory: for digest_algorithm in inventory['fixity']: for digest in inventory['fixity'][digest_algorithm]: for filepath in inventory['fixity'][digest_algorithm][digest]: if filepath in files_seen: if filepath not in fixity_digests: fixity_digests[filepath] = {} if digest_algorithm not in fixity_digests[filepath]: fixity_digests[filepath][digest_algorithm] = {} if digest not in fixity_digests[filepath][digest_algorithm]: fixity_digests[filepath][digest_algorithm][digest] = ['root'] else: self.log.error('E093b', where='root', digest_algorithm=digest_algorithm, digest=digest, content_path=filepath) # Check all files in root manifest if 'manifest' in inventory: for digest in inventory['manifest']: for filepath in inventory['manifest'][digest]: if filepath not in files_seen: self.log.error('E092b', where='root', content_path=filepath) else: if self.check_digests: content_digest = file_digest(filepath, digest_type=self.digest_algorithm, pyfs=self.obj_fs) if content_digest != normalized_digest(digest, digest_type=self.digest_algorithm): self.log.error('E092a', where='root', digest_algorithm=self.digest_algorithm, digest=digest, content_path=filepath, content_digest=content_digest) known_digests = {self.digest_algorithm: content_digest} # Are there digest values in the fixity block? self.check_additional_digests(filepath, known_digests, fixity_digests, 'E093a') # Are there other digests for this same file from other inventories? self.check_additional_digests(filepath, known_digests, prior_manifest_digests, 'E092a') self.check_additional_digests(filepath, known_digests, prior_fixity_digests, 'E093a') files_seen.discard(filepath) # Anything left in files_seen is not mentioned in the inventory if len(files_seen) > 0: self.log.error('E023a', where='root', extra_files=', '.join(sorted(files_seen))) def check_additional_digests(self, filepath, known_digests, additional_digests, error_code): """Check all the additional digests for filepath. This method is intended to be used both for manifest digests in prior versions and for fixity digests. The digests_seen dict is used to store any values calculated so that we don't recalculate digests that might appear multiple times. It is added to with any additional values calculated. Parameters: filepath - path of file in object (`v1/content/something` etc.) known_digests - dict of algorithm->digest that we have calculated additional_digests - dict: filepath -> algorithm -> digest -> [versions appears in] error_code - error code to log on mismatch (E092a for manifest, E093a for fixity) """ if filepath in additional_digests: for digest_algorithm in additional_digests[filepath]: if digest_algorithm in known_digests: # Don't recompute anything, just use it if we've seen it before content_digest = known_digests[digest_algorithm] else: content_digest = file_digest(filepath, digest_type=digest_algorithm, pyfs=self.obj_fs) known_digests[digest_algorithm] = content_digest for digest in additional_digests[filepath][digest_algorithm]: if content_digest != normalized_digest(digest, digest_type=digest_algorithm): where = ','.join(additional_digests[filepath][digest_algorithm][digest]) self.log.error(error_code, where=where, digest_algorithm=digest_algorithm, digest=digest, content_path=filepath, content_digest=content_digest) def read_inventory_digest(self, inv_digest_file): """Read inventory digest from sidecar file. Raise exception if there is an error, else return digest. """ with self.obj_fs.open(inv_digest_file, 'r') as fh: line = fh.readline() # we ignore any following lines, could raise exception m = re.match(r'''(\w+)\s+(\S+)\s*$''', line) if not m: raise Exception("Bad inventory digest file %s, wrong format" % (inv_digest_file)) if m.group(2) != 'inventory.json': raise Exception("Bad inventory name in inventory digest file %s" % (inv_digest_file)) return m.group(1)
ocfl/validator.py
codereval_python_data_107
Return a string indicating the type of thing at the given path. Return values: 'root' - looks like an OCFL Storage Root 'object' - looks like an OCFL Object 'file' - a file, might be an inventory other string explains error description Looks only at "0=*" Namaste files to determine the directory type. def find_path_type(path): """Return a string indicating the type of thing at the given path. Return values: 'root' - looks like an OCFL Storage Root 'object' - looks like an OCFL Object 'file' - a file, might be an inventory other string explains error description Looks only at "0=*" Namaste files to determine the directory type. """ try: pyfs = open_fs(path, create=False) except (fs.opener.errors.OpenerError, fs.errors.CreateFailed): # Failed to open path as a filesystem, try enclosing directory # in case path is a file (parent, filename) = fs.path.split(path) try: pyfs = open_fs(parent, create=False) except (fs.opener.errors.OpenerError, fs.errors.CreateFailed) as e: return "path cannot be opened, and nor can parent (" + str(e) + ")" # Can open parent, is filename a file there? try: info = pyfs.getinfo(filename) except fs.errors.ResourceNotFound: return "path does not exist" if info.is_dir: return "directory that could not be opened as a filesystem, this should not happen" # pragma: no cover return 'file' namastes = find_namastes(0, pyfs=pyfs) if len(namastes) == 0: return "no 0= declaration file" # Look at the first 0= Namaste file that is of OCFL form to determine type, if there are # multiple declarations this will be caught later for namaste in namastes: m = re.match(r'''ocfl(_object)?_(\d+\.\d+)$''', namaste.tvalue) if m: return 'root' if m.group(1) is None else 'object' return "unrecognized 0= declaration file or files (first is %s)" % (namastes[0].tvalue) # -*- coding: utf-8 -*- """Utility functions to support the OCFL Object library.""" import re import sys import fs import fs.path from ._version import __version__ from .namaste import find_namastes from .pyfs import open_fs NORMALIZATIONS = ['uri', 'md5'] # Must match possibilities in map_filepaths() class ObjectException(Exception): """Exception class for OCFL Object.""" def add_object_args(parser): """Add Object settings to argparse or argument group instance parser.""" # Disk scanning parser.add_argument('--skip', action='append', default=['README.md', '.DS_Store'], help='directories and files to ignore') parser.add_argument('--normalization', '--norm', default=None, help='filepath normalization strategy (None, %s)' % (', '.join(NORMALIZATIONS))) # Versioning strategy settings parser.add_argument('--no-forward-delta', action='store_true', help='do not use forward deltas') parser.add_argument('--no-dedupe', '--no-dedup', action='store_true', help='do not use deduplicate files within a version') # Validation settings parser.add_argument('--lax-digests', action='store_true', help='allow use of any known digest') # Object files parser.add_argument('--objdir', '--obj', help='read from or write to OCFL object directory objdir') def add_shared_args(parser): """Add arguments to be shared by any ocfl-py scripts.""" parser.add_argument('--verbose', '-v', action='store_true', help="be more verbose") parser.add_argument('--version', action='store_true', help='Show version number and exit') def check_shared_args(args): """Check arguments set with add_shared_args.""" if args.version: print("%s is part of ocfl-py version %s" % (fs.path.basename(sys.argv[0]), __version__)) sys.exit(0) def next_version(version): """Next version identifier following existing pattern. Must deal with both zero-prefixed and non-zero prefixed versions. """ m = re.match(r'''v((\d)\d*)$''', version) if not m: raise ObjectException("Bad version '%s'" % version) next_n = int(m.group(1)) + 1 if m.group(2) == '0': # Zero-padded version next_v = ('v0%0' + str(len(version) - 2) + 'd') % next_n if len(next_v) != len(version): raise ObjectException("Version number overflow for zero-padded version %d to %d" % (version, next_v)) return next_v # Not zero-padded return 'v' + str(next_n) def remove_first_directory(path): """Remove first directory from input path. The return value will not have a trailing parh separator, even if the input path does. Will return an empty string if the input path has just one path segment. """ # FIXME - how to do this efficiently? Current code does complete # split and rejoins, excluding the first directory rpath = '' while True: (head, tail) = fs.path.split(path) if path in (head, tail): break path = head rpath = tail if rpath == '' else fs.path.join(tail, rpath) return rpath def make_unused_filepath(filepath, used, separator='__'): """Find filepath with string appended that makes it disjoint from those in used.""" n = 1 while True: n += 1 f = filepath + separator + str(n) if f not in used: return f def find_path_type(path): """Return a string indicating the type of thing at the given path. Return values: 'root' - looks like an OCFL Storage Root 'object' - looks like an OCFL Object 'file' - a file, might be an inventory other string explains error description Looks only at "0=*" Namaste files to determine the directory type. """ try: pyfs = open_fs(path, create=False) except (fs.opener.errors.OpenerError, fs.errors.CreateFailed): # Failed to open path as a filesystem, try enclosing directory # in case path is a file (parent, filename) = fs.path.split(path) try: pyfs = open_fs(parent, create=False) except (fs.opener.errors.OpenerError, fs.errors.CreateFailed) as e: return "path cannot be opened, and nor can parent (" + str(e) + ")" # Can open parent, is filename a file there? try: info = pyfs.getinfo(filename) except fs.errors.ResourceNotFound: return "path does not exist" if info.is_dir: return "directory that could not be opened as a filesystem, this should not happen" # pragma: no cover return 'file' namastes = find_namastes(0, pyfs=pyfs) if len(namastes) == 0: return "no 0= declaration file" # Look at the first 0= Namaste file that is of OCFL form to determine type, if there are # multiple declarations this will be caught later for namaste in namastes: m = re.match(r'''ocfl(_object)?_(\d+\.\d+)$''', namaste.tvalue) if m: return 'root' if m.group(1) is None else 'object' return "unrecognized 0= declaration file or files (first is %s)" % (namastes[0].tvalue)
ocfl/object_utils.py
codereval_python_data_108
Amend the Bugzilla params def amend_bzparams(self, params, bug_ids): """Amend the Bugzilla params""" if not self.all_include_fields(): if "include_fields" in params: fields = params["include_fields"] if isinstance(fields, list): if "id" not in fields: fields.append("id") elif isinstance(fields, str): if fields != "id": params["include_fields"] = [fields, "id"] else: params["include_fields"] = [fields, "id"] else: params["include_fields"] = ["id"] params["include_fields"] += ["summary", "groups"] if self.has_assignee() and "assigned_to" not in params["include_fields"]: params["include_fields"].append("assigned_to") if self.has_product_component(): if "product" not in params["include_fields"]: params["include_fields"].append("product") if "component" not in params["include_fields"]: params["include_fields"].append("component") if self.has_needinfo() and "flags" not in params["include_fields"]: params["include_fields"].append("flags") if bug_ids: params["bug_id"] = bug_ids if self.filter_no_nag_keyword(): n = utils.get_last_field_num(params) params.update( { "f" + n: "status_whiteboard", "o" + n: "notsubstring", "v" + n: "[no-nag]", } ) if self.ignore_meta(): n = utils.get_last_field_num(params) params.update({"f" + n: "keywords", "o" + n: "nowords", "v" + n: "meta"}) # Limit the checkers to X years. Unlimited if max_years = -1 max_years = self.get_max_years() if max_years > 0: n = utils.get_last_field_num(params) params.update( { f"f{n}": "creation_ts", f"o{n}": "greaterthan", f"v{n}": f"-{max_years}y", } ) if self.has_default_products(): params["product"] = self.get_products() if not self.has_access_to_sec_bugs(): n = utils.get_last_field_num(params) params.update({"f" + n: "bug_group", "o" + n: "isempty"}) self.has_flags = "flags" in params.get("include_fields", []) # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import argparse import os import sys import time from collections import defaultdict from datetime import datetime from dateutil.relativedelta import relativedelta from jinja2 import Environment, FileSystemLoader from libmozdata import utils as lmdutils from libmozdata.bugzilla import Bugzilla from auto_nag import db, logger, mail, utils from auto_nag.cache import Cache from auto_nag.nag_me import Nag class BzCleaner(object): def __init__(self): super(BzCleaner, self).__init__() self._set_tool_name() self.has_autofix = False self.autofix_changes = {} self.quota_actions = defaultdict(list) self.no_manager = set() self.auto_needinfo = {} self.has_flags = False self.cache = Cache(self.name(), self.max_days_in_cache()) self.test_mode = utils.get_config("common", "test", False) self.versions = None logger.info("Run tool {}".format(self.get_tool_path())) def _set_tool_name(self): module = sys.modules[self.__class__.__module__] base = os.path.dirname(__file__) scripts = os.path.join(base, "scripts") self.__tool_path__ = os.path.relpath(module.__file__, scripts) name = os.path.basename(module.__file__) name = os.path.splitext(name)[0] self.__tool_name__ = name def init_versions(self): self.versions = utils.get_checked_versions() return bool(self.versions) def max_days_in_cache(self): """Get the max number of days the data must be kept in cache""" return self.get_config("max_days_in_cache", -1) def preamble(self): return None def description(self): """Get the description for the help""" return "" def name(self): """Get the tool name""" return self.__tool_name__ def get_tool_path(self): """Get the tool path""" return self.__tool_path__ def needinfo_template(self): """Get the txt template filename""" return self.name() + "_needinfo.txt" def template(self): """Get the html template filename""" return self.name() + ".html" def subject(self): """Get the partial email subject""" return self.description() def get_email_subject(self, date): """Get the email subject with a date or not""" af = "[autofix]" if self.has_autofix else "" if date: return "[autonag]{} {} for the {}".format(af, self.subject(), date) return "[autonag]{} {}".format(af, self.subject()) def ignore_date(self): """Should we ignore the date ?""" return False def must_run(self, date): """Check if the tool must run for this date""" days = self.get_config("must_run", None) if not days: return True weekday = date.weekday() week = utils.get_weekdays() for day in days: if week[day] == weekday: return True return False def has_enough_data(self): """Check if the tool has enough data to run""" if self.versions is None: # init_versions() has never been called return True return bool(self.versions) def filter_no_nag_keyword(self): """If True, then remove the bugs with [no-nag] in whiteboard from the bug list""" return True def add_no_manager(self, bugid): self.no_manager.add(str(bugid)) def has_assignee(self): return False def has_needinfo(self): return False def get_mail_to_auto_ni(self, bug): return None def all_include_fields(self): return False def get_max_ni(self): return -1 def get_max_actions(self): return -1 def exclude_no_action_bugs(self): """ If `True`, then remove bugs that have no actions from the email (e.g., needinfo got ignored due to exceeding the limit). This is applied only when using the `add_prioritized_action()` method. Returning `False` could be useful if we want to list all actions the tool would do if it had no limits. """ return True def ignore_meta(self): return False def columns(self): """The fields to get for the columns in email report""" return ["id", "summary"] def sort_columns(self): """Returns the key to sort columns""" return None def get_dates(self, date): """Get the dates for the bugzilla query (changedafter and changedbefore fields)""" date = lmdutils.get_date_ymd(date) lookup = self.get_config("days_lookup", 7) start_date = date - relativedelta(days=lookup) end_date = date + relativedelta(days=1) return start_date, end_date def get_extra_for_template(self): """Get extra data to put in the template""" return {} def get_extra_for_needinfo_template(self): """Get extra data to put in the needinfo template""" return {} def get_config(self, entry, default=None): return utils.get_config(self.name(), entry, default=default) def get_bz_params(self, date): """Get the Bugzilla parameters for the search query""" return {} def get_data(self): """Get the data structure to use in the bughandler""" return {} def get_summary(self, bug): return "..." if bug["groups"] else bug["summary"] def has_default_products(self): return True def has_product_component(self): return False def get_product_component(self): return self.prod_comp def get_max_years(self): return self.get_config("max-years", -1) def has_access_to_sec_bugs(self): return self.get_config("sec", True) def handle_bug(self, bug, data): """Implement this function to get all the bugs from the query""" return bug def get_db_extra(self): """Get extra information required for db insertion""" return { bugid: ni_mail for ni_mail, v in self.auto_needinfo.items() for bugid in v["bugids"] } def get_auto_ni_skiplist(self): """Return a set of email addresses that should never be needinfoed""" return set(self.get_config("needinfo_skiplist", default=[])) def add_auto_ni(self, bugid, data): if not data: return False ni_mail = data["mail"] if ni_mail in self.get_auto_ni_skiplist() or utils.is_no_assignee(ni_mail): return False if ni_mail in self.auto_needinfo: max_ni = self.get_max_ni() info = self.auto_needinfo[ni_mail] if max_ni > 0 and len(info["bugids"]) >= max_ni: return False info["bugids"].append(str(bugid)) else: self.auto_needinfo[ni_mail] = { "nickname": data["nickname"], "bugids": [str(bugid)], } return True def add_prioritized_action(self, bug, quota_name, needinfo=None, autofix=None): """ - `quota_name` is the key used to apply the limits, e.g., triage owner, team, or component """ assert needinfo or autofix # Avoid having more than one ni from our bot if needinfo and self.has_bot_set_ni(bug): needinfo = autofix = None action = { "bug": bug, "needinfo": needinfo, "autofix": autofix, } self.quota_actions[quota_name].append(action) def get_bug_sort_key(self, bug): return None def _populate_prioritized_actions(self, bugs): max_actions = self.get_max_actions() max_ni = self.get_max_ni() exclude_no_action_bugs = ( len(self.quota_actions) > 0 and self.exclude_no_action_bugs() ) bugs_with_action = set() for actions in self.quota_actions.values(): if len(actions) > max_ni or len(actions) > max_actions: actions.sort( key=lambda action: ( not action["needinfo"], self.get_bug_sort_key(action["bug"]), ) ) ni_count = 0 actions_count = 0 for action in actions: bugid = str(action["bug"]["id"]) if max_actions > 0 and actions_count >= max_actions: break if action["needinfo"]: if max_ni > 0 and ni_count >= max_ni: continue ok = self.add_auto_ni(bugid, action["needinfo"]) if not ok: # If we can't needinfo, we do not add the autofix continue if "extra" in action["needinfo"]: self.extra_ni[bugid] = action["needinfo"]["extra"] bugs_with_action.add(bugid) ni_count += 1 if action["autofix"]: assert bugid not in self.autofix_changes self.autofix_changes[bugid] = action["autofix"] bugs_with_action.add(bugid) if action["autofix"] or action["needinfo"]: actions_count += 1 if exclude_no_action_bugs: bugs = {id: bug for id, bug in bugs.items() if id in bugs_with_action} return bugs def bughandler(self, bug, data): """bug handler for the Bugzilla query""" if bug["id"] in self.cache: return if self.handle_bug(bug, data) is None: return bugid = str(bug["id"]) res = {"id": bugid} auto_ni = self.get_mail_to_auto_ni(bug) self.add_auto_ni(bugid, auto_ni) res["summary"] = self.get_summary(bug) if self.has_assignee(): res["assignee"] = utils.get_name_from_user_detail(bug["assigned_to_detail"]) if self.has_needinfo(): s = set() for flag in utils.get_needinfo(bug): s.add(flag["requestee"]) res["needinfos"] = sorted(s) if self.has_product_component(): for k in ["product", "component"]: res[k] = bug[k] if isinstance(self, Nag): bug = self.set_people_to_nag(bug, res) if not bug: return if bugid in data: data[bugid].update(res) else: data[bugid] = res def get_products(self): return self.get_config("products") + self.get_config("additional_products", []) def amend_bzparams(self, params, bug_ids): """Amend the Bugzilla params""" if not self.all_include_fields(): if "include_fields" in params: fields = params["include_fields"] if isinstance(fields, list): if "id" not in fields: fields.append("id") elif isinstance(fields, str): if fields != "id": params["include_fields"] = [fields, "id"] else: params["include_fields"] = [fields, "id"] else: params["include_fields"] = ["id"] params["include_fields"] += ["summary", "groups"] if self.has_assignee() and "assigned_to" not in params["include_fields"]: params["include_fields"].append("assigned_to") if self.has_product_component(): if "product" not in params["include_fields"]: params["include_fields"].append("product") if "component" not in params["include_fields"]: params["include_fields"].append("component") if self.has_needinfo() and "flags" not in params["include_fields"]: params["include_fields"].append("flags") if bug_ids: params["bug_id"] = bug_ids if self.filter_no_nag_keyword(): n = utils.get_last_field_num(params) params.update( { "f" + n: "status_whiteboard", "o" + n: "notsubstring", "v" + n: "[no-nag]", } ) if self.ignore_meta(): n = utils.get_last_field_num(params) params.update({"f" + n: "keywords", "o" + n: "nowords", "v" + n: "meta"}) # Limit the checkers to X years. Unlimited if max_years = -1 max_years = self.get_max_years() if max_years > 0: n = utils.get_last_field_num(params) params.update( { f"f{n}": "creation_ts", f"o{n}": "greaterthan", f"v{n}": f"-{max_years}y", } ) if self.has_default_products(): params["product"] = self.get_products() if not self.has_access_to_sec_bugs(): n = utils.get_last_field_num(params) params.update({"f" + n: "bug_group", "o" + n: "isempty"}) self.has_flags = "flags" in params.get("include_fields", []) def get_bugs(self, date="today", bug_ids=[], chunk_size=None): """Get the bugs""" bugs = self.get_data() params = self.get_bz_params(date) self.amend_bzparams(params, bug_ids) self.query_url = utils.get_bz_search_url(params) if isinstance(self, Nag): self.query_params: dict = params old_CHUNK_SIZE = Bugzilla.BUGZILLA_CHUNK_SIZE try: if chunk_size: Bugzilla.BUGZILLA_CHUNK_SIZE = chunk_size Bugzilla( params, bughandler=self.bughandler, bugdata=bugs, timeout=self.get_config("bz_query_timeout"), ).get_data().wait() finally: Bugzilla.BUGZILLA_CHUNK_SIZE = old_CHUNK_SIZE self.get_comments(bugs) return bugs def commenthandler(self, bug, bugid, data): return def _commenthandler(self, bug, bugid, data): comments = bug["comments"] bugid = str(bugid) if self.has_last_comment_time(): if comments: data[bugid]["last_comment"] = utils.get_human_lag(comments[-1]["time"]) else: data[bugid]["last_comment"] = "" self.commenthandler(bug, bugid, data) def get_comments(self, bugs): """Get the bugs comments""" if self.has_last_comment_time(): bugids = self.get_list_bugs(bugs) Bugzilla( bugids=bugids, commenthandler=self._commenthandler, commentdata=bugs ).get_data().wait() return bugs def has_last_comment_time(self): return False def get_list_bugs(self, bugs): return [x["id"] for x in bugs.values()] def get_documentation(self): return "For more information, please visit [auto_nag documentation](https://wiki.mozilla.org/Release_Management/autonag#{}).".format( self.get_tool_path().replace("/", ".2F") ) def has_bot_set_ni(self, bug): if not self.has_flags: raise Exception return utils.has_bot_set_ni(bug) def set_needinfo(self): if not self.auto_needinfo: return {} template_name = self.needinfo_template() assert bool(template_name) env = Environment(loader=FileSystemLoader("templates")) template = env.get_template(template_name) res = {} doc = self.get_documentation() for ni_mail, info in self.auto_needinfo.items(): nick = info["nickname"] for bugid in info["bugids"]: data = { "comment": {"body": ""}, "flags": [ { "name": "needinfo", "requestee": ni_mail, "status": "?", "new": "true", } ], } comment = None if nick: comment = template.render( nickname=nick, extra=self.get_extra_for_needinfo_template(), plural=utils.plural, bugid=bugid, documentation=doc, ) comment = comment.strip() + "\n" data["comment"]["body"] = comment if bugid not in res: res[bugid] = data else: res[bugid]["flags"] += data["flags"] if comment: res[bugid]["comment"]["body"] = comment return res def has_individual_autofix(self, changes): # check if we have a dictionary with bug numbers as keys # return True if all the keys are bug number # (which means that each bug has its own autofix) return changes and all( isinstance(bugid, int) or bugid.isdigit() for bugid in changes ) def get_autofix_change(self): """Get the change to do to autofix the bugs""" return self.autofix_changes def autofix(self, bugs): """Autofix the bugs according to what is returned by get_autofix_change""" ni_changes = self.set_needinfo() change = self.get_autofix_change() if not ni_changes and not change: return bugs self.has_autofix = True new_changes = {} if not self.has_individual_autofix(change): bugids = self.get_list_bugs(bugs) for bugid in bugids: new_changes[bugid] = utils.merge_bz_changes( change, ni_changes.get(bugid, {}) ) else: change = {str(k): v for k, v in change.items()} bugids = set(change.keys()) | set(ni_changes.keys()) for bugid in bugids: mrg = utils.merge_bz_changes( change.get(bugid, {}), ni_changes.get(bugid, {}) ) if mrg: new_changes[bugid] = mrg if self.dryrun or self.test_mode: for bugid, ch in new_changes.items(): logger.info( "The bugs: {}\n will be autofixed with:\n{}".format(bugid, ch) ) else: extra = self.get_db_extra() max_retries = utils.get_config("common", "bugzilla_max_retries", 3) for bugid, ch in new_changes.items(): added = False for _ in range(max_retries): failures = Bugzilla([str(bugid)]).put(ch) if failures: time.sleep(1) else: added = True db.BugChange.add(self.name(), bugid, extra=extra.get(bugid, "")) break if not added: self.failure_callback(bugid) logger.error( "{}: Cannot put data for bug {} (change => {}).".format( self.name(), bugid, ch ) ) return bugs def failure_callback(self, bugid): """Called on Bugzilla.put failures""" return def terminate(self): """Called when everything is done""" return def organize(self, bugs): return utils.organize(bugs, self.columns(), key=self.sort_columns()) def add_to_cache(self, bugs): """Add the bug keys to cache""" if isinstance(bugs, dict): self.cache.add(bugs.keys()) else: self.cache.add(bugs) def get_email_data(self, date, bug_ids): bugs = self.get_bugs(date=date, bug_ids=bug_ids) bugs = self._populate_prioritized_actions(bugs) bugs = self.autofix(bugs) self.add_to_cache(bugs) if bugs: return self.organize(bugs) def get_email(self, date, bug_ids=[]): """Get title and body for the email""" data = self.get_email_data(date, bug_ids) if data: extra = self.get_extra_for_template() env = Environment(loader=FileSystemLoader("templates")) template = env.get_template(self.template()) message = template.render( date=date, data=data, extra=extra, str=str, enumerate=enumerate, plural=utils.plural, no_manager=self.no_manager, table_attrs=self.get_config("table_attrs"), preamble=self.preamble(), ) common = env.get_template("common.html") body = common.render( message=message, query_url=utils.shorten_long_bz_url(self.query_url) ) return self.get_email_subject(date), body return None, None def send_email(self, date="today"): """Send the email""" if date: date = lmdutils.get_date(date) d = lmdutils.get_date_ymd(date) if isinstance(self, Nag): self.nag_date: datetime = d if not self.must_run(d): return if not self.has_enough_data(): logger.info("The tool {} hasn't enough data to run".format(self.name())) return login_info = utils.get_login_info() title, body = self.get_email(date) if title: receivers = utils.get_receivers(self.name()) status = "Success" try: mail.send( login_info["ldap_username"], receivers, title, body, html=True, login=login_info, dryrun=self.dryrun, ) except Exception: logger.exception("Tool {}".format(self.name())) status = "Failure" db.Email.add(self.name(), receivers, "global", status) if isinstance(self, Nag): self.send_mails(title, dryrun=self.dryrun) else: name = self.name().upper() if date: logger.info("{}: No data for {}".format(name, date)) else: logger.info("{}: No data".format(name)) logger.info("Query: {}".format(self.query_url)) def add_custom_arguments(self, parser): pass def parse_custom_arguments(self, args): pass def get_args_parser(self): """Get the argumends from the command line""" parser = argparse.ArgumentParser(description=self.description()) parser.add_argument( "--production", dest="dryrun", action="store_false", help="If the flag is not passed, just do the query, and print emails to console without emailing anyone", ) if not self.ignore_date(): parser.add_argument( "-D", "--date", dest="date", action="store", default="today", help="Date for the query", ) self.add_custom_arguments(parser) return parser def run(self): """Run the tool""" args = self.get_args_parser().parse_args() self.parse_custom_arguments(args) date = "" if self.ignore_date() else args.date self.dryrun = args.dryrun self.cache.set_dry_run(self.dryrun) try: self.send_email(date=date) self.terminate() logger.info("Tool {} has finished.".format(self.get_tool_path())) except Exception: logger.exception("Tool {}".format(self.name()))
auto_nag/bzcleaner.py
codereval_python_data_109
Given a nested borgmatic configuration data structure as a list of tuples in the form of: ( ruamel.yaml.nodes.ScalarNode as a key, ruamel.yaml.nodes.MappingNode or other Node as a value, ), ... deep merge any node values corresponding to duplicate keys and return the result. If there are colliding keys with non-MappingNode values (e.g., integers or strings), the last of the values wins. For instance, given node values of: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='7') ), ]), ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] ... the returned result would be: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] The purpose of deep merging like this is to support, for instance, merging one borgmatic configuration file into another for reuse, such that a configuration section ("retention", etc.) does not completely replace the corresponding section in a merged file. def deep_merge_nodes(nodes): ''' Given a nested borgmatic configuration data structure as a list of tuples in the form of: ( ruamel.yaml.nodes.ScalarNode as a key, ruamel.yaml.nodes.MappingNode or other Node as a value, ), ... deep merge any node values corresponding to duplicate keys and return the result. If there are colliding keys with non-MappingNode values (e.g., integers or strings), the last of the values wins. For instance, given node values of: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='7') ), ]), ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] ... the returned result would be: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] The purpose of deep merging like this is to support, for instance, merging one borgmatic configuration file into another for reuse, such that a configuration section ("retention", etc.) does not completely replace the corresponding section in a merged file. ''' # Map from original node key/value to the replacement merged node. DELETED_NODE as a replacement # node indications deletion. replaced_nodes = {} # To find nodes that require merging, compare each node with each other node. for a_key, a_value in nodes: for b_key, b_value in nodes: # If we've already considered one of the nodes for merging, skip it. if (a_key, a_value) in replaced_nodes or (b_key, b_value) in replaced_nodes: continue # If the keys match and the values are different, we need to merge these two A and B nodes. if a_key.tag == b_key.tag and a_key.value == b_key.value and a_value != b_value: # Since we're merging into the B node, consider the A node a duplicate and remove it. replaced_nodes[(a_key, a_value)] = DELETED_NODE # If we're dealing with MappingNodes, recurse and merge its values as well. if isinstance(b_value, ruamel.yaml.nodes.MappingNode): replaced_nodes[(b_key, b_value)] = ( b_key, ruamel.yaml.nodes.MappingNode( tag=b_value.tag, value=deep_merge_nodes(a_value.value + b_value.value), start_mark=b_value.start_mark, end_mark=b_value.end_mark, flow_style=b_value.flow_style, comment=b_value.comment, anchor=b_value.anchor, ), ) # If we're dealing with SequenceNodes, merge by appending one sequence to the other. elif isinstance(b_value, ruamel.yaml.nodes.SequenceNode): replaced_nodes[(b_key, b_value)] = ( b_key, ruamel.yaml.nodes.SequenceNode( tag=b_value.tag, value=a_value.value + b_value.value, start_mark=b_value.start_mark, end_mark=b_value.end_mark, flow_style=b_value.flow_style, comment=b_value.comment, anchor=b_value.anchor, ), ) return [ replaced_nodes.get(node, node) for node in nodes if replaced_nodes.get(node) != DELETED_NODE ] import logging import os import ruamel.yaml logger = logging.getLogger(__name__) class Yaml_with_loader_stream(ruamel.yaml.YAML): ''' A derived class of ruamel.yaml.YAML that simply tacks the loaded stream (file object) onto the loader class so that it's available anywhere that's passed a loader (in this case, include_configuration() below). ''' def get_constructor_parser(self, stream): constructor, parser = super(Yaml_with_loader_stream, self).get_constructor_parser(stream) constructor.loader.stream = stream return constructor, parser def load_configuration(filename): ''' Load the given configuration file and return its contents as a data structure of nested dicts and lists. Raise ruamel.yaml.error.YAMLError if something goes wrong parsing the YAML, or RecursionError if there are too many recursive includes. ''' yaml = Yaml_with_loader_stream(typ='safe') yaml.Constructor = Include_constructor return yaml.load(open(filename)) def include_configuration(loader, filename_node): ''' Load the given YAML filename (ignoring the given loader so we can use our own) and return its contents as a data structure of nested dicts and lists. If the filename is relative, probe for it within 1. the current working directory and 2. the directory containing the YAML file doing the including. Raise FileNotFoundError if an included file was not found. ''' include_directories = [os.getcwd(), os.path.abspath(os.path.dirname(loader.stream.name))] include_filename = os.path.expanduser(filename_node.value) if not os.path.isabs(include_filename): candidate_filenames = [ os.path.join(directory, include_filename) for directory in include_directories ] for candidate_filename in candidate_filenames: if os.path.exists(candidate_filename): include_filename = candidate_filename break else: raise FileNotFoundError( f'Could not find include {filename_node.value} at {" or ".join(candidate_filenames)}' ) return load_configuration(include_filename) DELETED_NODE = object() def deep_merge_nodes(nodes): ''' Given a nested borgmatic configuration data structure as a list of tuples in the form of: ( ruamel.yaml.nodes.ScalarNode as a key, ruamel.yaml.nodes.MappingNode or other Node as a value, ), ... deep merge any node values corresponding to duplicate keys and return the result. If there are colliding keys with non-MappingNode values (e.g., integers or strings), the last of the values wins. For instance, given node values of: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='7') ), ]), ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] ... the returned result would be: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] The purpose of deep merging like this is to support, for instance, merging one borgmatic configuration file into another for reuse, such that a configuration section ("retention", etc.) does not completely replace the corresponding section in a merged file. ''' # Map from original node key/value to the replacement merged node. DELETED_NODE as a replacement # node indications deletion. replaced_nodes = {} # To find nodes that require merging, compare each node with each other node. for a_key, a_value in nodes: for b_key, b_value in nodes: # If we've already considered one of the nodes for merging, skip it. if (a_key, a_value) in replaced_nodes or (b_key, b_value) in replaced_nodes: continue # If the keys match and the values are different, we need to merge these two A and B nodes. if a_key.tag == b_key.tag and a_key.value == b_key.value and a_value != b_value: # Since we're merging into the B node, consider the A node a duplicate and remove it. replaced_nodes[(a_key, a_value)] = DELETED_NODE # If we're dealing with MappingNodes, recurse and merge its values as well. if isinstance(b_value, ruamel.yaml.nodes.MappingNode): replaced_nodes[(b_key, b_value)] = ( b_key, ruamel.yaml.nodes.MappingNode( tag=b_value.tag, value=deep_merge_nodes(a_value.value + b_value.value), start_mark=b_value.start_mark, end_mark=b_value.end_mark, flow_style=b_value.flow_style, comment=b_value.comment, anchor=b_value.anchor, ), ) # If we're dealing with SequenceNodes, merge by appending one sequence to the other. elif isinstance(b_value, ruamel.yaml.nodes.SequenceNode): replaced_nodes[(b_key, b_value)] = ( b_key, ruamel.yaml.nodes.SequenceNode( tag=b_value.tag, value=a_value.value + b_value.value, start_mark=b_value.start_mark, end_mark=b_value.end_mark, flow_style=b_value.flow_style, comment=b_value.comment, anchor=b_value.anchor, ), ) return [ replaced_nodes.get(node, node) for node in nodes if replaced_nodes.get(node) != DELETED_NODE ] class Include_constructor(ruamel.yaml.SafeConstructor): ''' A YAML "constructor" (a ruamel.yaml concept) that supports a custom "!include" tag for including separate YAML configuration files. Example syntax: `retention: !include common.yaml` ''' def __init__(self, preserve_quotes=None, loader=None): super(Include_constructor, self).__init__(preserve_quotes, loader) self.add_constructor('!include', include_configuration) def flatten_mapping(self, node): ''' Support the special case of deep merging included configuration into an existing mapping using the YAML '<<' merge key. Example syntax: ``` retention: keep_daily: 1 <<: !include common.yaml ``` These includes are deep merged into the current configuration file. For instance, in this example, any "retention" options in common.yaml will get merged into the "retention" section in the example configuration file. ''' representer = ruamel.yaml.representer.SafeRepresenter() for index, (key_node, value_node) in enumerate(node.value): if key_node.tag == u'tag:yaml.org,2002:merge' and value_node.tag == '!include': included_value = representer.represent_data(self.construct_object(value_node)) node.value[index] = (key_node, included_value) super(Include_constructor, self).flatten_mapping(node) node.value = deep_merge_nodes(node.value)
borgmatic/config/load.py
codereval_python_data_110
Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. def parse_arguments(*arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. ''' parser = ArgumentParser(description='Generate a sample borgmatic YAML configuration file.') parser.add_argument( '-s', '--source', dest='source_filename', help='Optional YAML configuration file to merge into the generated configuration, useful for upgrading your configuration', ) parser.add_argument( '-d', '--destination', dest='destination_filename', default=DEFAULT_DESTINATION_CONFIG_FILENAME, help='Destination YAML configuration file, default: {}'.format( DEFAULT_DESTINATION_CONFIG_FILENAME ), ) parser.add_argument( '--overwrite', default=False, action='store_true', help='Whether to overwrite any existing destination file, defaults to false', ) return parser.parse_args(arguments) import sys from argparse import ArgumentParser from borgmatic.config import generate, validate DEFAULT_DESTINATION_CONFIG_FILENAME = '/etc/borgmatic/config.yaml' def parse_arguments(*arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. ''' parser = ArgumentParser(description='Generate a sample borgmatic YAML configuration file.') parser.add_argument( '-s', '--source', dest='source_filename', help='Optional YAML configuration file to merge into the generated configuration, useful for upgrading your configuration', ) parser.add_argument( '-d', '--destination', dest='destination_filename', default=DEFAULT_DESTINATION_CONFIG_FILENAME, help='Destination YAML configuration file, default: {}'.format( DEFAULT_DESTINATION_CONFIG_FILENAME ), ) parser.add_argument( '--overwrite', default=False, action='store_true', help='Whether to overwrite any existing destination file, defaults to false', ) return parser.parse_args(arguments) def main(): # pragma: no cover try: args = parse_arguments(*sys.argv[1:]) generate.generate_sample_configuration( args.source_filename, args.destination_filename, validate.schema_filename(), overwrite=args.overwrite, ) print('Generated a sample configuration file at {}.'.format(args.destination_filename)) print() if args.source_filename: print( 'Merged in the contents of configuration file at {}.'.format(args.source_filename) ) print('To review the changes made, run:') print() print( ' diff --unified {} {}'.format(args.source_filename, args.destination_filename) ) print() print('Please edit the file to suit your needs. The values are representative.') print('All fields are optional except where indicated.') print() print('If you ever need help: https://torsion.org/borgmatic/#issues') except (ValueError, OSError) as error: print(error, file=sys.stderr) sys.exit(1)
borgmatic/commands/generate_config.py
codereval_python_data_111
Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in action.option_strings) from borgmatic.commands import arguments UPGRADE_MESSAGE = ''' Your bash completions script is from a different version of borgmatic than is currently installed. Please upgrade your script so your completions match the command-line flags in your installed borgmatic! Try this to upgrade: sudo sh -c "borgmatic --bash-completion > $BASH_SOURCE" source $BASH_SOURCE ''' def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in action.option_strings) def bash_completion(): ''' Return a bash completion script for the borgmatic command. Produce this by introspecting borgmatic's command-line argument parsers. ''' top_level_parser, subparsers = arguments.make_parsers() global_flags = parser_flags(top_level_parser) actions = ' '.join(subparsers.choices.keys()) # Avert your eyes. return '\n'.join( ( 'check_version() {', ' local this_script="$(cat "$BASH_SOURCE" 2> /dev/null)"', ' local installed_script="$(borgmatic --bash-completion 2> /dev/null)"', ' if [ "$this_script" != "$installed_script" ] && [ "$installed_script" != "" ];' ' then cat << EOF\n%s\nEOF' % UPGRADE_MESSAGE, ' fi', '}', 'complete_borgmatic() {', ) + tuple( ''' if [[ " ${COMP_WORDS[*]} " =~ " %s " ]]; then COMPREPLY=($(compgen -W "%s %s %s" -- "${COMP_WORDS[COMP_CWORD]}")) return 0 fi''' % (action, parser_flags(subparser), actions, global_flags) for action, subparser in subparsers.choices.items() ) + ( ' COMPREPLY=($(compgen -W "%s %s" -- "${COMP_WORDS[COMP_CWORD]}"))' % (actions, global_flags), ' (check_version &)', '}', '\ncomplete -o bashdefault -o default -F complete_borgmatic borgmatic', ) )
borgmatic/commands/completion.py
codereval_python_data_112
Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. ''' top_level_parser, subparsers = make_parsers() arguments, remaining_arguments = parse_subparser_arguments( unparsed_arguments, subparsers.choices ) arguments['global'] = top_level_parser.parse_args(remaining_arguments) if arguments['global'].excludes_filename: raise ValueError( 'The --excludes option has been replaced with exclude_patterns in configuration' ) if 'init' in arguments and arguments['global'].dry_run: raise ValueError('The init action cannot be used with the --dry-run option') if ( 'list' in arguments and 'info' in arguments and arguments['list'].json and arguments['info'].json ): raise ValueError('With the --json option, list and info actions cannot be used together') return arguments import collections from argparse import Action, ArgumentParser from borgmatic.config import collect SUBPARSER_ALIASES = { 'init': ['--init', '-I'], 'prune': ['--prune', '-p'], 'compact': [], 'create': ['--create', '-C'], 'check': ['--check', '-k'], 'extract': ['--extract', '-x'], 'export-tar': ['--export-tar'], 'mount': ['--mount', '-m'], 'umount': ['--umount', '-u'], 'restore': ['--restore', '-r'], 'list': ['--list', '-l'], 'info': ['--info', '-i'], 'borg': [], } def parse_subparser_arguments(unparsed_arguments, subparsers): ''' Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). ''' arguments = collections.OrderedDict() remaining_arguments = list(unparsed_arguments) alias_to_subparser_name = { alias: subparser_name for subparser_name, aliases in SUBPARSER_ALIASES.items() for alias in aliases } # If the "borg" action is used, skip all other subparsers. This avoids confusion like # "borg list" triggering borgmatic's own list action. if 'borg' in unparsed_arguments: subparsers = {'borg': subparsers['borg']} for subparser_name, subparser in subparsers.items(): if subparser_name not in remaining_arguments: continue canonical_name = alias_to_subparser_name.get(subparser_name, subparser_name) # If a parsed value happens to be the same as the name of a subparser, remove it from the # remaining arguments. This prevents, for instance, "check --only extract" from triggering # the "extract" subparser. parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) for value in vars(parsed).values(): if isinstance(value, str): if value in subparsers: remaining_arguments.remove(value) elif isinstance(value, list): for item in value: if item in subparsers: remaining_arguments.remove(item) arguments[canonical_name] = parsed # If no actions are explicitly requested, assume defaults: prune, compact, create, and check. if not arguments and '--help' not in unparsed_arguments and '-h' not in unparsed_arguments: for subparser_name in ('prune', 'compact', 'create', 'check'): subparser = subparsers[subparser_name] parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) arguments[subparser_name] = parsed remaining_arguments = list(unparsed_arguments) # Now ask each subparser, one by one, to greedily consume arguments. for subparser_name, subparser in subparsers.items(): if subparser_name not in arguments.keys(): continue subparser = subparsers[subparser_name] unused_parsed, remaining_arguments = subparser.parse_known_args(remaining_arguments) # Special case: If "borg" is present in the arguments, consume all arguments after (+1) the # "borg" action. if 'borg' in arguments: borg_options_index = remaining_arguments.index('borg') + 1 arguments['borg'].options = remaining_arguments[borg_options_index:] remaining_arguments = remaining_arguments[:borg_options_index] # Remove the subparser names themselves. for subparser_name, subparser in subparsers.items(): if subparser_name in remaining_arguments: remaining_arguments.remove(subparser_name) return (arguments, remaining_arguments) class Extend_action(Action): ''' An argparse action to support Python 3.8's "extend" action in older versions of Python. ''' def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest, None) if items: items.extend(values) else: setattr(namespace, self.dest, list(values)) def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(expand_home=False) global_parser = ArgumentParser(add_help=False) global_parser.register('action', 'extend', Extend_action) global_group = global_parser.add_argument_group('global arguments') global_group.add_argument( '-c', '--config', nargs='*', dest='config_paths', default=config_paths, help='Configuration filenames or directories, defaults to: {}'.format( ' '.join(unexpanded_config_paths) ), ) global_group.add_argument( '--excludes', dest='excludes_filename', help='Deprecated in favor of exclude_patterns within configuration', ) global_group.add_argument( '-n', '--dry-run', dest='dry_run', action='store_true', help='Go through the motions, but do not actually write to any repositories', ) global_group.add_argument( '-nc', '--no-color', dest='no_color', action='store_true', help='Disable colored output' ) global_group.add_argument( '-v', '--verbosity', type=int, choices=range(-1, 3), default=0, help='Display verbose progress to the console (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--syslog-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to syslog (from only errors to very verbose: -1, 0, 1, or 2). Ignored when console is interactive or --log-file is given', ) global_group.add_argument( '--log-file-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to log file (from only errors to very verbose: -1, 0, 1, or 2). Only used when --log-file is given', ) global_group.add_argument( '--monitoring-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to monitoring integrations that support logging (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--log-file', type=str, default=None, help='Write log messages to this file instead of syslog', ) global_group.add_argument( '--override', metavar='SECTION.OPTION=VALUE', nargs='+', dest='overrides', action='extend', help='One or more configuration file options to override with specified values', ) global_group.add_argument( '--no-environment-interpolation', dest='resolve_env', action='store_false', help='Do not resolve environment variables in configuration file', ) global_group.add_argument( '--bash-completion', default=False, action='store_true', help='Show bash completion script and exit', ) global_group.add_argument( '--version', dest='version', default=False, action='store_true', help='Display installed version number of borgmatic and exit', ) top_level_parser = ArgumentParser( description=''' Simple, configuration-driven backup software for servers and workstations. If none of the action options are given, then borgmatic defaults to: prune, compact, create, and check. ''', parents=[global_parser], ) subparsers = top_level_parser.add_subparsers( title='actions', metavar='', help='Specify zero or more actions. Defaults to prune, compact, create, and check. Use --help with action for details:', ) init_parser = subparsers.add_parser( 'init', aliases=SUBPARSER_ALIASES['init'], help='Initialize an empty Borg repository', description='Initialize an empty Borg repository', add_help=False, ) init_group = init_parser.add_argument_group('init arguments') init_group.add_argument( '-e', '--encryption', dest='encryption_mode', help='Borg repository encryption mode', required=True, ) init_group.add_argument( '--append-only', dest='append_only', action='store_true', help='Create an append-only repository', ) init_group.add_argument( '--storage-quota', dest='storage_quota', help='Create a repository with a fixed storage quota', ) init_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') prune_parser = subparsers.add_parser( 'prune', aliases=SUBPARSER_ALIASES['prune'], help='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', description='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', add_help=False, ) prune_group = prune_parser.add_argument_group('prune arguments') prune_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) prune_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) prune_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') compact_parser = subparsers.add_parser( 'compact', aliases=SUBPARSER_ALIASES['compact'], help='Compact segments to free space (Borg 1.2+ only)', description='Compact segments to free space (Borg 1.2+ only)', add_help=False, ) compact_group = compact_parser.add_argument_group('compact arguments') compact_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress as each segment is compacted', ) compact_group.add_argument( '--cleanup-commits', dest='cleanup_commits', default=False, action='store_true', help='Cleanup commit-only 17-byte segment files left behind by Borg 1.1', ) compact_group.add_argument( '--threshold', type=int, dest='threshold', help='Minimum saved space percentage threshold for compacting a segment, defaults to 10', ) compact_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) create_parser = subparsers.add_parser( 'create', aliases=SUBPARSER_ALIASES['create'], help='Create archives (actually perform backups)', description='Create archives (actually perform backups)', add_help=False, ) create_group = create_parser.add_argument_group('create arguments') create_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is backed up', ) create_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) create_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) create_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) create_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') check_parser = subparsers.add_parser( 'check', aliases=SUBPARSER_ALIASES['check'], help='Check archives for consistency', description='Check archives for consistency', add_help=False, ) check_group = check_parser.add_argument_group('check arguments') check_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is checked', ) check_group.add_argument( '--repair', dest='repair', default=False, action='store_true', help='Attempt to repair any inconsistencies found (for interactive use)', ) check_group.add_argument( '--only', metavar='CHECK', choices=('repository', 'archives', 'data', 'extract'), dest='only', action='append', help='Run a particular consistency check (repository, archives, data, or extract) instead of configured checks (subject to configured frequency, can specify flag multiple times)', ) check_group.add_argument( '--force', default=False, action='store_true', help='Ignore configured check frequencies and run checks unconditionally', ) check_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') extract_parser = subparsers.add_parser( 'extract', aliases=SUBPARSER_ALIASES['extract'], help='Extract files from a named archive to the current directory', description='Extract a named archive to the current directory', add_help=False, ) extract_group = extract_parser.add_argument_group('extract arguments') extract_group.add_argument( '--repository', help='Path of repository to extract, defaults to the configured repository if there is only one', ) extract_group.add_argument( '--archive', help='Name of archive to extract (or "latest")', required=True ) extract_group.add_argument( '--path', '--restore-path', metavar='PATH', nargs='+', dest='paths', help='Paths to extract from archive, defaults to the entire archive', ) extract_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Directory to extract files into, defaults to the current directory', ) extract_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each extracted path. Skip paths with fewer elements', ) extract_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is extracted', ) extract_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) export_tar_parser = subparsers.add_parser( 'export-tar', aliases=SUBPARSER_ALIASES['export-tar'], help='Export an archive to a tar-formatted file or stream', description='Export an archive to a tar-formatted file or stream', add_help=False, ) export_tar_group = export_tar_parser.add_argument_group('export-tar arguments') export_tar_group.add_argument( '--repository', help='Path of repository to export from, defaults to the configured repository if there is only one', ) export_tar_group.add_argument( '--archive', help='Name of archive to export (or "latest")', required=True ) export_tar_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to export from archive, defaults to the entire archive', ) export_tar_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Path to destination export tar file, or "-" for stdout (but be careful about dirtying output with --verbosity or --files)', required=True, ) export_tar_group.add_argument( '--tar-filter', help='Name of filter program to pipe data through' ) export_tar_group.add_argument( '--files', default=False, action='store_true', help='Show per-file details' ) export_tar_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each exported path. Skip paths with fewer elements', ) export_tar_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) mount_parser = subparsers.add_parser( 'mount', aliases=SUBPARSER_ALIASES['mount'], help='Mount files from a named archive as a FUSE filesystem', description='Mount a named archive as a FUSE filesystem', add_help=False, ) mount_group = mount_parser.add_argument_group('mount arguments') mount_group.add_argument( '--repository', help='Path of repository to use, defaults to the configured repository if there is only one', ) mount_group.add_argument('--archive', help='Name of archive to mount (or "latest")') mount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path where filesystem is to be mounted', required=True, ) mount_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to mount from archive, defaults to the entire archive', ) mount_group.add_argument( '--foreground', dest='foreground', default=False, action='store_true', help='Stay in foreground until ctrl-C is pressed', ) mount_group.add_argument('--options', dest='options', help='Extra Borg mount options') mount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') umount_parser = subparsers.add_parser( 'umount', aliases=SUBPARSER_ALIASES['umount'], help='Unmount a FUSE filesystem that was mounted with "borgmatic mount"', description='Unmount a mounted FUSE filesystem', add_help=False, ) umount_group = umount_parser.add_argument_group('umount arguments') umount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path of filesystem to unmount', required=True, ) umount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') restore_parser = subparsers.add_parser( 'restore', aliases=SUBPARSER_ALIASES['restore'], help='Restore database dumps from a named archive', description='Restore database dumps from a named archive. (To extract files instead, use "borgmatic extract".)', add_help=False, ) restore_group = restore_parser.add_argument_group('restore arguments') restore_group.add_argument( '--repository', help='Path of repository to restore from, defaults to the configured repository if there is only one', ) restore_group.add_argument( '--archive', help='Name of archive to restore from (or "latest")', required=True ) restore_group.add_argument( '--database', metavar='NAME', nargs='+', dest='databases', help='Names of databases to restore from archive, defaults to all databases. Note that any databases to restore must be defined in borgmatic\'s configuration', ) restore_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) list_parser = subparsers.add_parser( 'list', aliases=SUBPARSER_ALIASES['list'], help='List archives', description='List archives or the contents of an archive', add_help=False, ) list_group = list_parser.add_argument_group('list arguments') list_group.add_argument( '--repository', help='Path of repository to list, defaults to the configured repositories', ) list_group.add_argument('--archive', help='Name of archive to list (or "latest")') list_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths or patterns to list from a single selected archive (via "--archive"), defaults to listing the entire archive', ) list_group.add_argument( '--find', metavar='PATH', nargs='+', dest='find_paths', help='Partial paths or patterns to search for and list across multiple archives', ) list_group.add_argument( '--short', default=False, action='store_true', help='Output only archive or path names' ) list_group.add_argument('--format', help='Format for file listing') list_group.add_argument( '--json', default=False, action='store_true', help='Output results as JSON' ) list_group.add_argument( '-P', '--prefix', help='Only list archive names starting with this prefix' ) list_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only list archive names matching this glob' ) list_group.add_argument( '--successful', default=True, action='store_true', help='Deprecated in favor of listing successful (non-checkpoint) backups by default in newer versions of Borg', ) list_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) list_group.add_argument( '--first', metavar='N', help='List first N archives after other filters are applied' ) list_group.add_argument( '--last', metavar='N', help='List last N archives after other filters are applied' ) list_group.add_argument( '-e', '--exclude', metavar='PATTERN', help='Exclude paths matching the pattern' ) list_group.add_argument( '--exclude-from', metavar='FILENAME', help='Exclude paths from exclude file, one per line' ) list_group.add_argument('--pattern', help='Include or exclude paths matching a pattern') list_group.add_argument( '--patterns-from', metavar='FILENAME', help='Include or exclude paths matching patterns from pattern file, one per line', ) list_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') info_parser = subparsers.add_parser( 'info', aliases=SUBPARSER_ALIASES['info'], help='Display summary information on archives', description='Display summary information on archives', add_help=False, ) info_group = info_parser.add_argument_group('info arguments') info_group.add_argument( '--repository', help='Path of repository to show info for, defaults to the configured repository if there is only one', ) info_group.add_argument('--archive', help='Name of archive to show info for (or "latest")') info_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) info_group.add_argument( '-P', '--prefix', help='Only show info for archive names starting with this prefix' ) info_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only show info for archive names matching this glob', ) info_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) info_group.add_argument( '--first', metavar='N', help='Show info for first N archives after other filters are applied', ) info_group.add_argument( '--last', metavar='N', help='Show info for last N archives after other filters are applied' ) info_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') borg_parser = subparsers.add_parser( 'borg', aliases=SUBPARSER_ALIASES['borg'], help='Run an arbitrary Borg command', description='Run an arbitrary Borg command based on borgmatic\'s configuration', add_help=False, ) borg_group = borg_parser.add_argument_group('borg arguments') borg_group.add_argument( '--repository', help='Path of repository to pass to Borg, defaults to the configured repositories', ) borg_group.add_argument('--archive', help='Name of archive to pass to Borg (or "latest")') borg_group.add_argument( '--', metavar='OPTION', dest='options', nargs='+', help='Options to pass to Borg, command first ("create", "list", etc). "--" is optional. To specify the repository or the archive, you must use --repository or --archive instead of providing them here.', ) borg_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') return top_level_parser, subparsers def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. ''' top_level_parser, subparsers = make_parsers() arguments, remaining_arguments = parse_subparser_arguments( unparsed_arguments, subparsers.choices ) arguments['global'] = top_level_parser.parse_args(remaining_arguments) if arguments['global'].excludes_filename: raise ValueError( 'The --excludes option has been replaced with exclude_patterns in configuration' ) if 'init' in arguments and arguments['global'].dry_run: raise ValueError('The init action cannot be used with the --dry-run option') if ( 'list' in arguments and 'info' in arguments and arguments['list'].json and arguments['info'].json ): raise ValueError('With the --json option, list and info actions cannot be used together') return arguments
borgmatic/commands/arguments.py
codereval_python_data_113
Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). def parse_subparser_arguments(unparsed_arguments, subparsers): ''' Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). ''' arguments = collections.OrderedDict() remaining_arguments = list(unparsed_arguments) alias_to_subparser_name = { alias: subparser_name for subparser_name, aliases in SUBPARSER_ALIASES.items() for alias in aliases } # If the "borg" action is used, skip all other subparsers. This avoids confusion like # "borg list" triggering borgmatic's own list action. if 'borg' in unparsed_arguments: subparsers = {'borg': subparsers['borg']} for subparser_name, subparser in subparsers.items(): if subparser_name not in remaining_arguments: continue canonical_name = alias_to_subparser_name.get(subparser_name, subparser_name) # If a parsed value happens to be the same as the name of a subparser, remove it from the # remaining arguments. This prevents, for instance, "check --only extract" from triggering # the "extract" subparser. parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) for value in vars(parsed).values(): if isinstance(value, str): if value in subparsers: remaining_arguments.remove(value) elif isinstance(value, list): for item in value: if item in subparsers: remaining_arguments.remove(item) arguments[canonical_name] = parsed # If no actions are explicitly requested, assume defaults: prune, compact, create, and check. if not arguments and '--help' not in unparsed_arguments and '-h' not in unparsed_arguments: for subparser_name in ('prune', 'compact', 'create', 'check'): subparser = subparsers[subparser_name] parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) arguments[subparser_name] = parsed remaining_arguments = list(unparsed_arguments) # Now ask each subparser, one by one, to greedily consume arguments. for subparser_name, subparser in subparsers.items(): if subparser_name not in arguments.keys(): continue subparser = subparsers[subparser_name] unused_parsed, remaining_arguments = subparser.parse_known_args(remaining_arguments) # Special case: If "borg" is present in the arguments, consume all arguments after (+1) the # "borg" action. if 'borg' in arguments: borg_options_index = remaining_arguments.index('borg') + 1 arguments['borg'].options = remaining_arguments[borg_options_index:] remaining_arguments = remaining_arguments[:borg_options_index] # Remove the subparser names themselves. for subparser_name, subparser in subparsers.items(): if subparser_name in remaining_arguments: remaining_arguments.remove(subparser_name) return (arguments, remaining_arguments) import collections from argparse import Action, ArgumentParser from borgmatic.config import collect SUBPARSER_ALIASES = { 'init': ['--init', '-I'], 'prune': ['--prune', '-p'], 'compact': [], 'create': ['--create', '-C'], 'check': ['--check', '-k'], 'extract': ['--extract', '-x'], 'export-tar': ['--export-tar'], 'mount': ['--mount', '-m'], 'umount': ['--umount', '-u'], 'restore': ['--restore', '-r'], 'list': ['--list', '-l'], 'info': ['--info', '-i'], 'borg': [], } def parse_subparser_arguments(unparsed_arguments, subparsers): ''' Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). ''' arguments = collections.OrderedDict() remaining_arguments = list(unparsed_arguments) alias_to_subparser_name = { alias: subparser_name for subparser_name, aliases in SUBPARSER_ALIASES.items() for alias in aliases } # If the "borg" action is used, skip all other subparsers. This avoids confusion like # "borg list" triggering borgmatic's own list action. if 'borg' in unparsed_arguments: subparsers = {'borg': subparsers['borg']} for subparser_name, subparser in subparsers.items(): if subparser_name not in remaining_arguments: continue canonical_name = alias_to_subparser_name.get(subparser_name, subparser_name) # If a parsed value happens to be the same as the name of a subparser, remove it from the # remaining arguments. This prevents, for instance, "check --only extract" from triggering # the "extract" subparser. parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) for value in vars(parsed).values(): if isinstance(value, str): if value in subparsers: remaining_arguments.remove(value) elif isinstance(value, list): for item in value: if item in subparsers: remaining_arguments.remove(item) arguments[canonical_name] = parsed # If no actions are explicitly requested, assume defaults: prune, compact, create, and check. if not arguments and '--help' not in unparsed_arguments and '-h' not in unparsed_arguments: for subparser_name in ('prune', 'compact', 'create', 'check'): subparser = subparsers[subparser_name] parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) arguments[subparser_name] = parsed remaining_arguments = list(unparsed_arguments) # Now ask each subparser, one by one, to greedily consume arguments. for subparser_name, subparser in subparsers.items(): if subparser_name not in arguments.keys(): continue subparser = subparsers[subparser_name] unused_parsed, remaining_arguments = subparser.parse_known_args(remaining_arguments) # Special case: If "borg" is present in the arguments, consume all arguments after (+1) the # "borg" action. if 'borg' in arguments: borg_options_index = remaining_arguments.index('borg') + 1 arguments['borg'].options = remaining_arguments[borg_options_index:] remaining_arguments = remaining_arguments[:borg_options_index] # Remove the subparser names themselves. for subparser_name, subparser in subparsers.items(): if subparser_name in remaining_arguments: remaining_arguments.remove(subparser_name) return (arguments, remaining_arguments) class Extend_action(Action): ''' An argparse action to support Python 3.8's "extend" action in older versions of Python. ''' def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest, None) if items: items.extend(values) else: setattr(namespace, self.dest, list(values)) def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(expand_home=False) global_parser = ArgumentParser(add_help=False) global_parser.register('action', 'extend', Extend_action) global_group = global_parser.add_argument_group('global arguments') global_group.add_argument( '-c', '--config', nargs='*', dest='config_paths', default=config_paths, help='Configuration filenames or directories, defaults to: {}'.format( ' '.join(unexpanded_config_paths) ), ) global_group.add_argument( '--excludes', dest='excludes_filename', help='Deprecated in favor of exclude_patterns within configuration', ) global_group.add_argument( '-n', '--dry-run', dest='dry_run', action='store_true', help='Go through the motions, but do not actually write to any repositories', ) global_group.add_argument( '-nc', '--no-color', dest='no_color', action='store_true', help='Disable colored output' ) global_group.add_argument( '-v', '--verbosity', type=int, choices=range(-1, 3), default=0, help='Display verbose progress to the console (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--syslog-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to syslog (from only errors to very verbose: -1, 0, 1, or 2). Ignored when console is interactive or --log-file is given', ) global_group.add_argument( '--log-file-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to log file (from only errors to very verbose: -1, 0, 1, or 2). Only used when --log-file is given', ) global_group.add_argument( '--monitoring-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to monitoring integrations that support logging (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--log-file', type=str, default=None, help='Write log messages to this file instead of syslog', ) global_group.add_argument( '--override', metavar='SECTION.OPTION=VALUE', nargs='+', dest='overrides', action='extend', help='One or more configuration file options to override with specified values', ) global_group.add_argument( '--no-environment-interpolation', dest='resolve_env', action='store_false', help='Do not resolve environment variables in configuration file', ) global_group.add_argument( '--bash-completion', default=False, action='store_true', help='Show bash completion script and exit', ) global_group.add_argument( '--version', dest='version', default=False, action='store_true', help='Display installed version number of borgmatic and exit', ) top_level_parser = ArgumentParser( description=''' Simple, configuration-driven backup software for servers and workstations. If none of the action options are given, then borgmatic defaults to: prune, compact, create, and check. ''', parents=[global_parser], ) subparsers = top_level_parser.add_subparsers( title='actions', metavar='', help='Specify zero or more actions. Defaults to prune, compact, create, and check. Use --help with action for details:', ) init_parser = subparsers.add_parser( 'init', aliases=SUBPARSER_ALIASES['init'], help='Initialize an empty Borg repository', description='Initialize an empty Borg repository', add_help=False, ) init_group = init_parser.add_argument_group('init arguments') init_group.add_argument( '-e', '--encryption', dest='encryption_mode', help='Borg repository encryption mode', required=True, ) init_group.add_argument( '--append-only', dest='append_only', action='store_true', help='Create an append-only repository', ) init_group.add_argument( '--storage-quota', dest='storage_quota', help='Create a repository with a fixed storage quota', ) init_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') prune_parser = subparsers.add_parser( 'prune', aliases=SUBPARSER_ALIASES['prune'], help='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', description='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', add_help=False, ) prune_group = prune_parser.add_argument_group('prune arguments') prune_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) prune_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) prune_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') compact_parser = subparsers.add_parser( 'compact', aliases=SUBPARSER_ALIASES['compact'], help='Compact segments to free space (Borg 1.2+ only)', description='Compact segments to free space (Borg 1.2+ only)', add_help=False, ) compact_group = compact_parser.add_argument_group('compact arguments') compact_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress as each segment is compacted', ) compact_group.add_argument( '--cleanup-commits', dest='cleanup_commits', default=False, action='store_true', help='Cleanup commit-only 17-byte segment files left behind by Borg 1.1', ) compact_group.add_argument( '--threshold', type=int, dest='threshold', help='Minimum saved space percentage threshold for compacting a segment, defaults to 10', ) compact_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) create_parser = subparsers.add_parser( 'create', aliases=SUBPARSER_ALIASES['create'], help='Create archives (actually perform backups)', description='Create archives (actually perform backups)', add_help=False, ) create_group = create_parser.add_argument_group('create arguments') create_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is backed up', ) create_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) create_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) create_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) create_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') check_parser = subparsers.add_parser( 'check', aliases=SUBPARSER_ALIASES['check'], help='Check archives for consistency', description='Check archives for consistency', add_help=False, ) check_group = check_parser.add_argument_group('check arguments') check_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is checked', ) check_group.add_argument( '--repair', dest='repair', default=False, action='store_true', help='Attempt to repair any inconsistencies found (for interactive use)', ) check_group.add_argument( '--only', metavar='CHECK', choices=('repository', 'archives', 'data', 'extract'), dest='only', action='append', help='Run a particular consistency check (repository, archives, data, or extract) instead of configured checks (subject to configured frequency, can specify flag multiple times)', ) check_group.add_argument( '--force', default=False, action='store_true', help='Ignore configured check frequencies and run checks unconditionally', ) check_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') extract_parser = subparsers.add_parser( 'extract', aliases=SUBPARSER_ALIASES['extract'], help='Extract files from a named archive to the current directory', description='Extract a named archive to the current directory', add_help=False, ) extract_group = extract_parser.add_argument_group('extract arguments') extract_group.add_argument( '--repository', help='Path of repository to extract, defaults to the configured repository if there is only one', ) extract_group.add_argument( '--archive', help='Name of archive to extract (or "latest")', required=True ) extract_group.add_argument( '--path', '--restore-path', metavar='PATH', nargs='+', dest='paths', help='Paths to extract from archive, defaults to the entire archive', ) extract_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Directory to extract files into, defaults to the current directory', ) extract_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each extracted path. Skip paths with fewer elements', ) extract_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is extracted', ) extract_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) export_tar_parser = subparsers.add_parser( 'export-tar', aliases=SUBPARSER_ALIASES['export-tar'], help='Export an archive to a tar-formatted file or stream', description='Export an archive to a tar-formatted file or stream', add_help=False, ) export_tar_group = export_tar_parser.add_argument_group('export-tar arguments') export_tar_group.add_argument( '--repository', help='Path of repository to export from, defaults to the configured repository if there is only one', ) export_tar_group.add_argument( '--archive', help='Name of archive to export (or "latest")', required=True ) export_tar_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to export from archive, defaults to the entire archive', ) export_tar_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Path to destination export tar file, or "-" for stdout (but be careful about dirtying output with --verbosity or --files)', required=True, ) export_tar_group.add_argument( '--tar-filter', help='Name of filter program to pipe data through' ) export_tar_group.add_argument( '--files', default=False, action='store_true', help='Show per-file details' ) export_tar_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each exported path. Skip paths with fewer elements', ) export_tar_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) mount_parser = subparsers.add_parser( 'mount', aliases=SUBPARSER_ALIASES['mount'], help='Mount files from a named archive as a FUSE filesystem', description='Mount a named archive as a FUSE filesystem', add_help=False, ) mount_group = mount_parser.add_argument_group('mount arguments') mount_group.add_argument( '--repository', help='Path of repository to use, defaults to the configured repository if there is only one', ) mount_group.add_argument('--archive', help='Name of archive to mount (or "latest")') mount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path where filesystem is to be mounted', required=True, ) mount_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to mount from archive, defaults to the entire archive', ) mount_group.add_argument( '--foreground', dest='foreground', default=False, action='store_true', help='Stay in foreground until ctrl-C is pressed', ) mount_group.add_argument('--options', dest='options', help='Extra Borg mount options') mount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') umount_parser = subparsers.add_parser( 'umount', aliases=SUBPARSER_ALIASES['umount'], help='Unmount a FUSE filesystem that was mounted with "borgmatic mount"', description='Unmount a mounted FUSE filesystem', add_help=False, ) umount_group = umount_parser.add_argument_group('umount arguments') umount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path of filesystem to unmount', required=True, ) umount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') restore_parser = subparsers.add_parser( 'restore', aliases=SUBPARSER_ALIASES['restore'], help='Restore database dumps from a named archive', description='Restore database dumps from a named archive. (To extract files instead, use "borgmatic extract".)', add_help=False, ) restore_group = restore_parser.add_argument_group('restore arguments') restore_group.add_argument( '--repository', help='Path of repository to restore from, defaults to the configured repository if there is only one', ) restore_group.add_argument( '--archive', help='Name of archive to restore from (or "latest")', required=True ) restore_group.add_argument( '--database', metavar='NAME', nargs='+', dest='databases', help='Names of databases to restore from archive, defaults to all databases. Note that any databases to restore must be defined in borgmatic\'s configuration', ) restore_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) list_parser = subparsers.add_parser( 'list', aliases=SUBPARSER_ALIASES['list'], help='List archives', description='List archives or the contents of an archive', add_help=False, ) list_group = list_parser.add_argument_group('list arguments') list_group.add_argument( '--repository', help='Path of repository to list, defaults to the configured repositories', ) list_group.add_argument('--archive', help='Name of archive to list (or "latest")') list_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths or patterns to list from a single selected archive (via "--archive"), defaults to listing the entire archive', ) list_group.add_argument( '--find', metavar='PATH', nargs='+', dest='find_paths', help='Partial paths or patterns to search for and list across multiple archives', ) list_group.add_argument( '--short', default=False, action='store_true', help='Output only archive or path names' ) list_group.add_argument('--format', help='Format for file listing') list_group.add_argument( '--json', default=False, action='store_true', help='Output results as JSON' ) list_group.add_argument( '-P', '--prefix', help='Only list archive names starting with this prefix' ) list_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only list archive names matching this glob' ) list_group.add_argument( '--successful', default=True, action='store_true', help='Deprecated in favor of listing successful (non-checkpoint) backups by default in newer versions of Borg', ) list_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) list_group.add_argument( '--first', metavar='N', help='List first N archives after other filters are applied' ) list_group.add_argument( '--last', metavar='N', help='List last N archives after other filters are applied' ) list_group.add_argument( '-e', '--exclude', metavar='PATTERN', help='Exclude paths matching the pattern' ) list_group.add_argument( '--exclude-from', metavar='FILENAME', help='Exclude paths from exclude file, one per line' ) list_group.add_argument('--pattern', help='Include or exclude paths matching a pattern') list_group.add_argument( '--patterns-from', metavar='FILENAME', help='Include or exclude paths matching patterns from pattern file, one per line', ) list_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') info_parser = subparsers.add_parser( 'info', aliases=SUBPARSER_ALIASES['info'], help='Display summary information on archives', description='Display summary information on archives', add_help=False, ) info_group = info_parser.add_argument_group('info arguments') info_group.add_argument( '--repository', help='Path of repository to show info for, defaults to the configured repository if there is only one', ) info_group.add_argument('--archive', help='Name of archive to show info for (or "latest")') info_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) info_group.add_argument( '-P', '--prefix', help='Only show info for archive names starting with this prefix' ) info_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only show info for archive names matching this glob', ) info_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) info_group.add_argument( '--first', metavar='N', help='Show info for first N archives after other filters are applied', ) info_group.add_argument( '--last', metavar='N', help='Show info for last N archives after other filters are applied' ) info_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') borg_parser = subparsers.add_parser( 'borg', aliases=SUBPARSER_ALIASES['borg'], help='Run an arbitrary Borg command', description='Run an arbitrary Borg command based on borgmatic\'s configuration', add_help=False, ) borg_group = borg_parser.add_argument_group('borg arguments') borg_group.add_argument( '--repository', help='Path of repository to pass to Borg, defaults to the configured repositories', ) borg_group.add_argument('--archive', help='Name of archive to pass to Borg (or "latest")') borg_group.add_argument( '--', metavar='OPTION', dest='options', nargs='+', help='Options to pass to Borg, command first ("create", "list", etc). "--" is optional. To specify the repository or the archive, you must use --repository or --archive instead of providing them here.', ) borg_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') return top_level_parser, subparsers def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. ''' top_level_parser, subparsers = make_parsers() arguments, remaining_arguments = parse_subparser_arguments( unparsed_arguments, subparsers.choices ) arguments['global'] = top_level_parser.parse_args(remaining_arguments) if arguments['global'].excludes_filename: raise ValueError( 'The --excludes option has been replaced with exclude_patterns in configuration' ) if 'init' in arguments and arguments['global'].dry_run: raise ValueError('The init action cannot be used with the --dry-run option') if ( 'list' in arguments and 'info' in arguments and arguments['list'].json and arguments['info'].json ): raise ValueError('With the --json option, list and info actions cannot be used together') return arguments
borgmatic/commands/arguments.py
codereval_python_data_114
Build a top-level parser and its subparsers and return them as a tuple. def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(expand_home=False) global_parser = ArgumentParser(add_help=False) global_parser.register('action', 'extend', Extend_action) global_group = global_parser.add_argument_group('global arguments') global_group.add_argument( '-c', '--config', nargs='*', dest='config_paths', default=config_paths, help='Configuration filenames or directories, defaults to: {}'.format( ' '.join(unexpanded_config_paths) ), ) global_group.add_argument( '--excludes', dest='excludes_filename', help='Deprecated in favor of exclude_patterns within configuration', ) global_group.add_argument( '-n', '--dry-run', dest='dry_run', action='store_true', help='Go through the motions, but do not actually write to any repositories', ) global_group.add_argument( '-nc', '--no-color', dest='no_color', action='store_true', help='Disable colored output' ) global_group.add_argument( '-v', '--verbosity', type=int, choices=range(-1, 3), default=0, help='Display verbose progress to the console (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--syslog-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to syslog (from only errors to very verbose: -1, 0, 1, or 2). Ignored when console is interactive or --log-file is given', ) global_group.add_argument( '--log-file-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to log file (from only errors to very verbose: -1, 0, 1, or 2). Only used when --log-file is given', ) global_group.add_argument( '--monitoring-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to monitoring integrations that support logging (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--log-file', type=str, default=None, help='Write log messages to this file instead of syslog', ) global_group.add_argument( '--override', metavar='SECTION.OPTION=VALUE', nargs='+', dest='overrides', action='extend', help='One or more configuration file options to override with specified values', ) global_group.add_argument( '--no-environment-interpolation', dest='resolve_env', action='store_false', help='Do not resolve environment variables in configuration file', ) global_group.add_argument( '--bash-completion', default=False, action='store_true', help='Show bash completion script and exit', ) global_group.add_argument( '--version', dest='version', default=False, action='store_true', help='Display installed version number of borgmatic and exit', ) top_level_parser = ArgumentParser( description=''' Simple, configuration-driven backup software for servers and workstations. If none of the action options are given, then borgmatic defaults to: prune, compact, create, and check. ''', parents=[global_parser], ) subparsers = top_level_parser.add_subparsers( title='actions', metavar='', help='Specify zero or more actions. Defaults to prune, compact, create, and check. Use --help with action for details:', ) init_parser = subparsers.add_parser( 'init', aliases=SUBPARSER_ALIASES['init'], help='Initialize an empty Borg repository', description='Initialize an empty Borg repository', add_help=False, ) init_group = init_parser.add_argument_group('init arguments') init_group.add_argument( '-e', '--encryption', dest='encryption_mode', help='Borg repository encryption mode', required=True, ) init_group.add_argument( '--append-only', dest='append_only', action='store_true', help='Create an append-only repository', ) init_group.add_argument( '--storage-quota', dest='storage_quota', help='Create a repository with a fixed storage quota', ) init_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') prune_parser = subparsers.add_parser( 'prune', aliases=SUBPARSER_ALIASES['prune'], help='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', description='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', add_help=False, ) prune_group = prune_parser.add_argument_group('prune arguments') prune_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) prune_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) prune_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') compact_parser = subparsers.add_parser( 'compact', aliases=SUBPARSER_ALIASES['compact'], help='Compact segments to free space (Borg 1.2+ only)', description='Compact segments to free space (Borg 1.2+ only)', add_help=False, ) compact_group = compact_parser.add_argument_group('compact arguments') compact_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress as each segment is compacted', ) compact_group.add_argument( '--cleanup-commits', dest='cleanup_commits', default=False, action='store_true', help='Cleanup commit-only 17-byte segment files left behind by Borg 1.1', ) compact_group.add_argument( '--threshold', type=int, dest='threshold', help='Minimum saved space percentage threshold for compacting a segment, defaults to 10', ) compact_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) create_parser = subparsers.add_parser( 'create', aliases=SUBPARSER_ALIASES['create'], help='Create archives (actually perform backups)', description='Create archives (actually perform backups)', add_help=False, ) create_group = create_parser.add_argument_group('create arguments') create_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is backed up', ) create_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) create_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) create_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) create_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') check_parser = subparsers.add_parser( 'check', aliases=SUBPARSER_ALIASES['check'], help='Check archives for consistency', description='Check archives for consistency', add_help=False, ) check_group = check_parser.add_argument_group('check arguments') check_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is checked', ) check_group.add_argument( '--repair', dest='repair', default=False, action='store_true', help='Attempt to repair any inconsistencies found (for interactive use)', ) check_group.add_argument( '--only', metavar='CHECK', choices=('repository', 'archives', 'data', 'extract'), dest='only', action='append', help='Run a particular consistency check (repository, archives, data, or extract) instead of configured checks (subject to configured frequency, can specify flag multiple times)', ) check_group.add_argument( '--force', default=False, action='store_true', help='Ignore configured check frequencies and run checks unconditionally', ) check_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') extract_parser = subparsers.add_parser( 'extract', aliases=SUBPARSER_ALIASES['extract'], help='Extract files from a named archive to the current directory', description='Extract a named archive to the current directory', add_help=False, ) extract_group = extract_parser.add_argument_group('extract arguments') extract_group.add_argument( '--repository', help='Path of repository to extract, defaults to the configured repository if there is only one', ) extract_group.add_argument( '--archive', help='Name of archive to extract (or "latest")', required=True ) extract_group.add_argument( '--path', '--restore-path', metavar='PATH', nargs='+', dest='paths', help='Paths to extract from archive, defaults to the entire archive', ) extract_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Directory to extract files into, defaults to the current directory', ) extract_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each extracted path. Skip paths with fewer elements', ) extract_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is extracted', ) extract_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) export_tar_parser = subparsers.add_parser( 'export-tar', aliases=SUBPARSER_ALIASES['export-tar'], help='Export an archive to a tar-formatted file or stream', description='Export an archive to a tar-formatted file or stream', add_help=False, ) export_tar_group = export_tar_parser.add_argument_group('export-tar arguments') export_tar_group.add_argument( '--repository', help='Path of repository to export from, defaults to the configured repository if there is only one', ) export_tar_group.add_argument( '--archive', help='Name of archive to export (or "latest")', required=True ) export_tar_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to export from archive, defaults to the entire archive', ) export_tar_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Path to destination export tar file, or "-" for stdout (but be careful about dirtying output with --verbosity or --files)', required=True, ) export_tar_group.add_argument( '--tar-filter', help='Name of filter program to pipe data through' ) export_tar_group.add_argument( '--files', default=False, action='store_true', help='Show per-file details' ) export_tar_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each exported path. Skip paths with fewer elements', ) export_tar_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) mount_parser = subparsers.add_parser( 'mount', aliases=SUBPARSER_ALIASES['mount'], help='Mount files from a named archive as a FUSE filesystem', description='Mount a named archive as a FUSE filesystem', add_help=False, ) mount_group = mount_parser.add_argument_group('mount arguments') mount_group.add_argument( '--repository', help='Path of repository to use, defaults to the configured repository if there is only one', ) mount_group.add_argument('--archive', help='Name of archive to mount (or "latest")') mount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path where filesystem is to be mounted', required=True, ) mount_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to mount from archive, defaults to the entire archive', ) mount_group.add_argument( '--foreground', dest='foreground', default=False, action='store_true', help='Stay in foreground until ctrl-C is pressed', ) mount_group.add_argument('--options', dest='options', help='Extra Borg mount options') mount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') umount_parser = subparsers.add_parser( 'umount', aliases=SUBPARSER_ALIASES['umount'], help='Unmount a FUSE filesystem that was mounted with "borgmatic mount"', description='Unmount a mounted FUSE filesystem', add_help=False, ) umount_group = umount_parser.add_argument_group('umount arguments') umount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path of filesystem to unmount', required=True, ) umount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') restore_parser = subparsers.add_parser( 'restore', aliases=SUBPARSER_ALIASES['restore'], help='Restore database dumps from a named archive', description='Restore database dumps from a named archive. (To extract files instead, use "borgmatic extract".)', add_help=False, ) restore_group = restore_parser.add_argument_group('restore arguments') restore_group.add_argument( '--repository', help='Path of repository to restore from, defaults to the configured repository if there is only one', ) restore_group.add_argument( '--archive', help='Name of archive to restore from (or "latest")', required=True ) restore_group.add_argument( '--database', metavar='NAME', nargs='+', dest='databases', help='Names of databases to restore from archive, defaults to all databases. Note that any databases to restore must be defined in borgmatic\'s configuration', ) restore_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) list_parser = subparsers.add_parser( 'list', aliases=SUBPARSER_ALIASES['list'], help='List archives', description='List archives or the contents of an archive', add_help=False, ) list_group = list_parser.add_argument_group('list arguments') list_group.add_argument( '--repository', help='Path of repository to list, defaults to the configured repositories', ) list_group.add_argument('--archive', help='Name of archive to list (or "latest")') list_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths or patterns to list from a single selected archive (via "--archive"), defaults to listing the entire archive', ) list_group.add_argument( '--find', metavar='PATH', nargs='+', dest='find_paths', help='Partial paths or patterns to search for and list across multiple archives', ) list_group.add_argument( '--short', default=False, action='store_true', help='Output only archive or path names' ) list_group.add_argument('--format', help='Format for file listing') list_group.add_argument( '--json', default=False, action='store_true', help='Output results as JSON' ) list_group.add_argument( '-P', '--prefix', help='Only list archive names starting with this prefix' ) list_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only list archive names matching this glob' ) list_group.add_argument( '--successful', default=True, action='store_true', help='Deprecated in favor of listing successful (non-checkpoint) backups by default in newer versions of Borg', ) list_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) list_group.add_argument( '--first', metavar='N', help='List first N archives after other filters are applied' ) list_group.add_argument( '--last', metavar='N', help='List last N archives after other filters are applied' ) list_group.add_argument( '-e', '--exclude', metavar='PATTERN', help='Exclude paths matching the pattern' ) list_group.add_argument( '--exclude-from', metavar='FILENAME', help='Exclude paths from exclude file, one per line' ) list_group.add_argument('--pattern', help='Include or exclude paths matching a pattern') list_group.add_argument( '--patterns-from', metavar='FILENAME', help='Include or exclude paths matching patterns from pattern file, one per line', ) list_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') info_parser = subparsers.add_parser( 'info', aliases=SUBPARSER_ALIASES['info'], help='Display summary information on archives', description='Display summary information on archives', add_help=False, ) info_group = info_parser.add_argument_group('info arguments') info_group.add_argument( '--repository', help='Path of repository to show info for, defaults to the configured repository if there is only one', ) info_group.add_argument('--archive', help='Name of archive to show info for (or "latest")') info_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) info_group.add_argument( '-P', '--prefix', help='Only show info for archive names starting with this prefix' ) info_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only show info for archive names matching this glob', ) info_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) info_group.add_argument( '--first', metavar='N', help='Show info for first N archives after other filters are applied', ) info_group.add_argument( '--last', metavar='N', help='Show info for last N archives after other filters are applied' ) info_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') borg_parser = subparsers.add_parser( 'borg', aliases=SUBPARSER_ALIASES['borg'], help='Run an arbitrary Borg command', description='Run an arbitrary Borg command based on borgmatic\'s configuration', add_help=False, ) borg_group = borg_parser.add_argument_group('borg arguments') borg_group.add_argument( '--repository', help='Path of repository to pass to Borg, defaults to the configured repositories', ) borg_group.add_argument('--archive', help='Name of archive to pass to Borg (or "latest")') borg_group.add_argument( '--', metavar='OPTION', dest='options', nargs='+', help='Options to pass to Borg, command first ("create", "list", etc). "--" is optional. To specify the repository or the archive, you must use --repository or --archive instead of providing them here.', ) borg_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') return top_level_parser, subparsers import collections from argparse import Action, ArgumentParser from borgmatic.config import collect SUBPARSER_ALIASES = { 'init': ['--init', '-I'], 'prune': ['--prune', '-p'], 'compact': [], 'create': ['--create', '-C'], 'check': ['--check', '-k'], 'extract': ['--extract', '-x'], 'export-tar': ['--export-tar'], 'mount': ['--mount', '-m'], 'umount': ['--umount', '-u'], 'restore': ['--restore', '-r'], 'list': ['--list', '-l'], 'info': ['--info', '-i'], 'borg': [], } def parse_subparser_arguments(unparsed_arguments, subparsers): ''' Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). ''' arguments = collections.OrderedDict() remaining_arguments = list(unparsed_arguments) alias_to_subparser_name = { alias: subparser_name for subparser_name, aliases in SUBPARSER_ALIASES.items() for alias in aliases } # If the "borg" action is used, skip all other subparsers. This avoids confusion like # "borg list" triggering borgmatic's own list action. if 'borg' in unparsed_arguments: subparsers = {'borg': subparsers['borg']} for subparser_name, subparser in subparsers.items(): if subparser_name not in remaining_arguments: continue canonical_name = alias_to_subparser_name.get(subparser_name, subparser_name) # If a parsed value happens to be the same as the name of a subparser, remove it from the # remaining arguments. This prevents, for instance, "check --only extract" from triggering # the "extract" subparser. parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) for value in vars(parsed).values(): if isinstance(value, str): if value in subparsers: remaining_arguments.remove(value) elif isinstance(value, list): for item in value: if item in subparsers: remaining_arguments.remove(item) arguments[canonical_name] = parsed # If no actions are explicitly requested, assume defaults: prune, compact, create, and check. if not arguments and '--help' not in unparsed_arguments and '-h' not in unparsed_arguments: for subparser_name in ('prune', 'compact', 'create', 'check'): subparser = subparsers[subparser_name] parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) arguments[subparser_name] = parsed remaining_arguments = list(unparsed_arguments) # Now ask each subparser, one by one, to greedily consume arguments. for subparser_name, subparser in subparsers.items(): if subparser_name not in arguments.keys(): continue subparser = subparsers[subparser_name] unused_parsed, remaining_arguments = subparser.parse_known_args(remaining_arguments) # Special case: If "borg" is present in the arguments, consume all arguments after (+1) the # "borg" action. if 'borg' in arguments: borg_options_index = remaining_arguments.index('borg') + 1 arguments['borg'].options = remaining_arguments[borg_options_index:] remaining_arguments = remaining_arguments[:borg_options_index] # Remove the subparser names themselves. for subparser_name, subparser in subparsers.items(): if subparser_name in remaining_arguments: remaining_arguments.remove(subparser_name) return (arguments, remaining_arguments) class Extend_action(Action): ''' An argparse action to support Python 3.8's "extend" action in older versions of Python. ''' def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest, None) if items: items.extend(values) else: setattr(namespace, self.dest, list(values)) def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(expand_home=False) global_parser = ArgumentParser(add_help=False) global_parser.register('action', 'extend', Extend_action) global_group = global_parser.add_argument_group('global arguments') global_group.add_argument( '-c', '--config', nargs='*', dest='config_paths', default=config_paths, help='Configuration filenames or directories, defaults to: {}'.format( ' '.join(unexpanded_config_paths) ), ) global_group.add_argument( '--excludes', dest='excludes_filename', help='Deprecated in favor of exclude_patterns within configuration', ) global_group.add_argument( '-n', '--dry-run', dest='dry_run', action='store_true', help='Go through the motions, but do not actually write to any repositories', ) global_group.add_argument( '-nc', '--no-color', dest='no_color', action='store_true', help='Disable colored output' ) global_group.add_argument( '-v', '--verbosity', type=int, choices=range(-1, 3), default=0, help='Display verbose progress to the console (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--syslog-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to syslog (from only errors to very verbose: -1, 0, 1, or 2). Ignored when console is interactive or --log-file is given', ) global_group.add_argument( '--log-file-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to log file (from only errors to very verbose: -1, 0, 1, or 2). Only used when --log-file is given', ) global_group.add_argument( '--monitoring-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to monitoring integrations that support logging (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--log-file', type=str, default=None, help='Write log messages to this file instead of syslog', ) global_group.add_argument( '--override', metavar='SECTION.OPTION=VALUE', nargs='+', dest='overrides', action='extend', help='One or more configuration file options to override with specified values', ) global_group.add_argument( '--no-environment-interpolation', dest='resolve_env', action='store_false', help='Do not resolve environment variables in configuration file', ) global_group.add_argument( '--bash-completion', default=False, action='store_true', help='Show bash completion script and exit', ) global_group.add_argument( '--version', dest='version', default=False, action='store_true', help='Display installed version number of borgmatic and exit', ) top_level_parser = ArgumentParser( description=''' Simple, configuration-driven backup software for servers and workstations. If none of the action options are given, then borgmatic defaults to: prune, compact, create, and check. ''', parents=[global_parser], ) subparsers = top_level_parser.add_subparsers( title='actions', metavar='', help='Specify zero or more actions. Defaults to prune, compact, create, and check. Use --help with action for details:', ) init_parser = subparsers.add_parser( 'init', aliases=SUBPARSER_ALIASES['init'], help='Initialize an empty Borg repository', description='Initialize an empty Borg repository', add_help=False, ) init_group = init_parser.add_argument_group('init arguments') init_group.add_argument( '-e', '--encryption', dest='encryption_mode', help='Borg repository encryption mode', required=True, ) init_group.add_argument( '--append-only', dest='append_only', action='store_true', help='Create an append-only repository', ) init_group.add_argument( '--storage-quota', dest='storage_quota', help='Create a repository with a fixed storage quota', ) init_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') prune_parser = subparsers.add_parser( 'prune', aliases=SUBPARSER_ALIASES['prune'], help='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', description='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', add_help=False, ) prune_group = prune_parser.add_argument_group('prune arguments') prune_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) prune_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) prune_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') compact_parser = subparsers.add_parser( 'compact', aliases=SUBPARSER_ALIASES['compact'], help='Compact segments to free space (Borg 1.2+ only)', description='Compact segments to free space (Borg 1.2+ only)', add_help=False, ) compact_group = compact_parser.add_argument_group('compact arguments') compact_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress as each segment is compacted', ) compact_group.add_argument( '--cleanup-commits', dest='cleanup_commits', default=False, action='store_true', help='Cleanup commit-only 17-byte segment files left behind by Borg 1.1', ) compact_group.add_argument( '--threshold', type=int, dest='threshold', help='Minimum saved space percentage threshold for compacting a segment, defaults to 10', ) compact_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) create_parser = subparsers.add_parser( 'create', aliases=SUBPARSER_ALIASES['create'], help='Create archives (actually perform backups)', description='Create archives (actually perform backups)', add_help=False, ) create_group = create_parser.add_argument_group('create arguments') create_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is backed up', ) create_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) create_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) create_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) create_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') check_parser = subparsers.add_parser( 'check', aliases=SUBPARSER_ALIASES['check'], help='Check archives for consistency', description='Check archives for consistency', add_help=False, ) check_group = check_parser.add_argument_group('check arguments') check_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is checked', ) check_group.add_argument( '--repair', dest='repair', default=False, action='store_true', help='Attempt to repair any inconsistencies found (for interactive use)', ) check_group.add_argument( '--only', metavar='CHECK', choices=('repository', 'archives', 'data', 'extract'), dest='only', action='append', help='Run a particular consistency check (repository, archives, data, or extract) instead of configured checks (subject to configured frequency, can specify flag multiple times)', ) check_group.add_argument( '--force', default=False, action='store_true', help='Ignore configured check frequencies and run checks unconditionally', ) check_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') extract_parser = subparsers.add_parser( 'extract', aliases=SUBPARSER_ALIASES['extract'], help='Extract files from a named archive to the current directory', description='Extract a named archive to the current directory', add_help=False, ) extract_group = extract_parser.add_argument_group('extract arguments') extract_group.add_argument( '--repository', help='Path of repository to extract, defaults to the configured repository if there is only one', ) extract_group.add_argument( '--archive', help='Name of archive to extract (or "latest")', required=True ) extract_group.add_argument( '--path', '--restore-path', metavar='PATH', nargs='+', dest='paths', help='Paths to extract from archive, defaults to the entire archive', ) extract_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Directory to extract files into, defaults to the current directory', ) extract_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each extracted path. Skip paths with fewer elements', ) extract_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is extracted', ) extract_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) export_tar_parser = subparsers.add_parser( 'export-tar', aliases=SUBPARSER_ALIASES['export-tar'], help='Export an archive to a tar-formatted file or stream', description='Export an archive to a tar-formatted file or stream', add_help=False, ) export_tar_group = export_tar_parser.add_argument_group('export-tar arguments') export_tar_group.add_argument( '--repository', help='Path of repository to export from, defaults to the configured repository if there is only one', ) export_tar_group.add_argument( '--archive', help='Name of archive to export (or "latest")', required=True ) export_tar_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to export from archive, defaults to the entire archive', ) export_tar_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Path to destination export tar file, or "-" for stdout (but be careful about dirtying output with --verbosity or --files)', required=True, ) export_tar_group.add_argument( '--tar-filter', help='Name of filter program to pipe data through' ) export_tar_group.add_argument( '--files', default=False, action='store_true', help='Show per-file details' ) export_tar_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each exported path. Skip paths with fewer elements', ) export_tar_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) mount_parser = subparsers.add_parser( 'mount', aliases=SUBPARSER_ALIASES['mount'], help='Mount files from a named archive as a FUSE filesystem', description='Mount a named archive as a FUSE filesystem', add_help=False, ) mount_group = mount_parser.add_argument_group('mount arguments') mount_group.add_argument( '--repository', help='Path of repository to use, defaults to the configured repository if there is only one', ) mount_group.add_argument('--archive', help='Name of archive to mount (or "latest")') mount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path where filesystem is to be mounted', required=True, ) mount_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to mount from archive, defaults to the entire archive', ) mount_group.add_argument( '--foreground', dest='foreground', default=False, action='store_true', help='Stay in foreground until ctrl-C is pressed', ) mount_group.add_argument('--options', dest='options', help='Extra Borg mount options') mount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') umount_parser = subparsers.add_parser( 'umount', aliases=SUBPARSER_ALIASES['umount'], help='Unmount a FUSE filesystem that was mounted with "borgmatic mount"', description='Unmount a mounted FUSE filesystem', add_help=False, ) umount_group = umount_parser.add_argument_group('umount arguments') umount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path of filesystem to unmount', required=True, ) umount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') restore_parser = subparsers.add_parser( 'restore', aliases=SUBPARSER_ALIASES['restore'], help='Restore database dumps from a named archive', description='Restore database dumps from a named archive. (To extract files instead, use "borgmatic extract".)', add_help=False, ) restore_group = restore_parser.add_argument_group('restore arguments') restore_group.add_argument( '--repository', help='Path of repository to restore from, defaults to the configured repository if there is only one', ) restore_group.add_argument( '--archive', help='Name of archive to restore from (or "latest")', required=True ) restore_group.add_argument( '--database', metavar='NAME', nargs='+', dest='databases', help='Names of databases to restore from archive, defaults to all databases. Note that any databases to restore must be defined in borgmatic\'s configuration', ) restore_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) list_parser = subparsers.add_parser( 'list', aliases=SUBPARSER_ALIASES['list'], help='List archives', description='List archives or the contents of an archive', add_help=False, ) list_group = list_parser.add_argument_group('list arguments') list_group.add_argument( '--repository', help='Path of repository to list, defaults to the configured repositories', ) list_group.add_argument('--archive', help='Name of archive to list (or "latest")') list_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths or patterns to list from a single selected archive (via "--archive"), defaults to listing the entire archive', ) list_group.add_argument( '--find', metavar='PATH', nargs='+', dest='find_paths', help='Partial paths or patterns to search for and list across multiple archives', ) list_group.add_argument( '--short', default=False, action='store_true', help='Output only archive or path names' ) list_group.add_argument('--format', help='Format for file listing') list_group.add_argument( '--json', default=False, action='store_true', help='Output results as JSON' ) list_group.add_argument( '-P', '--prefix', help='Only list archive names starting with this prefix' ) list_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only list archive names matching this glob' ) list_group.add_argument( '--successful', default=True, action='store_true', help='Deprecated in favor of listing successful (non-checkpoint) backups by default in newer versions of Borg', ) list_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) list_group.add_argument( '--first', metavar='N', help='List first N archives after other filters are applied' ) list_group.add_argument( '--last', metavar='N', help='List last N archives after other filters are applied' ) list_group.add_argument( '-e', '--exclude', metavar='PATTERN', help='Exclude paths matching the pattern' ) list_group.add_argument( '--exclude-from', metavar='FILENAME', help='Exclude paths from exclude file, one per line' ) list_group.add_argument('--pattern', help='Include or exclude paths matching a pattern') list_group.add_argument( '--patterns-from', metavar='FILENAME', help='Include or exclude paths matching patterns from pattern file, one per line', ) list_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') info_parser = subparsers.add_parser( 'info', aliases=SUBPARSER_ALIASES['info'], help='Display summary information on archives', description='Display summary information on archives', add_help=False, ) info_group = info_parser.add_argument_group('info arguments') info_group.add_argument( '--repository', help='Path of repository to show info for, defaults to the configured repository if there is only one', ) info_group.add_argument('--archive', help='Name of archive to show info for (or "latest")') info_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) info_group.add_argument( '-P', '--prefix', help='Only show info for archive names starting with this prefix' ) info_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only show info for archive names matching this glob', ) info_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) info_group.add_argument( '--first', metavar='N', help='Show info for first N archives after other filters are applied', ) info_group.add_argument( '--last', metavar='N', help='Show info for last N archives after other filters are applied' ) info_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') borg_parser = subparsers.add_parser( 'borg', aliases=SUBPARSER_ALIASES['borg'], help='Run an arbitrary Borg command', description='Run an arbitrary Borg command based on borgmatic\'s configuration', add_help=False, ) borg_group = borg_parser.add_argument_group('borg arguments') borg_group.add_argument( '--repository', help='Path of repository to pass to Borg, defaults to the configured repositories', ) borg_group.add_argument('--archive', help='Name of archive to pass to Borg (or "latest")') borg_group.add_argument( '--', metavar='OPTION', dest='options', nargs='+', help='Options to pass to Borg, command first ("create", "list", etc). "--" is optional. To specify the repository or the archive, you must use --repository or --archive instead of providing them here.', ) borg_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') return top_level_parser, subparsers def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. ''' top_level_parser, subparsers = make_parsers() arguments, remaining_arguments = parse_subparser_arguments( unparsed_arguments, subparsers.choices ) arguments['global'] = top_level_parser.parse_args(remaining_arguments) if arguments['global'].excludes_filename: raise ValueError( 'The --excludes option has been replaced with exclude_patterns in configuration' ) if 'init' in arguments and arguments['global'].dry_run: raise ValueError('The init action cannot be used with the --dry-run option') if ( 'list' in arguments and 'info' in arguments and arguments['list'].json and arguments['info'].json ): raise ValueError('With the --json option, list and info actions cannot be used together') return arguments
borgmatic/commands/arguments.py
codereval_python_data_115
Given a nested borgmatic configuration data structure as a list of tuples in the form of: ( ruamel.yaml.nodes.ScalarNode as a key, ruamel.yaml.nodes.MappingNode or other Node as a value, ), ... deep merge any node values corresponding to duplicate keys and return the result. If there are colliding keys with non-MappingNode values (e.g., integers or strings), the last of the values wins. For instance, given node values of: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='7') ), ]), ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] ... the returned result would be: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] The purpose of deep merging like this is to support, for instance, merging one borgmatic configuration file into another for reuse, such that a configuration section ("retention", etc.) does not completely replace the corresponding section in a merged file. def deep_merge_nodes(nodes): ''' Given a nested borgmatic configuration data structure as a list of tuples in the form of: ( ruamel.yaml.nodes.ScalarNode as a key, ruamel.yaml.nodes.MappingNode or other Node as a value, ), ... deep merge any node values corresponding to duplicate keys and return the result. If there are colliding keys with non-MappingNode values (e.g., integers or strings), the last of the values wins. For instance, given node values of: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='7') ), ]), ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] ... the returned result would be: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] The purpose of deep merging like this is to support, for instance, merging one borgmatic configuration file into another for reuse, such that a configuration section ("retention", etc.) does not completely replace the corresponding section in a merged file. ''' # Map from original node key/value to the replacement merged node. DELETED_NODE as a replacement # node indications deletion. replaced_nodes = {} # To find nodes that require merging, compare each node with each other node. for a_key, a_value in nodes: for b_key, b_value in nodes: # If we've already considered one of the nodes for merging, skip it. if (a_key, a_value) in replaced_nodes or (b_key, b_value) in replaced_nodes: continue # If the keys match and the values are different, we need to merge these two A and B nodes. if a_key.tag == b_key.tag and a_key.value == b_key.value and a_value != b_value: # Since we're merging into the B node, consider the A node a duplicate and remove it. replaced_nodes[(a_key, a_value)] = DELETED_NODE # If we're dealing with MappingNodes, recurse and merge its values as well. if isinstance(b_value, ruamel.yaml.nodes.MappingNode): replaced_nodes[(b_key, b_value)] = ( b_key, ruamel.yaml.nodes.MappingNode( tag=b_value.tag, value=deep_merge_nodes(a_value.value + b_value.value), start_mark=b_value.start_mark, end_mark=b_value.end_mark, flow_style=b_value.flow_style, comment=b_value.comment, anchor=b_value.anchor, ), ) # If we're dealing with SequenceNodes, merge by appending one sequence to the other. elif isinstance(b_value, ruamel.yaml.nodes.SequenceNode): replaced_nodes[(b_key, b_value)] = ( b_key, ruamel.yaml.nodes.SequenceNode( tag=b_value.tag, value=a_value.value + b_value.value, start_mark=b_value.start_mark, end_mark=b_value.end_mark, flow_style=b_value.flow_style, comment=b_value.comment, anchor=b_value.anchor, ), ) return [ replaced_nodes.get(node, node) for node in nodes if replaced_nodes.get(node) != DELETED_NODE ] import logging import os import ruamel.yaml logger = logging.getLogger(__name__) class Yaml_with_loader_stream(ruamel.yaml.YAML): ''' A derived class of ruamel.yaml.YAML that simply tacks the loaded stream (file object) onto the loader class so that it's available anywhere that's passed a loader (in this case, include_configuration() below). ''' def get_constructor_parser(self, stream): constructor, parser = super(Yaml_with_loader_stream, self).get_constructor_parser(stream) constructor.loader.stream = stream return constructor, parser def load_configuration(filename): ''' Load the given configuration file and return its contents as a data structure of nested dicts and lists. Raise ruamel.yaml.error.YAMLError if something goes wrong parsing the YAML, or RecursionError if there are too many recursive includes. ''' yaml = Yaml_with_loader_stream(typ='safe') yaml.Constructor = Include_constructor return yaml.load(open(filename)) def include_configuration(loader, filename_node): ''' Load the given YAML filename (ignoring the given loader so we can use our own) and return its contents as a data structure of nested dicts and lists. If the filename is relative, probe for it within 1. the current working directory and 2. the directory containing the YAML file doing the including. Raise FileNotFoundError if an included file was not found. ''' include_directories = [os.getcwd(), os.path.abspath(os.path.dirname(loader.stream.name))] include_filename = os.path.expanduser(filename_node.value) if not os.path.isabs(include_filename): candidate_filenames = [ os.path.join(directory, include_filename) for directory in include_directories ] for candidate_filename in candidate_filenames: if os.path.exists(candidate_filename): include_filename = candidate_filename break else: raise FileNotFoundError( f'Could not find include {filename_node.value} at {" or ".join(candidate_filenames)}' ) return load_configuration(include_filename) DELETED_NODE = object() def deep_merge_nodes(nodes): ''' Given a nested borgmatic configuration data structure as a list of tuples in the form of: ( ruamel.yaml.nodes.ScalarNode as a key, ruamel.yaml.nodes.MappingNode or other Node as a value, ), ... deep merge any node values corresponding to duplicate keys and return the result. If there are colliding keys with non-MappingNode values (e.g., integers or strings), the last of the values wins. For instance, given node values of: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='7') ), ]), ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] ... the returned result would be: [ ( ScalarNode(tag='tag:yaml.org,2002:str', value='retention'), MappingNode(tag='tag:yaml.org,2002:map', value=[ ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_hourly'), ScalarNode(tag='tag:yaml.org,2002:int', value='24') ), ( ScalarNode(tag='tag:yaml.org,2002:str', value='keep_daily'), ScalarNode(tag='tag:yaml.org,2002:int', value='5') ), ]), ), ] The purpose of deep merging like this is to support, for instance, merging one borgmatic configuration file into another for reuse, such that a configuration section ("retention", etc.) does not completely replace the corresponding section in a merged file. ''' # Map from original node key/value to the replacement merged node. DELETED_NODE as a replacement # node indications deletion. replaced_nodes = {} # To find nodes that require merging, compare each node with each other node. for a_key, a_value in nodes: for b_key, b_value in nodes: # If we've already considered one of the nodes for merging, skip it. if (a_key, a_value) in replaced_nodes or (b_key, b_value) in replaced_nodes: continue # If the keys match and the values are different, we need to merge these two A and B nodes. if a_key.tag == b_key.tag and a_key.value == b_key.value and a_value != b_value: # Since we're merging into the B node, consider the A node a duplicate and remove it. replaced_nodes[(a_key, a_value)] = DELETED_NODE # If we're dealing with MappingNodes, recurse and merge its values as well. if isinstance(b_value, ruamel.yaml.nodes.MappingNode): replaced_nodes[(b_key, b_value)] = ( b_key, ruamel.yaml.nodes.MappingNode( tag=b_value.tag, value=deep_merge_nodes(a_value.value + b_value.value), start_mark=b_value.start_mark, end_mark=b_value.end_mark, flow_style=b_value.flow_style, comment=b_value.comment, anchor=b_value.anchor, ), ) # If we're dealing with SequenceNodes, merge by appending one sequence to the other. elif isinstance(b_value, ruamel.yaml.nodes.SequenceNode): replaced_nodes[(b_key, b_value)] = ( b_key, ruamel.yaml.nodes.SequenceNode( tag=b_value.tag, value=a_value.value + b_value.value, start_mark=b_value.start_mark, end_mark=b_value.end_mark, flow_style=b_value.flow_style, comment=b_value.comment, anchor=b_value.anchor, ), ) return [ replaced_nodes.get(node, node) for node in nodes if replaced_nodes.get(node) != DELETED_NODE ] class Include_constructor(ruamel.yaml.SafeConstructor): ''' A YAML "constructor" (a ruamel.yaml concept) that supports a custom "!include" tag for including separate YAML configuration files. Example syntax: `retention: !include common.yaml` ''' def __init__(self, preserve_quotes=None, loader=None): super(Include_constructor, self).__init__(preserve_quotes, loader) self.add_constructor('!include', include_configuration) def flatten_mapping(self, node): ''' Support the special case of deep merging included configuration into an existing mapping using the YAML '<<' merge key. Example syntax: ``` retention: keep_daily: 1 <<: !include common.yaml ``` These includes are deep merged into the current configuration file. For instance, in this example, any "retention" options in common.yaml will get merged into the "retention" section in the example configuration file. ''' representer = ruamel.yaml.representer.SafeRepresenter() for index, (key_node, value_node) in enumerate(node.value): if key_node.tag == u'tag:yaml.org,2002:merge' and value_node.tag == '!include': included_value = representer.represent_data(self.construct_object(value_node)) node.value[index] = (key_node, included_value) super(Include_constructor, self).flatten_mapping(node) node.value = deep_merge_nodes(node.value)
borgmatic/config/load.py
codereval_python_data_116
Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. def parse_arguments(*arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. ''' parser = ArgumentParser(description='Generate a sample borgmatic YAML configuration file.') parser.add_argument( '-s', '--source', dest='source_filename', help='Optional YAML configuration file to merge into the generated configuration, useful for upgrading your configuration', ) parser.add_argument( '-d', '--destination', dest='destination_filename', default=DEFAULT_DESTINATION_CONFIG_FILENAME, help='Destination YAML configuration file, default: {}'.format( DEFAULT_DESTINATION_CONFIG_FILENAME ), ) parser.add_argument( '--overwrite', default=False, action='store_true', help='Whether to overwrite any existing destination file, defaults to false', ) return parser.parse_args(arguments) import sys from argparse import ArgumentParser from borgmatic.config import generate, validate DEFAULT_DESTINATION_CONFIG_FILENAME = '/etc/borgmatic/config.yaml' def parse_arguments(*arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. ''' parser = ArgumentParser(description='Generate a sample borgmatic YAML configuration file.') parser.add_argument( '-s', '--source', dest='source_filename', help='Optional YAML configuration file to merge into the generated configuration, useful for upgrading your configuration', ) parser.add_argument( '-d', '--destination', dest='destination_filename', default=DEFAULT_DESTINATION_CONFIG_FILENAME, help='Destination YAML configuration file, default: {}'.format( DEFAULT_DESTINATION_CONFIG_FILENAME ), ) parser.add_argument( '--overwrite', default=False, action='store_true', help='Whether to overwrite any existing destination file, defaults to false', ) return parser.parse_args(arguments) def main(): # pragma: no cover try: args = parse_arguments(*sys.argv[1:]) generate.generate_sample_configuration( args.source_filename, args.destination_filename, validate.schema_filename(), overwrite=args.overwrite, ) print('Generated a sample configuration file at {}.'.format(args.destination_filename)) print() if args.source_filename: print( 'Merged in the contents of configuration file at {}.'.format(args.source_filename) ) print('To review the changes made, run:') print() print( ' diff --unified {} {}'.format(args.source_filename, args.destination_filename) ) print() print('Please edit the file to suit your needs. The values are representative.') print('All fields are optional except where indicated.') print() print('If you ever need help: https://torsion.org/borgmatic/#issues') except (ValueError, OSError) as error: print(error, file=sys.stderr) sys.exit(1)
borgmatic/commands/generate_config.py
codereval_python_data_117
Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in action.option_strings) from borgmatic.commands import arguments UPGRADE_MESSAGE = ''' Your bash completions script is from a different version of borgmatic than is currently installed. Please upgrade your script so your completions match the command-line flags in your installed borgmatic! Try this to upgrade: sudo sh -c "borgmatic --bash-completion > $BASH_SOURCE" source $BASH_SOURCE ''' def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in action.option_strings) def bash_completion(): ''' Return a bash completion script for the borgmatic command. Produce this by introspecting borgmatic's command-line argument parsers. ''' top_level_parser, subparsers = arguments.make_parsers() global_flags = parser_flags(top_level_parser) actions = ' '.join(subparsers.choices.keys()) # Avert your eyes. return '\n'.join( ( 'check_version() {', ' local this_script="$(cat "$BASH_SOURCE" 2> /dev/null)"', ' local installed_script="$(borgmatic --bash-completion 2> /dev/null)"', ' if [ "$this_script" != "$installed_script" ] && [ "$installed_script" != "" ];' ' then cat << EOF\n%s\nEOF' % UPGRADE_MESSAGE, ' fi', '}', 'complete_borgmatic() {', ) + tuple( ''' if [[ " ${COMP_WORDS[*]} " =~ " %s " ]]; then COMPREPLY=($(compgen -W "%s %s %s" -- "${COMP_WORDS[COMP_CWORD]}")) return 0 fi''' % (action, parser_flags(subparser), actions, global_flags) for action, subparser in subparsers.choices.items() ) + ( ' COMPREPLY=($(compgen -W "%s %s" -- "${COMP_WORDS[COMP_CWORD]}"))' % (actions, global_flags), ' (check_version &)', '}', '\ncomplete -o bashdefault -o default -F complete_borgmatic borgmatic', ) )
borgmatic/commands/completion.py
codereval_python_data_118
Return a bash completion script for the borgmatic command. Produce this by introspecting borgmatic's command-line argument parsers. def bash_completion(): ''' Return a bash completion script for the borgmatic command. Produce this by introspecting borgmatic's command-line argument parsers. ''' top_level_parser, subparsers = arguments.make_parsers() global_flags = parser_flags(top_level_parser) actions = ' '.join(subparsers.choices.keys()) # Avert your eyes. return '\n'.join( ( 'check_version() {', ' local this_script="$(cat "$BASH_SOURCE" 2> /dev/null)"', ' local installed_script="$(borgmatic --bash-completion 2> /dev/null)"', ' if [ "$this_script" != "$installed_script" ] && [ "$installed_script" != "" ];' ' then cat << EOF\n%s\nEOF' % UPGRADE_MESSAGE, ' fi', '}', 'complete_borgmatic() {', ) + tuple( ''' if [[ " ${COMP_WORDS[*]} " =~ " %s " ]]; then COMPREPLY=($(compgen -W "%s %s %s" -- "${COMP_WORDS[COMP_CWORD]}")) return 0 fi''' % (action, parser_flags(subparser), actions, global_flags) for action, subparser in subparsers.choices.items() ) + ( ' COMPREPLY=($(compgen -W "%s %s" -- "${COMP_WORDS[COMP_CWORD]}"))' % (actions, global_flags), ' (check_version &)', '}', '\ncomplete -o bashdefault -o default -F complete_borgmatic borgmatic', ) ) from borgmatic.commands import arguments UPGRADE_MESSAGE = ''' Your bash completions script is from a different version of borgmatic than is currently installed. Please upgrade your script so your completions match the command-line flags in your installed borgmatic! Try this to upgrade: sudo sh -c "borgmatic --bash-completion > $BASH_SOURCE" source $BASH_SOURCE ''' def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in action.option_strings) def bash_completion(): ''' Return a bash completion script for the borgmatic command. Produce this by introspecting borgmatic's command-line argument parsers. ''' top_level_parser, subparsers = arguments.make_parsers() global_flags = parser_flags(top_level_parser) actions = ' '.join(subparsers.choices.keys()) # Avert your eyes. return '\n'.join( ( 'check_version() {', ' local this_script="$(cat "$BASH_SOURCE" 2> /dev/null)"', ' local installed_script="$(borgmatic --bash-completion 2> /dev/null)"', ' if [ "$this_script" != "$installed_script" ] && [ "$installed_script" != "" ];' ' then cat << EOF\n%s\nEOF' % UPGRADE_MESSAGE, ' fi', '}', 'complete_borgmatic() {', ) + tuple( ''' if [[ " ${COMP_WORDS[*]} " =~ " %s " ]]; then COMPREPLY=($(compgen -W "%s %s %s" -- "${COMP_WORDS[COMP_CWORD]}")) return 0 fi''' % (action, parser_flags(subparser), actions, global_flags) for action, subparser in subparsers.choices.items() ) + ( ' COMPREPLY=($(compgen -W "%s %s" -- "${COMP_WORDS[COMP_CWORD]}"))' % (actions, global_flags), ' (check_version &)', '}', '\ncomplete -o bashdefault -o default -F complete_borgmatic borgmatic', ) )
borgmatic/commands/completion.py
codereval_python_data_119
Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. ''' top_level_parser, subparsers = make_parsers() arguments, remaining_arguments = parse_subparser_arguments( unparsed_arguments, subparsers.choices ) arguments['global'] = top_level_parser.parse_args(remaining_arguments) if arguments['global'].excludes_filename: raise ValueError( 'The --excludes option has been replaced with exclude_patterns in configuration' ) if 'init' in arguments and arguments['global'].dry_run: raise ValueError('The init action cannot be used with the --dry-run option') if ( 'list' in arguments and 'info' in arguments and arguments['list'].json and arguments['info'].json ): raise ValueError('With the --json option, list and info actions cannot be used together') return arguments import collections from argparse import Action, ArgumentParser from borgmatic.config import collect SUBPARSER_ALIASES = { 'init': ['--init', '-I'], 'prune': ['--prune', '-p'], 'compact': [], 'create': ['--create', '-C'], 'check': ['--check', '-k'], 'extract': ['--extract', '-x'], 'export-tar': ['--export-tar'], 'mount': ['--mount', '-m'], 'umount': ['--umount', '-u'], 'restore': ['--restore', '-r'], 'list': ['--list', '-l'], 'info': ['--info', '-i'], 'borg': [], } def parse_subparser_arguments(unparsed_arguments, subparsers): ''' Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). ''' arguments = collections.OrderedDict() remaining_arguments = list(unparsed_arguments) alias_to_subparser_name = { alias: subparser_name for subparser_name, aliases in SUBPARSER_ALIASES.items() for alias in aliases } # If the "borg" action is used, skip all other subparsers. This avoids confusion like # "borg list" triggering borgmatic's own list action. if 'borg' in unparsed_arguments: subparsers = {'borg': subparsers['borg']} for subparser_name, subparser in subparsers.items(): if subparser_name not in remaining_arguments: continue canonical_name = alias_to_subparser_name.get(subparser_name, subparser_name) # If a parsed value happens to be the same as the name of a subparser, remove it from the # remaining arguments. This prevents, for instance, "check --only extract" from triggering # the "extract" subparser. parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) for value in vars(parsed).values(): if isinstance(value, str): if value in subparsers: remaining_arguments.remove(value) elif isinstance(value, list): for item in value: if item in subparsers: remaining_arguments.remove(item) arguments[canonical_name] = parsed # If no actions are explicitly requested, assume defaults: prune, compact, create, and check. if not arguments and '--help' not in unparsed_arguments and '-h' not in unparsed_arguments: for subparser_name in ('prune', 'compact', 'create', 'check'): subparser = subparsers[subparser_name] parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) arguments[subparser_name] = parsed remaining_arguments = list(unparsed_arguments) # Now ask each subparser, one by one, to greedily consume arguments. for subparser_name, subparser in subparsers.items(): if subparser_name not in arguments.keys(): continue subparser = subparsers[subparser_name] unused_parsed, remaining_arguments = subparser.parse_known_args(remaining_arguments) # Special case: If "borg" is present in the arguments, consume all arguments after (+1) the # "borg" action. if 'borg' in arguments: borg_options_index = remaining_arguments.index('borg') + 1 arguments['borg'].options = remaining_arguments[borg_options_index:] remaining_arguments = remaining_arguments[:borg_options_index] # Remove the subparser names themselves. for subparser_name, subparser in subparsers.items(): if subparser_name in remaining_arguments: remaining_arguments.remove(subparser_name) return (arguments, remaining_arguments) class Extend_action(Action): ''' An argparse action to support Python 3.8's "extend" action in older versions of Python. ''' def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest, None) if items: items.extend(values) else: setattr(namespace, self.dest, list(values)) def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(expand_home=False) global_parser = ArgumentParser(add_help=False) global_parser.register('action', 'extend', Extend_action) global_group = global_parser.add_argument_group('global arguments') global_group.add_argument( '-c', '--config', nargs='*', dest='config_paths', default=config_paths, help='Configuration filenames or directories, defaults to: {}'.format( ' '.join(unexpanded_config_paths) ), ) global_group.add_argument( '--excludes', dest='excludes_filename', help='Deprecated in favor of exclude_patterns within configuration', ) global_group.add_argument( '-n', '--dry-run', dest='dry_run', action='store_true', help='Go through the motions, but do not actually write to any repositories', ) global_group.add_argument( '-nc', '--no-color', dest='no_color', action='store_true', help='Disable colored output' ) global_group.add_argument( '-v', '--verbosity', type=int, choices=range(-1, 3), default=0, help='Display verbose progress to the console (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--syslog-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to syslog (from only errors to very verbose: -1, 0, 1, or 2). Ignored when console is interactive or --log-file is given', ) global_group.add_argument( '--log-file-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to log file (from only errors to very verbose: -1, 0, 1, or 2). Only used when --log-file is given', ) global_group.add_argument( '--monitoring-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to monitoring integrations that support logging (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--log-file', type=str, default=None, help='Write log messages to this file instead of syslog', ) global_group.add_argument( '--override', metavar='SECTION.OPTION=VALUE', nargs='+', dest='overrides', action='extend', help='One or more configuration file options to override with specified values', ) global_group.add_argument( '--no-environment-interpolation', dest='resolve_env', action='store_false', help='Do not resolve environment variables in configuration file', ) global_group.add_argument( '--bash-completion', default=False, action='store_true', help='Show bash completion script and exit', ) global_group.add_argument( '--version', dest='version', default=False, action='store_true', help='Display installed version number of borgmatic and exit', ) top_level_parser = ArgumentParser( description=''' Simple, configuration-driven backup software for servers and workstations. If none of the action options are given, then borgmatic defaults to: prune, compact, create, and check. ''', parents=[global_parser], ) subparsers = top_level_parser.add_subparsers( title='actions', metavar='', help='Specify zero or more actions. Defaults to prune, compact, create, and check. Use --help with action for details:', ) init_parser = subparsers.add_parser( 'init', aliases=SUBPARSER_ALIASES['init'], help='Initialize an empty Borg repository', description='Initialize an empty Borg repository', add_help=False, ) init_group = init_parser.add_argument_group('init arguments') init_group.add_argument( '-e', '--encryption', dest='encryption_mode', help='Borg repository encryption mode', required=True, ) init_group.add_argument( '--append-only', dest='append_only', action='store_true', help='Create an append-only repository', ) init_group.add_argument( '--storage-quota', dest='storage_quota', help='Create a repository with a fixed storage quota', ) init_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') prune_parser = subparsers.add_parser( 'prune', aliases=SUBPARSER_ALIASES['prune'], help='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', description='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', add_help=False, ) prune_group = prune_parser.add_argument_group('prune arguments') prune_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) prune_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) prune_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') compact_parser = subparsers.add_parser( 'compact', aliases=SUBPARSER_ALIASES['compact'], help='Compact segments to free space (Borg 1.2+ only)', description='Compact segments to free space (Borg 1.2+ only)', add_help=False, ) compact_group = compact_parser.add_argument_group('compact arguments') compact_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress as each segment is compacted', ) compact_group.add_argument( '--cleanup-commits', dest='cleanup_commits', default=False, action='store_true', help='Cleanup commit-only 17-byte segment files left behind by Borg 1.1', ) compact_group.add_argument( '--threshold', type=int, dest='threshold', help='Minimum saved space percentage threshold for compacting a segment, defaults to 10', ) compact_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) create_parser = subparsers.add_parser( 'create', aliases=SUBPARSER_ALIASES['create'], help='Create archives (actually perform backups)', description='Create archives (actually perform backups)', add_help=False, ) create_group = create_parser.add_argument_group('create arguments') create_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is backed up', ) create_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) create_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) create_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) create_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') check_parser = subparsers.add_parser( 'check', aliases=SUBPARSER_ALIASES['check'], help='Check archives for consistency', description='Check archives for consistency', add_help=False, ) check_group = check_parser.add_argument_group('check arguments') check_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is checked', ) check_group.add_argument( '--repair', dest='repair', default=False, action='store_true', help='Attempt to repair any inconsistencies found (for interactive use)', ) check_group.add_argument( '--only', metavar='CHECK', choices=('repository', 'archives', 'data', 'extract'), dest='only', action='append', help='Run a particular consistency check (repository, archives, data, or extract) instead of configured checks (subject to configured frequency, can specify flag multiple times)', ) check_group.add_argument( '--force', default=False, action='store_true', help='Ignore configured check frequencies and run checks unconditionally', ) check_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') extract_parser = subparsers.add_parser( 'extract', aliases=SUBPARSER_ALIASES['extract'], help='Extract files from a named archive to the current directory', description='Extract a named archive to the current directory', add_help=False, ) extract_group = extract_parser.add_argument_group('extract arguments') extract_group.add_argument( '--repository', help='Path of repository to extract, defaults to the configured repository if there is only one', ) extract_group.add_argument( '--archive', help='Name of archive to extract (or "latest")', required=True ) extract_group.add_argument( '--path', '--restore-path', metavar='PATH', nargs='+', dest='paths', help='Paths to extract from archive, defaults to the entire archive', ) extract_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Directory to extract files into, defaults to the current directory', ) extract_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each extracted path. Skip paths with fewer elements', ) extract_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is extracted', ) extract_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) export_tar_parser = subparsers.add_parser( 'export-tar', aliases=SUBPARSER_ALIASES['export-tar'], help='Export an archive to a tar-formatted file or stream', description='Export an archive to a tar-formatted file or stream', add_help=False, ) export_tar_group = export_tar_parser.add_argument_group('export-tar arguments') export_tar_group.add_argument( '--repository', help='Path of repository to export from, defaults to the configured repository if there is only one', ) export_tar_group.add_argument( '--archive', help='Name of archive to export (or "latest")', required=True ) export_tar_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to export from archive, defaults to the entire archive', ) export_tar_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Path to destination export tar file, or "-" for stdout (but be careful about dirtying output with --verbosity or --files)', required=True, ) export_tar_group.add_argument( '--tar-filter', help='Name of filter program to pipe data through' ) export_tar_group.add_argument( '--files', default=False, action='store_true', help='Show per-file details' ) export_tar_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each exported path. Skip paths with fewer elements', ) export_tar_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) mount_parser = subparsers.add_parser( 'mount', aliases=SUBPARSER_ALIASES['mount'], help='Mount files from a named archive as a FUSE filesystem', description='Mount a named archive as a FUSE filesystem', add_help=False, ) mount_group = mount_parser.add_argument_group('mount arguments') mount_group.add_argument( '--repository', help='Path of repository to use, defaults to the configured repository if there is only one', ) mount_group.add_argument('--archive', help='Name of archive to mount (or "latest")') mount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path where filesystem is to be mounted', required=True, ) mount_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to mount from archive, defaults to the entire archive', ) mount_group.add_argument( '--foreground', dest='foreground', default=False, action='store_true', help='Stay in foreground until ctrl-C is pressed', ) mount_group.add_argument('--options', dest='options', help='Extra Borg mount options') mount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') umount_parser = subparsers.add_parser( 'umount', aliases=SUBPARSER_ALIASES['umount'], help='Unmount a FUSE filesystem that was mounted with "borgmatic mount"', description='Unmount a mounted FUSE filesystem', add_help=False, ) umount_group = umount_parser.add_argument_group('umount arguments') umount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path of filesystem to unmount', required=True, ) umount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') restore_parser = subparsers.add_parser( 'restore', aliases=SUBPARSER_ALIASES['restore'], help='Restore database dumps from a named archive', description='Restore database dumps from a named archive. (To extract files instead, use "borgmatic extract".)', add_help=False, ) restore_group = restore_parser.add_argument_group('restore arguments') restore_group.add_argument( '--repository', help='Path of repository to restore from, defaults to the configured repository if there is only one', ) restore_group.add_argument( '--archive', help='Name of archive to restore from (or "latest")', required=True ) restore_group.add_argument( '--database', metavar='NAME', nargs='+', dest='databases', help='Names of databases to restore from archive, defaults to all databases. Note that any databases to restore must be defined in borgmatic\'s configuration', ) restore_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) list_parser = subparsers.add_parser( 'list', aliases=SUBPARSER_ALIASES['list'], help='List archives', description='List archives or the contents of an archive', add_help=False, ) list_group = list_parser.add_argument_group('list arguments') list_group.add_argument( '--repository', help='Path of repository to list, defaults to the configured repositories', ) list_group.add_argument('--archive', help='Name of archive to list (or "latest")') list_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths or patterns to list from a single selected archive (via "--archive"), defaults to listing the entire archive', ) list_group.add_argument( '--find', metavar='PATH', nargs='+', dest='find_paths', help='Partial paths or patterns to search for and list across multiple archives', ) list_group.add_argument( '--short', default=False, action='store_true', help='Output only archive or path names' ) list_group.add_argument('--format', help='Format for file listing') list_group.add_argument( '--json', default=False, action='store_true', help='Output results as JSON' ) list_group.add_argument( '-P', '--prefix', help='Only list archive names starting with this prefix' ) list_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only list archive names matching this glob' ) list_group.add_argument( '--successful', default=True, action='store_true', help='Deprecated in favor of listing successful (non-checkpoint) backups by default in newer versions of Borg', ) list_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) list_group.add_argument( '--first', metavar='N', help='List first N archives after other filters are applied' ) list_group.add_argument( '--last', metavar='N', help='List last N archives after other filters are applied' ) list_group.add_argument( '-e', '--exclude', metavar='PATTERN', help='Exclude paths matching the pattern' ) list_group.add_argument( '--exclude-from', metavar='FILENAME', help='Exclude paths from exclude file, one per line' ) list_group.add_argument('--pattern', help='Include or exclude paths matching a pattern') list_group.add_argument( '--patterns-from', metavar='FILENAME', help='Include or exclude paths matching patterns from pattern file, one per line', ) list_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') info_parser = subparsers.add_parser( 'info', aliases=SUBPARSER_ALIASES['info'], help='Display summary information on archives', description='Display summary information on archives', add_help=False, ) info_group = info_parser.add_argument_group('info arguments') info_group.add_argument( '--repository', help='Path of repository to show info for, defaults to the configured repository if there is only one', ) info_group.add_argument('--archive', help='Name of archive to show info for (or "latest")') info_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) info_group.add_argument( '-P', '--prefix', help='Only show info for archive names starting with this prefix' ) info_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only show info for archive names matching this glob', ) info_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) info_group.add_argument( '--first', metavar='N', help='Show info for first N archives after other filters are applied', ) info_group.add_argument( '--last', metavar='N', help='Show info for last N archives after other filters are applied' ) info_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') borg_parser = subparsers.add_parser( 'borg', aliases=SUBPARSER_ALIASES['borg'], help='Run an arbitrary Borg command', description='Run an arbitrary Borg command based on borgmatic\'s configuration', add_help=False, ) borg_group = borg_parser.add_argument_group('borg arguments') borg_group.add_argument( '--repository', help='Path of repository to pass to Borg, defaults to the configured repositories', ) borg_group.add_argument('--archive', help='Name of archive to pass to Borg (or "latest")') borg_group.add_argument( '--', metavar='OPTION', dest='options', nargs='+', help='Options to pass to Borg, command first ("create", "list", etc). "--" is optional. To specify the repository or the archive, you must use --repository or --archive instead of providing them here.', ) borg_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') return top_level_parser, subparsers def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. ''' top_level_parser, subparsers = make_parsers() arguments, remaining_arguments = parse_subparser_arguments( unparsed_arguments, subparsers.choices ) arguments['global'] = top_level_parser.parse_args(remaining_arguments) if arguments['global'].excludes_filename: raise ValueError( 'The --excludes option has been replaced with exclude_patterns in configuration' ) if 'init' in arguments and arguments['global'].dry_run: raise ValueError('The init action cannot be used with the --dry-run option') if ( 'list' in arguments and 'info' in arguments and arguments['list'].json and arguments['info'].json ): raise ValueError('With the --json option, list and info actions cannot be used together') return arguments
borgmatic/commands/arguments.py
codereval_python_data_120
Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). def parse_subparser_arguments(unparsed_arguments, subparsers): ''' Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). ''' arguments = collections.OrderedDict() remaining_arguments = list(unparsed_arguments) alias_to_subparser_name = { alias: subparser_name for subparser_name, aliases in SUBPARSER_ALIASES.items() for alias in aliases } # If the "borg" action is used, skip all other subparsers. This avoids confusion like # "borg list" triggering borgmatic's own list action. if 'borg' in unparsed_arguments: subparsers = {'borg': subparsers['borg']} for subparser_name, subparser in subparsers.items(): if subparser_name not in remaining_arguments: continue canonical_name = alias_to_subparser_name.get(subparser_name, subparser_name) # If a parsed value happens to be the same as the name of a subparser, remove it from the # remaining arguments. This prevents, for instance, "check --only extract" from triggering # the "extract" subparser. parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) for value in vars(parsed).values(): if isinstance(value, str): if value in subparsers: remaining_arguments.remove(value) elif isinstance(value, list): for item in value: if item in subparsers: remaining_arguments.remove(item) arguments[canonical_name] = parsed # If no actions are explicitly requested, assume defaults: prune, compact, create, and check. if not arguments and '--help' not in unparsed_arguments and '-h' not in unparsed_arguments: for subparser_name in ('prune', 'compact', 'create', 'check'): subparser = subparsers[subparser_name] parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) arguments[subparser_name] = parsed remaining_arguments = list(unparsed_arguments) # Now ask each subparser, one by one, to greedily consume arguments. for subparser_name, subparser in subparsers.items(): if subparser_name not in arguments.keys(): continue subparser = subparsers[subparser_name] unused_parsed, remaining_arguments = subparser.parse_known_args(remaining_arguments) # Special case: If "borg" is present in the arguments, consume all arguments after (+1) the # "borg" action. if 'borg' in arguments: borg_options_index = remaining_arguments.index('borg') + 1 arguments['borg'].options = remaining_arguments[borg_options_index:] remaining_arguments = remaining_arguments[:borg_options_index] # Remove the subparser names themselves. for subparser_name, subparser in subparsers.items(): if subparser_name in remaining_arguments: remaining_arguments.remove(subparser_name) return (arguments, remaining_arguments) import collections from argparse import Action, ArgumentParser from borgmatic.config import collect SUBPARSER_ALIASES = { 'init': ['--init', '-I'], 'prune': ['--prune', '-p'], 'compact': [], 'create': ['--create', '-C'], 'check': ['--check', '-k'], 'extract': ['--extract', '-x'], 'export-tar': ['--export-tar'], 'mount': ['--mount', '-m'], 'umount': ['--umount', '-u'], 'restore': ['--restore', '-r'], 'list': ['--list', '-l'], 'info': ['--info', '-i'], 'borg': [], } def parse_subparser_arguments(unparsed_arguments, subparsers): ''' Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). ''' arguments = collections.OrderedDict() remaining_arguments = list(unparsed_arguments) alias_to_subparser_name = { alias: subparser_name for subparser_name, aliases in SUBPARSER_ALIASES.items() for alias in aliases } # If the "borg" action is used, skip all other subparsers. This avoids confusion like # "borg list" triggering borgmatic's own list action. if 'borg' in unparsed_arguments: subparsers = {'borg': subparsers['borg']} for subparser_name, subparser in subparsers.items(): if subparser_name not in remaining_arguments: continue canonical_name = alias_to_subparser_name.get(subparser_name, subparser_name) # If a parsed value happens to be the same as the name of a subparser, remove it from the # remaining arguments. This prevents, for instance, "check --only extract" from triggering # the "extract" subparser. parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) for value in vars(parsed).values(): if isinstance(value, str): if value in subparsers: remaining_arguments.remove(value) elif isinstance(value, list): for item in value: if item in subparsers: remaining_arguments.remove(item) arguments[canonical_name] = parsed # If no actions are explicitly requested, assume defaults: prune, compact, create, and check. if not arguments and '--help' not in unparsed_arguments and '-h' not in unparsed_arguments: for subparser_name in ('prune', 'compact', 'create', 'check'): subparser = subparsers[subparser_name] parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) arguments[subparser_name] = parsed remaining_arguments = list(unparsed_arguments) # Now ask each subparser, one by one, to greedily consume arguments. for subparser_name, subparser in subparsers.items(): if subparser_name not in arguments.keys(): continue subparser = subparsers[subparser_name] unused_parsed, remaining_arguments = subparser.parse_known_args(remaining_arguments) # Special case: If "borg" is present in the arguments, consume all arguments after (+1) the # "borg" action. if 'borg' in arguments: borg_options_index = remaining_arguments.index('borg') + 1 arguments['borg'].options = remaining_arguments[borg_options_index:] remaining_arguments = remaining_arguments[:borg_options_index] # Remove the subparser names themselves. for subparser_name, subparser in subparsers.items(): if subparser_name in remaining_arguments: remaining_arguments.remove(subparser_name) return (arguments, remaining_arguments) class Extend_action(Action): ''' An argparse action to support Python 3.8's "extend" action in older versions of Python. ''' def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest, None) if items: items.extend(values) else: setattr(namespace, self.dest, list(values)) def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(expand_home=False) global_parser = ArgumentParser(add_help=False) global_parser.register('action', 'extend', Extend_action) global_group = global_parser.add_argument_group('global arguments') global_group.add_argument( '-c', '--config', nargs='*', dest='config_paths', default=config_paths, help='Configuration filenames or directories, defaults to: {}'.format( ' '.join(unexpanded_config_paths) ), ) global_group.add_argument( '--excludes', dest='excludes_filename', help='Deprecated in favor of exclude_patterns within configuration', ) global_group.add_argument( '-n', '--dry-run', dest='dry_run', action='store_true', help='Go through the motions, but do not actually write to any repositories', ) global_group.add_argument( '-nc', '--no-color', dest='no_color', action='store_true', help='Disable colored output' ) global_group.add_argument( '-v', '--verbosity', type=int, choices=range(-1, 3), default=0, help='Display verbose progress to the console (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--syslog-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to syslog (from only errors to very verbose: -1, 0, 1, or 2). Ignored when console is interactive or --log-file is given', ) global_group.add_argument( '--log-file-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to log file (from only errors to very verbose: -1, 0, 1, or 2). Only used when --log-file is given', ) global_group.add_argument( '--monitoring-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to monitoring integrations that support logging (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--log-file', type=str, default=None, help='Write log messages to this file instead of syslog', ) global_group.add_argument( '--override', metavar='SECTION.OPTION=VALUE', nargs='+', dest='overrides', action='extend', help='One or more configuration file options to override with specified values', ) global_group.add_argument( '--no-environment-interpolation', dest='resolve_env', action='store_false', help='Do not resolve environment variables in configuration file', ) global_group.add_argument( '--bash-completion', default=False, action='store_true', help='Show bash completion script and exit', ) global_group.add_argument( '--version', dest='version', default=False, action='store_true', help='Display installed version number of borgmatic and exit', ) top_level_parser = ArgumentParser( description=''' Simple, configuration-driven backup software for servers and workstations. If none of the action options are given, then borgmatic defaults to: prune, compact, create, and check. ''', parents=[global_parser], ) subparsers = top_level_parser.add_subparsers( title='actions', metavar='', help='Specify zero or more actions. Defaults to prune, compact, create, and check. Use --help with action for details:', ) init_parser = subparsers.add_parser( 'init', aliases=SUBPARSER_ALIASES['init'], help='Initialize an empty Borg repository', description='Initialize an empty Borg repository', add_help=False, ) init_group = init_parser.add_argument_group('init arguments') init_group.add_argument( '-e', '--encryption', dest='encryption_mode', help='Borg repository encryption mode', required=True, ) init_group.add_argument( '--append-only', dest='append_only', action='store_true', help='Create an append-only repository', ) init_group.add_argument( '--storage-quota', dest='storage_quota', help='Create a repository with a fixed storage quota', ) init_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') prune_parser = subparsers.add_parser( 'prune', aliases=SUBPARSER_ALIASES['prune'], help='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', description='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', add_help=False, ) prune_group = prune_parser.add_argument_group('prune arguments') prune_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) prune_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) prune_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') compact_parser = subparsers.add_parser( 'compact', aliases=SUBPARSER_ALIASES['compact'], help='Compact segments to free space (Borg 1.2+ only)', description='Compact segments to free space (Borg 1.2+ only)', add_help=False, ) compact_group = compact_parser.add_argument_group('compact arguments') compact_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress as each segment is compacted', ) compact_group.add_argument( '--cleanup-commits', dest='cleanup_commits', default=False, action='store_true', help='Cleanup commit-only 17-byte segment files left behind by Borg 1.1', ) compact_group.add_argument( '--threshold', type=int, dest='threshold', help='Minimum saved space percentage threshold for compacting a segment, defaults to 10', ) compact_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) create_parser = subparsers.add_parser( 'create', aliases=SUBPARSER_ALIASES['create'], help='Create archives (actually perform backups)', description='Create archives (actually perform backups)', add_help=False, ) create_group = create_parser.add_argument_group('create arguments') create_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is backed up', ) create_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) create_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) create_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) create_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') check_parser = subparsers.add_parser( 'check', aliases=SUBPARSER_ALIASES['check'], help='Check archives for consistency', description='Check archives for consistency', add_help=False, ) check_group = check_parser.add_argument_group('check arguments') check_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is checked', ) check_group.add_argument( '--repair', dest='repair', default=False, action='store_true', help='Attempt to repair any inconsistencies found (for interactive use)', ) check_group.add_argument( '--only', metavar='CHECK', choices=('repository', 'archives', 'data', 'extract'), dest='only', action='append', help='Run a particular consistency check (repository, archives, data, or extract) instead of configured checks (subject to configured frequency, can specify flag multiple times)', ) check_group.add_argument( '--force', default=False, action='store_true', help='Ignore configured check frequencies and run checks unconditionally', ) check_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') extract_parser = subparsers.add_parser( 'extract', aliases=SUBPARSER_ALIASES['extract'], help='Extract files from a named archive to the current directory', description='Extract a named archive to the current directory', add_help=False, ) extract_group = extract_parser.add_argument_group('extract arguments') extract_group.add_argument( '--repository', help='Path of repository to extract, defaults to the configured repository if there is only one', ) extract_group.add_argument( '--archive', help='Name of archive to extract (or "latest")', required=True ) extract_group.add_argument( '--path', '--restore-path', metavar='PATH', nargs='+', dest='paths', help='Paths to extract from archive, defaults to the entire archive', ) extract_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Directory to extract files into, defaults to the current directory', ) extract_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each extracted path. Skip paths with fewer elements', ) extract_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is extracted', ) extract_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) export_tar_parser = subparsers.add_parser( 'export-tar', aliases=SUBPARSER_ALIASES['export-tar'], help='Export an archive to a tar-formatted file or stream', description='Export an archive to a tar-formatted file or stream', add_help=False, ) export_tar_group = export_tar_parser.add_argument_group('export-tar arguments') export_tar_group.add_argument( '--repository', help='Path of repository to export from, defaults to the configured repository if there is only one', ) export_tar_group.add_argument( '--archive', help='Name of archive to export (or "latest")', required=True ) export_tar_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to export from archive, defaults to the entire archive', ) export_tar_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Path to destination export tar file, or "-" for stdout (but be careful about dirtying output with --verbosity or --files)', required=True, ) export_tar_group.add_argument( '--tar-filter', help='Name of filter program to pipe data through' ) export_tar_group.add_argument( '--files', default=False, action='store_true', help='Show per-file details' ) export_tar_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each exported path. Skip paths with fewer elements', ) export_tar_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) mount_parser = subparsers.add_parser( 'mount', aliases=SUBPARSER_ALIASES['mount'], help='Mount files from a named archive as a FUSE filesystem', description='Mount a named archive as a FUSE filesystem', add_help=False, ) mount_group = mount_parser.add_argument_group('mount arguments') mount_group.add_argument( '--repository', help='Path of repository to use, defaults to the configured repository if there is only one', ) mount_group.add_argument('--archive', help='Name of archive to mount (or "latest")') mount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path where filesystem is to be mounted', required=True, ) mount_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to mount from archive, defaults to the entire archive', ) mount_group.add_argument( '--foreground', dest='foreground', default=False, action='store_true', help='Stay in foreground until ctrl-C is pressed', ) mount_group.add_argument('--options', dest='options', help='Extra Borg mount options') mount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') umount_parser = subparsers.add_parser( 'umount', aliases=SUBPARSER_ALIASES['umount'], help='Unmount a FUSE filesystem that was mounted with "borgmatic mount"', description='Unmount a mounted FUSE filesystem', add_help=False, ) umount_group = umount_parser.add_argument_group('umount arguments') umount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path of filesystem to unmount', required=True, ) umount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') restore_parser = subparsers.add_parser( 'restore', aliases=SUBPARSER_ALIASES['restore'], help='Restore database dumps from a named archive', description='Restore database dumps from a named archive. (To extract files instead, use "borgmatic extract".)', add_help=False, ) restore_group = restore_parser.add_argument_group('restore arguments') restore_group.add_argument( '--repository', help='Path of repository to restore from, defaults to the configured repository if there is only one', ) restore_group.add_argument( '--archive', help='Name of archive to restore from (or "latest")', required=True ) restore_group.add_argument( '--database', metavar='NAME', nargs='+', dest='databases', help='Names of databases to restore from archive, defaults to all databases. Note that any databases to restore must be defined in borgmatic\'s configuration', ) restore_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) list_parser = subparsers.add_parser( 'list', aliases=SUBPARSER_ALIASES['list'], help='List archives', description='List archives or the contents of an archive', add_help=False, ) list_group = list_parser.add_argument_group('list arguments') list_group.add_argument( '--repository', help='Path of repository to list, defaults to the configured repositories', ) list_group.add_argument('--archive', help='Name of archive to list (or "latest")') list_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths or patterns to list from a single selected archive (via "--archive"), defaults to listing the entire archive', ) list_group.add_argument( '--find', metavar='PATH', nargs='+', dest='find_paths', help='Partial paths or patterns to search for and list across multiple archives', ) list_group.add_argument( '--short', default=False, action='store_true', help='Output only archive or path names' ) list_group.add_argument('--format', help='Format for file listing') list_group.add_argument( '--json', default=False, action='store_true', help='Output results as JSON' ) list_group.add_argument( '-P', '--prefix', help='Only list archive names starting with this prefix' ) list_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only list archive names matching this glob' ) list_group.add_argument( '--successful', default=True, action='store_true', help='Deprecated in favor of listing successful (non-checkpoint) backups by default in newer versions of Borg', ) list_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) list_group.add_argument( '--first', metavar='N', help='List first N archives after other filters are applied' ) list_group.add_argument( '--last', metavar='N', help='List last N archives after other filters are applied' ) list_group.add_argument( '-e', '--exclude', metavar='PATTERN', help='Exclude paths matching the pattern' ) list_group.add_argument( '--exclude-from', metavar='FILENAME', help='Exclude paths from exclude file, one per line' ) list_group.add_argument('--pattern', help='Include or exclude paths matching a pattern') list_group.add_argument( '--patterns-from', metavar='FILENAME', help='Include or exclude paths matching patterns from pattern file, one per line', ) list_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') info_parser = subparsers.add_parser( 'info', aliases=SUBPARSER_ALIASES['info'], help='Display summary information on archives', description='Display summary information on archives', add_help=False, ) info_group = info_parser.add_argument_group('info arguments') info_group.add_argument( '--repository', help='Path of repository to show info for, defaults to the configured repository if there is only one', ) info_group.add_argument('--archive', help='Name of archive to show info for (or "latest")') info_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) info_group.add_argument( '-P', '--prefix', help='Only show info for archive names starting with this prefix' ) info_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only show info for archive names matching this glob', ) info_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) info_group.add_argument( '--first', metavar='N', help='Show info for first N archives after other filters are applied', ) info_group.add_argument( '--last', metavar='N', help='Show info for last N archives after other filters are applied' ) info_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') borg_parser = subparsers.add_parser( 'borg', aliases=SUBPARSER_ALIASES['borg'], help='Run an arbitrary Borg command', description='Run an arbitrary Borg command based on borgmatic\'s configuration', add_help=False, ) borg_group = borg_parser.add_argument_group('borg arguments') borg_group.add_argument( '--repository', help='Path of repository to pass to Borg, defaults to the configured repositories', ) borg_group.add_argument('--archive', help='Name of archive to pass to Borg (or "latest")') borg_group.add_argument( '--', metavar='OPTION', dest='options', nargs='+', help='Options to pass to Borg, command first ("create", "list", etc). "--" is optional. To specify the repository or the archive, you must use --repository or --archive instead of providing them here.', ) borg_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') return top_level_parser, subparsers def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. ''' top_level_parser, subparsers = make_parsers() arguments, remaining_arguments = parse_subparser_arguments( unparsed_arguments, subparsers.choices ) arguments['global'] = top_level_parser.parse_args(remaining_arguments) if arguments['global'].excludes_filename: raise ValueError( 'The --excludes option has been replaced with exclude_patterns in configuration' ) if 'init' in arguments and arguments['global'].dry_run: raise ValueError('The init action cannot be used with the --dry-run option') if ( 'list' in arguments and 'info' in arguments and arguments['list'].json and arguments['info'].json ): raise ValueError('With the --json option, list and info actions cannot be used together') return arguments
borgmatic/commands/arguments.py
codereval_python_data_121
Build a top-level parser and its subparsers and return them as a tuple. def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(expand_home=False) global_parser = ArgumentParser(add_help=False) global_parser.register('action', 'extend', Extend_action) global_group = global_parser.add_argument_group('global arguments') global_group.add_argument( '-c', '--config', nargs='*', dest='config_paths', default=config_paths, help='Configuration filenames or directories, defaults to: {}'.format( ' '.join(unexpanded_config_paths) ), ) global_group.add_argument( '--excludes', dest='excludes_filename', help='Deprecated in favor of exclude_patterns within configuration', ) global_group.add_argument( '-n', '--dry-run', dest='dry_run', action='store_true', help='Go through the motions, but do not actually write to any repositories', ) global_group.add_argument( '-nc', '--no-color', dest='no_color', action='store_true', help='Disable colored output' ) global_group.add_argument( '-v', '--verbosity', type=int, choices=range(-1, 3), default=0, help='Display verbose progress to the console (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--syslog-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to syslog (from only errors to very verbose: -1, 0, 1, or 2). Ignored when console is interactive or --log-file is given', ) global_group.add_argument( '--log-file-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to log file (from only errors to very verbose: -1, 0, 1, or 2). Only used when --log-file is given', ) global_group.add_argument( '--monitoring-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to monitoring integrations that support logging (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--log-file', type=str, default=None, help='Write log messages to this file instead of syslog', ) global_group.add_argument( '--override', metavar='SECTION.OPTION=VALUE', nargs='+', dest='overrides', action='extend', help='One or more configuration file options to override with specified values', ) global_group.add_argument( '--no-environment-interpolation', dest='resolve_env', action='store_false', help='Do not resolve environment variables in configuration file', ) global_group.add_argument( '--bash-completion', default=False, action='store_true', help='Show bash completion script and exit', ) global_group.add_argument( '--version', dest='version', default=False, action='store_true', help='Display installed version number of borgmatic and exit', ) top_level_parser = ArgumentParser( description=''' Simple, configuration-driven backup software for servers and workstations. If none of the action options are given, then borgmatic defaults to: prune, compact, create, and check. ''', parents=[global_parser], ) subparsers = top_level_parser.add_subparsers( title='actions', metavar='', help='Specify zero or more actions. Defaults to prune, compact, create, and check. Use --help with action for details:', ) init_parser = subparsers.add_parser( 'init', aliases=SUBPARSER_ALIASES['init'], help='Initialize an empty Borg repository', description='Initialize an empty Borg repository', add_help=False, ) init_group = init_parser.add_argument_group('init arguments') init_group.add_argument( '-e', '--encryption', dest='encryption_mode', help='Borg repository encryption mode', required=True, ) init_group.add_argument( '--append-only', dest='append_only', action='store_true', help='Create an append-only repository', ) init_group.add_argument( '--storage-quota', dest='storage_quota', help='Create a repository with a fixed storage quota', ) init_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') prune_parser = subparsers.add_parser( 'prune', aliases=SUBPARSER_ALIASES['prune'], help='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', description='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', add_help=False, ) prune_group = prune_parser.add_argument_group('prune arguments') prune_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) prune_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) prune_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') compact_parser = subparsers.add_parser( 'compact', aliases=SUBPARSER_ALIASES['compact'], help='Compact segments to free space (Borg 1.2+ only)', description='Compact segments to free space (Borg 1.2+ only)', add_help=False, ) compact_group = compact_parser.add_argument_group('compact arguments') compact_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress as each segment is compacted', ) compact_group.add_argument( '--cleanup-commits', dest='cleanup_commits', default=False, action='store_true', help='Cleanup commit-only 17-byte segment files left behind by Borg 1.1', ) compact_group.add_argument( '--threshold', type=int, dest='threshold', help='Minimum saved space percentage threshold for compacting a segment, defaults to 10', ) compact_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) create_parser = subparsers.add_parser( 'create', aliases=SUBPARSER_ALIASES['create'], help='Create archives (actually perform backups)', description='Create archives (actually perform backups)', add_help=False, ) create_group = create_parser.add_argument_group('create arguments') create_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is backed up', ) create_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) create_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) create_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) create_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') check_parser = subparsers.add_parser( 'check', aliases=SUBPARSER_ALIASES['check'], help='Check archives for consistency', description='Check archives for consistency', add_help=False, ) check_group = check_parser.add_argument_group('check arguments') check_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is checked', ) check_group.add_argument( '--repair', dest='repair', default=False, action='store_true', help='Attempt to repair any inconsistencies found (for interactive use)', ) check_group.add_argument( '--only', metavar='CHECK', choices=('repository', 'archives', 'data', 'extract'), dest='only', action='append', help='Run a particular consistency check (repository, archives, data, or extract) instead of configured checks (subject to configured frequency, can specify flag multiple times)', ) check_group.add_argument( '--force', default=False, action='store_true', help='Ignore configured check frequencies and run checks unconditionally', ) check_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') extract_parser = subparsers.add_parser( 'extract', aliases=SUBPARSER_ALIASES['extract'], help='Extract files from a named archive to the current directory', description='Extract a named archive to the current directory', add_help=False, ) extract_group = extract_parser.add_argument_group('extract arguments') extract_group.add_argument( '--repository', help='Path of repository to extract, defaults to the configured repository if there is only one', ) extract_group.add_argument( '--archive', help='Name of archive to extract (or "latest")', required=True ) extract_group.add_argument( '--path', '--restore-path', metavar='PATH', nargs='+', dest='paths', help='Paths to extract from archive, defaults to the entire archive', ) extract_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Directory to extract files into, defaults to the current directory', ) extract_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each extracted path. Skip paths with fewer elements', ) extract_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is extracted', ) extract_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) export_tar_parser = subparsers.add_parser( 'export-tar', aliases=SUBPARSER_ALIASES['export-tar'], help='Export an archive to a tar-formatted file or stream', description='Export an archive to a tar-formatted file or stream', add_help=False, ) export_tar_group = export_tar_parser.add_argument_group('export-tar arguments') export_tar_group.add_argument( '--repository', help='Path of repository to export from, defaults to the configured repository if there is only one', ) export_tar_group.add_argument( '--archive', help='Name of archive to export (or "latest")', required=True ) export_tar_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to export from archive, defaults to the entire archive', ) export_tar_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Path to destination export tar file, or "-" for stdout (but be careful about dirtying output with --verbosity or --files)', required=True, ) export_tar_group.add_argument( '--tar-filter', help='Name of filter program to pipe data through' ) export_tar_group.add_argument( '--files', default=False, action='store_true', help='Show per-file details' ) export_tar_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each exported path. Skip paths with fewer elements', ) export_tar_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) mount_parser = subparsers.add_parser( 'mount', aliases=SUBPARSER_ALIASES['mount'], help='Mount files from a named archive as a FUSE filesystem', description='Mount a named archive as a FUSE filesystem', add_help=False, ) mount_group = mount_parser.add_argument_group('mount arguments') mount_group.add_argument( '--repository', help='Path of repository to use, defaults to the configured repository if there is only one', ) mount_group.add_argument('--archive', help='Name of archive to mount (or "latest")') mount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path where filesystem is to be mounted', required=True, ) mount_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to mount from archive, defaults to the entire archive', ) mount_group.add_argument( '--foreground', dest='foreground', default=False, action='store_true', help='Stay in foreground until ctrl-C is pressed', ) mount_group.add_argument('--options', dest='options', help='Extra Borg mount options') mount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') umount_parser = subparsers.add_parser( 'umount', aliases=SUBPARSER_ALIASES['umount'], help='Unmount a FUSE filesystem that was mounted with "borgmatic mount"', description='Unmount a mounted FUSE filesystem', add_help=False, ) umount_group = umount_parser.add_argument_group('umount arguments') umount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path of filesystem to unmount', required=True, ) umount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') restore_parser = subparsers.add_parser( 'restore', aliases=SUBPARSER_ALIASES['restore'], help='Restore database dumps from a named archive', description='Restore database dumps from a named archive. (To extract files instead, use "borgmatic extract".)', add_help=False, ) restore_group = restore_parser.add_argument_group('restore arguments') restore_group.add_argument( '--repository', help='Path of repository to restore from, defaults to the configured repository if there is only one', ) restore_group.add_argument( '--archive', help='Name of archive to restore from (or "latest")', required=True ) restore_group.add_argument( '--database', metavar='NAME', nargs='+', dest='databases', help='Names of databases to restore from archive, defaults to all databases. Note that any databases to restore must be defined in borgmatic\'s configuration', ) restore_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) list_parser = subparsers.add_parser( 'list', aliases=SUBPARSER_ALIASES['list'], help='List archives', description='List archives or the contents of an archive', add_help=False, ) list_group = list_parser.add_argument_group('list arguments') list_group.add_argument( '--repository', help='Path of repository to list, defaults to the configured repositories', ) list_group.add_argument('--archive', help='Name of archive to list (or "latest")') list_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths or patterns to list from a single selected archive (via "--archive"), defaults to listing the entire archive', ) list_group.add_argument( '--find', metavar='PATH', nargs='+', dest='find_paths', help='Partial paths or patterns to search for and list across multiple archives', ) list_group.add_argument( '--short', default=False, action='store_true', help='Output only archive or path names' ) list_group.add_argument('--format', help='Format for file listing') list_group.add_argument( '--json', default=False, action='store_true', help='Output results as JSON' ) list_group.add_argument( '-P', '--prefix', help='Only list archive names starting with this prefix' ) list_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only list archive names matching this glob' ) list_group.add_argument( '--successful', default=True, action='store_true', help='Deprecated in favor of listing successful (non-checkpoint) backups by default in newer versions of Borg', ) list_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) list_group.add_argument( '--first', metavar='N', help='List first N archives after other filters are applied' ) list_group.add_argument( '--last', metavar='N', help='List last N archives after other filters are applied' ) list_group.add_argument( '-e', '--exclude', metavar='PATTERN', help='Exclude paths matching the pattern' ) list_group.add_argument( '--exclude-from', metavar='FILENAME', help='Exclude paths from exclude file, one per line' ) list_group.add_argument('--pattern', help='Include or exclude paths matching a pattern') list_group.add_argument( '--patterns-from', metavar='FILENAME', help='Include or exclude paths matching patterns from pattern file, one per line', ) list_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') info_parser = subparsers.add_parser( 'info', aliases=SUBPARSER_ALIASES['info'], help='Display summary information on archives', description='Display summary information on archives', add_help=False, ) info_group = info_parser.add_argument_group('info arguments') info_group.add_argument( '--repository', help='Path of repository to show info for, defaults to the configured repository if there is only one', ) info_group.add_argument('--archive', help='Name of archive to show info for (or "latest")') info_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) info_group.add_argument( '-P', '--prefix', help='Only show info for archive names starting with this prefix' ) info_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only show info for archive names matching this glob', ) info_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) info_group.add_argument( '--first', metavar='N', help='Show info for first N archives after other filters are applied', ) info_group.add_argument( '--last', metavar='N', help='Show info for last N archives after other filters are applied' ) info_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') borg_parser = subparsers.add_parser( 'borg', aliases=SUBPARSER_ALIASES['borg'], help='Run an arbitrary Borg command', description='Run an arbitrary Borg command based on borgmatic\'s configuration', add_help=False, ) borg_group = borg_parser.add_argument_group('borg arguments') borg_group.add_argument( '--repository', help='Path of repository to pass to Borg, defaults to the configured repositories', ) borg_group.add_argument('--archive', help='Name of archive to pass to Borg (or "latest")') borg_group.add_argument( '--', metavar='OPTION', dest='options', nargs='+', help='Options to pass to Borg, command first ("create", "list", etc). "--" is optional. To specify the repository or the archive, you must use --repository or --archive instead of providing them here.', ) borg_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') return top_level_parser, subparsers import collections from argparse import Action, ArgumentParser from borgmatic.config import collect SUBPARSER_ALIASES = { 'init': ['--init', '-I'], 'prune': ['--prune', '-p'], 'compact': [], 'create': ['--create', '-C'], 'check': ['--check', '-k'], 'extract': ['--extract', '-x'], 'export-tar': ['--export-tar'], 'mount': ['--mount', '-m'], 'umount': ['--umount', '-u'], 'restore': ['--restore', '-r'], 'list': ['--list', '-l'], 'info': ['--info', '-i'], 'borg': [], } def parse_subparser_arguments(unparsed_arguments, subparsers): ''' Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subparser name to a parsed namespace of arguments, a list of remaining arguments not claimed by any subparser). ''' arguments = collections.OrderedDict() remaining_arguments = list(unparsed_arguments) alias_to_subparser_name = { alias: subparser_name for subparser_name, aliases in SUBPARSER_ALIASES.items() for alias in aliases } # If the "borg" action is used, skip all other subparsers. This avoids confusion like # "borg list" triggering borgmatic's own list action. if 'borg' in unparsed_arguments: subparsers = {'borg': subparsers['borg']} for subparser_name, subparser in subparsers.items(): if subparser_name not in remaining_arguments: continue canonical_name = alias_to_subparser_name.get(subparser_name, subparser_name) # If a parsed value happens to be the same as the name of a subparser, remove it from the # remaining arguments. This prevents, for instance, "check --only extract" from triggering # the "extract" subparser. parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) for value in vars(parsed).values(): if isinstance(value, str): if value in subparsers: remaining_arguments.remove(value) elif isinstance(value, list): for item in value: if item in subparsers: remaining_arguments.remove(item) arguments[canonical_name] = parsed # If no actions are explicitly requested, assume defaults: prune, compact, create, and check. if not arguments and '--help' not in unparsed_arguments and '-h' not in unparsed_arguments: for subparser_name in ('prune', 'compact', 'create', 'check'): subparser = subparsers[subparser_name] parsed, unused_remaining = subparser.parse_known_args(unparsed_arguments) arguments[subparser_name] = parsed remaining_arguments = list(unparsed_arguments) # Now ask each subparser, one by one, to greedily consume arguments. for subparser_name, subparser in subparsers.items(): if subparser_name not in arguments.keys(): continue subparser = subparsers[subparser_name] unused_parsed, remaining_arguments = subparser.parse_known_args(remaining_arguments) # Special case: If "borg" is present in the arguments, consume all arguments after (+1) the # "borg" action. if 'borg' in arguments: borg_options_index = remaining_arguments.index('borg') + 1 arguments['borg'].options = remaining_arguments[borg_options_index:] remaining_arguments = remaining_arguments[:borg_options_index] # Remove the subparser names themselves. for subparser_name, subparser in subparsers.items(): if subparser_name in remaining_arguments: remaining_arguments.remove(subparser_name) return (arguments, remaining_arguments) class Extend_action(Action): ''' An argparse action to support Python 3.8's "extend" action in older versions of Python. ''' def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest, None) if items: items.extend(values) else: setattr(namespace, self.dest, list(values)) def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(expand_home=False) global_parser = ArgumentParser(add_help=False) global_parser.register('action', 'extend', Extend_action) global_group = global_parser.add_argument_group('global arguments') global_group.add_argument( '-c', '--config', nargs='*', dest='config_paths', default=config_paths, help='Configuration filenames or directories, defaults to: {}'.format( ' '.join(unexpanded_config_paths) ), ) global_group.add_argument( '--excludes', dest='excludes_filename', help='Deprecated in favor of exclude_patterns within configuration', ) global_group.add_argument( '-n', '--dry-run', dest='dry_run', action='store_true', help='Go through the motions, but do not actually write to any repositories', ) global_group.add_argument( '-nc', '--no-color', dest='no_color', action='store_true', help='Disable colored output' ) global_group.add_argument( '-v', '--verbosity', type=int, choices=range(-1, 3), default=0, help='Display verbose progress to the console (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--syslog-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to syslog (from only errors to very verbose: -1, 0, 1, or 2). Ignored when console is interactive or --log-file is given', ) global_group.add_argument( '--log-file-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to log file (from only errors to very verbose: -1, 0, 1, or 2). Only used when --log-file is given', ) global_group.add_argument( '--monitoring-verbosity', type=int, choices=range(-1, 3), default=0, help='Log verbose progress to monitoring integrations that support logging (from only errors to very verbose: -1, 0, 1, or 2)', ) global_group.add_argument( '--log-file', type=str, default=None, help='Write log messages to this file instead of syslog', ) global_group.add_argument( '--override', metavar='SECTION.OPTION=VALUE', nargs='+', dest='overrides', action='extend', help='One or more configuration file options to override with specified values', ) global_group.add_argument( '--no-environment-interpolation', dest='resolve_env', action='store_false', help='Do not resolve environment variables in configuration file', ) global_group.add_argument( '--bash-completion', default=False, action='store_true', help='Show bash completion script and exit', ) global_group.add_argument( '--version', dest='version', default=False, action='store_true', help='Display installed version number of borgmatic and exit', ) top_level_parser = ArgumentParser( description=''' Simple, configuration-driven backup software for servers and workstations. If none of the action options are given, then borgmatic defaults to: prune, compact, create, and check. ''', parents=[global_parser], ) subparsers = top_level_parser.add_subparsers( title='actions', metavar='', help='Specify zero or more actions. Defaults to prune, compact, create, and check. Use --help with action for details:', ) init_parser = subparsers.add_parser( 'init', aliases=SUBPARSER_ALIASES['init'], help='Initialize an empty Borg repository', description='Initialize an empty Borg repository', add_help=False, ) init_group = init_parser.add_argument_group('init arguments') init_group.add_argument( '-e', '--encryption', dest='encryption_mode', help='Borg repository encryption mode', required=True, ) init_group.add_argument( '--append-only', dest='append_only', action='store_true', help='Create an append-only repository', ) init_group.add_argument( '--storage-quota', dest='storage_quota', help='Create a repository with a fixed storage quota', ) init_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') prune_parser = subparsers.add_parser( 'prune', aliases=SUBPARSER_ALIASES['prune'], help='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', description='Prune archives according to the retention policy (with Borg 1.2+, run compact afterwards to actually free space)', add_help=False, ) prune_group = prune_parser.add_argument_group('prune arguments') prune_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) prune_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) prune_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') compact_parser = subparsers.add_parser( 'compact', aliases=SUBPARSER_ALIASES['compact'], help='Compact segments to free space (Borg 1.2+ only)', description='Compact segments to free space (Borg 1.2+ only)', add_help=False, ) compact_group = compact_parser.add_argument_group('compact arguments') compact_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress as each segment is compacted', ) compact_group.add_argument( '--cleanup-commits', dest='cleanup_commits', default=False, action='store_true', help='Cleanup commit-only 17-byte segment files left behind by Borg 1.1', ) compact_group.add_argument( '--threshold', type=int, dest='threshold', help='Minimum saved space percentage threshold for compacting a segment, defaults to 10', ) compact_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) create_parser = subparsers.add_parser( 'create', aliases=SUBPARSER_ALIASES['create'], help='Create archives (actually perform backups)', description='Create archives (actually perform backups)', add_help=False, ) create_group = create_parser.add_argument_group('create arguments') create_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is backed up', ) create_group.add_argument( '--stats', dest='stats', default=False, action='store_true', help='Display statistics of archive', ) create_group.add_argument( '--files', dest='files', default=False, action='store_true', help='Show per-file details' ) create_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) create_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') check_parser = subparsers.add_parser( 'check', aliases=SUBPARSER_ALIASES['check'], help='Check archives for consistency', description='Check archives for consistency', add_help=False, ) check_group = check_parser.add_argument_group('check arguments') check_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is checked', ) check_group.add_argument( '--repair', dest='repair', default=False, action='store_true', help='Attempt to repair any inconsistencies found (for interactive use)', ) check_group.add_argument( '--only', metavar='CHECK', choices=('repository', 'archives', 'data', 'extract'), dest='only', action='append', help='Run a particular consistency check (repository, archives, data, or extract) instead of configured checks (subject to configured frequency, can specify flag multiple times)', ) check_group.add_argument( '--force', default=False, action='store_true', help='Ignore configured check frequencies and run checks unconditionally', ) check_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') extract_parser = subparsers.add_parser( 'extract', aliases=SUBPARSER_ALIASES['extract'], help='Extract files from a named archive to the current directory', description='Extract a named archive to the current directory', add_help=False, ) extract_group = extract_parser.add_argument_group('extract arguments') extract_group.add_argument( '--repository', help='Path of repository to extract, defaults to the configured repository if there is only one', ) extract_group.add_argument( '--archive', help='Name of archive to extract (or "latest")', required=True ) extract_group.add_argument( '--path', '--restore-path', metavar='PATH', nargs='+', dest='paths', help='Paths to extract from archive, defaults to the entire archive', ) extract_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Directory to extract files into, defaults to the current directory', ) extract_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each extracted path. Skip paths with fewer elements', ) extract_group.add_argument( '--progress', dest='progress', default=False, action='store_true', help='Display progress for each file as it is extracted', ) extract_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) export_tar_parser = subparsers.add_parser( 'export-tar', aliases=SUBPARSER_ALIASES['export-tar'], help='Export an archive to a tar-formatted file or stream', description='Export an archive to a tar-formatted file or stream', add_help=False, ) export_tar_group = export_tar_parser.add_argument_group('export-tar arguments') export_tar_group.add_argument( '--repository', help='Path of repository to export from, defaults to the configured repository if there is only one', ) export_tar_group.add_argument( '--archive', help='Name of archive to export (or "latest")', required=True ) export_tar_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to export from archive, defaults to the entire archive', ) export_tar_group.add_argument( '--destination', metavar='PATH', dest='destination', help='Path to destination export tar file, or "-" for stdout (but be careful about dirtying output with --verbosity or --files)', required=True, ) export_tar_group.add_argument( '--tar-filter', help='Name of filter program to pipe data through' ) export_tar_group.add_argument( '--files', default=False, action='store_true', help='Show per-file details' ) export_tar_group.add_argument( '--strip-components', type=int, metavar='NUMBER', dest='strip_components', help='Number of leading path components to remove from each exported path. Skip paths with fewer elements', ) export_tar_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) mount_parser = subparsers.add_parser( 'mount', aliases=SUBPARSER_ALIASES['mount'], help='Mount files from a named archive as a FUSE filesystem', description='Mount a named archive as a FUSE filesystem', add_help=False, ) mount_group = mount_parser.add_argument_group('mount arguments') mount_group.add_argument( '--repository', help='Path of repository to use, defaults to the configured repository if there is only one', ) mount_group.add_argument('--archive', help='Name of archive to mount (or "latest")') mount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path where filesystem is to be mounted', required=True, ) mount_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths to mount from archive, defaults to the entire archive', ) mount_group.add_argument( '--foreground', dest='foreground', default=False, action='store_true', help='Stay in foreground until ctrl-C is pressed', ) mount_group.add_argument('--options', dest='options', help='Extra Borg mount options') mount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') umount_parser = subparsers.add_parser( 'umount', aliases=SUBPARSER_ALIASES['umount'], help='Unmount a FUSE filesystem that was mounted with "borgmatic mount"', description='Unmount a mounted FUSE filesystem', add_help=False, ) umount_group = umount_parser.add_argument_group('umount arguments') umount_group.add_argument( '--mount-point', metavar='PATH', dest='mount_point', help='Path of filesystem to unmount', required=True, ) umount_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') restore_parser = subparsers.add_parser( 'restore', aliases=SUBPARSER_ALIASES['restore'], help='Restore database dumps from a named archive', description='Restore database dumps from a named archive. (To extract files instead, use "borgmatic extract".)', add_help=False, ) restore_group = restore_parser.add_argument_group('restore arguments') restore_group.add_argument( '--repository', help='Path of repository to restore from, defaults to the configured repository if there is only one', ) restore_group.add_argument( '--archive', help='Name of archive to restore from (or "latest")', required=True ) restore_group.add_argument( '--database', metavar='NAME', nargs='+', dest='databases', help='Names of databases to restore from archive, defaults to all databases. Note that any databases to restore must be defined in borgmatic\'s configuration', ) restore_group.add_argument( '-h', '--help', action='help', help='Show this help message and exit' ) list_parser = subparsers.add_parser( 'list', aliases=SUBPARSER_ALIASES['list'], help='List archives', description='List archives or the contents of an archive', add_help=False, ) list_group = list_parser.add_argument_group('list arguments') list_group.add_argument( '--repository', help='Path of repository to list, defaults to the configured repositories', ) list_group.add_argument('--archive', help='Name of archive to list (or "latest")') list_group.add_argument( '--path', metavar='PATH', nargs='+', dest='paths', help='Paths or patterns to list from a single selected archive (via "--archive"), defaults to listing the entire archive', ) list_group.add_argument( '--find', metavar='PATH', nargs='+', dest='find_paths', help='Partial paths or patterns to search for and list across multiple archives', ) list_group.add_argument( '--short', default=False, action='store_true', help='Output only archive or path names' ) list_group.add_argument('--format', help='Format for file listing') list_group.add_argument( '--json', default=False, action='store_true', help='Output results as JSON' ) list_group.add_argument( '-P', '--prefix', help='Only list archive names starting with this prefix' ) list_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only list archive names matching this glob' ) list_group.add_argument( '--successful', default=True, action='store_true', help='Deprecated in favor of listing successful (non-checkpoint) backups by default in newer versions of Borg', ) list_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) list_group.add_argument( '--first', metavar='N', help='List first N archives after other filters are applied' ) list_group.add_argument( '--last', metavar='N', help='List last N archives after other filters are applied' ) list_group.add_argument( '-e', '--exclude', metavar='PATTERN', help='Exclude paths matching the pattern' ) list_group.add_argument( '--exclude-from', metavar='FILENAME', help='Exclude paths from exclude file, one per line' ) list_group.add_argument('--pattern', help='Include or exclude paths matching a pattern') list_group.add_argument( '--patterns-from', metavar='FILENAME', help='Include or exclude paths matching patterns from pattern file, one per line', ) list_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') info_parser = subparsers.add_parser( 'info', aliases=SUBPARSER_ALIASES['info'], help='Display summary information on archives', description='Display summary information on archives', add_help=False, ) info_group = info_parser.add_argument_group('info arguments') info_group.add_argument( '--repository', help='Path of repository to show info for, defaults to the configured repository if there is only one', ) info_group.add_argument('--archive', help='Name of archive to show info for (or "latest")') info_group.add_argument( '--json', dest='json', default=False, action='store_true', help='Output results as JSON' ) info_group.add_argument( '-P', '--prefix', help='Only show info for archive names starting with this prefix' ) info_group.add_argument( '-a', '--glob-archives', metavar='GLOB', help='Only show info for archive names matching this glob', ) info_group.add_argument( '--sort-by', metavar='KEYS', help='Comma-separated list of sorting keys' ) info_group.add_argument( '--first', metavar='N', help='Show info for first N archives after other filters are applied', ) info_group.add_argument( '--last', metavar='N', help='Show info for last N archives after other filters are applied' ) info_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') borg_parser = subparsers.add_parser( 'borg', aliases=SUBPARSER_ALIASES['borg'], help='Run an arbitrary Borg command', description='Run an arbitrary Borg command based on borgmatic\'s configuration', add_help=False, ) borg_group = borg_parser.add_argument_group('borg arguments') borg_group.add_argument( '--repository', help='Path of repository to pass to Borg, defaults to the configured repositories', ) borg_group.add_argument('--archive', help='Name of archive to pass to Borg (or "latest")') borg_group.add_argument( '--', metavar='OPTION', dest='options', nargs='+', help='Options to pass to Borg, command first ("create", "list", etc). "--" is optional. To specify the repository or the archive, you must use --repository or --archive instead of providing them here.', ) borg_group.add_argument('-h', '--help', action='help', help='Show this help message and exit') return top_level_parser, subparsers def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. ''' top_level_parser, subparsers = make_parsers() arguments, remaining_arguments = parse_subparser_arguments( unparsed_arguments, subparsers.choices ) arguments['global'] = top_level_parser.parse_args(remaining_arguments) if arguments['global'].excludes_filename: raise ValueError( 'The --excludes option has been replaced with exclude_patterns in configuration' ) if 'init' in arguments and arguments['global'].dry_run: raise ValueError('The init action cannot be used with the --dry-run option') if ( 'list' in arguments and 'info' in arguments and arguments['list'].json and arguments['info'].json ): raise ValueError('With the --json option, list and info actions cannot be used together') return arguments
borgmatic/commands/arguments.py
codereval_python_data_122
Returns WAPI response page by page Args: response (list): WAPI response. max_results (int): Maximum number of objects to be returned in one page. Returns: Generator object with WAPI response split page by page. def paging(response, max_results): """Returns WAPI response page by page Args: response (list): WAPI response. max_results (int): Maximum number of objects to be returned in one page. Returns: Generator object with WAPI response split page by page. """ i = 0 while i < len(response): yield response[i:i + max_results] i = i + max_results # Copyright 2015 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import netaddr import six try: from oslo_log import log as logging except ImportError: # pragma: no cover import logging try: from oslo_serialization import jsonutils except ImportError: # pragma: no cover import json as jsonutils LOG = logging.getLogger(__name__) def is_valid_ip(ip): try: netaddr.IPAddress(ip) except netaddr.core.AddrFormatError: return False return True def generate_duid(mac): """DUID is consisted of 10 hex numbers. 0x00 + mac with last 3 hex + mac with 6 hex """ valid = mac and isinstance(mac, six.string_types) if not valid: raise ValueError("Invalid argument was passed") return "00:" + mac[9:] + ":" + mac def determine_ip_version(ip_in): ip_ver = 4 if isinstance(ip_in, (list, tuple)): ip_in = ip_in[0] if ip_in: if isinstance(ip_in, int): if ip_in == 6: ip_ver = 6 else: ip_ver = 4 elif hasattr(ip_in, 'ip_version'): return ip_in.ip_version else: if type(ip_in) is dict: addr = ip_in['ip_address'] else: addr = ip_in try: ip = netaddr.IPAddress(addr) except ValueError: ip = netaddr.IPNetwork(addr) ip_ver = ip.version return ip_ver def safe_json_load(data): try: return jsonutils.loads(data) except ValueError: LOG.warning("Could not decode reply into json: %s", data) def try_value_to_bool(value, strict_mode=True): """Tries to convert value into boolean. Args: value (str): Value that should be converted into boolean. strict_mode (bool): - If strict_mode is True, Only string representation of str(True) and str(False) are converted into booleans; - If strict_mode is False, anything that looks like True or False is converted into booleans: - Values accepted as True are: 'true', 'on', 'yes' (case independent) - Values accepted as False are: 'false', 'off', 'no' (case independent) Returns: True, False, or original value in case of failed conversion. """ if strict_mode: true_list = ('True',) false_list = ('False',) val = value else: true_list = ('true', 'on', 'yes') false_list = ('false', 'off', 'no') val = str(value).lower() if val in true_list: return True elif val in false_list: return False return value def paging(response, max_results): """Returns WAPI response page by page Args: response (list): WAPI response. max_results (int): Maximum number of objects to be returned in one page. Returns: Generator object with WAPI response split page by page. """ i = 0 while i < len(response): yield response[i:i + max_results] i = i + max_results
infoblox_client/utils.py
codereval_python_data_123
Convert human readable file size to bytes. Resulting value is an approximation as input value is in most case rounded. Args: size: A string representing a human readable file size (eg: '500K') Returns: A decimal representation of file size Examples:: >>> size_to_bytes("500") 500 >>> size_to_bytes("1K") 1000 def size_to_bytes(size: str) -> int: """Convert human readable file size to bytes. Resulting value is an approximation as input value is in most case rounded. Args: size: A string representing a human readable file size (eg: '500K') Returns: A decimal representation of file size Examples:: >>> size_to_bytes("500") 500 >>> size_to_bytes("1K") 1000 """ units = { "K": 1000, "M": 1000**2, "G": 1000**3, "T": 1000**4, "P": 1000**5, "E": 1000**6, "Z": 1000**7, "Y": 1000**8, } if size.endswith(tuple(units)): v, u = (size[:-1], size[-1]) return int(v) * units[u] else: return int(size) # Copyright (C) 2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import datetime import logging from pathlib import Path import re import tarfile from typing import Any, Dict, Iterator, List, Optional from urllib.parse import unquote, urljoin from bs4 import BeautifulSoup import requests from swh.model.hashutil import hash_to_hex from swh.scheduler.interface import SchedulerInterface from swh.scheduler.model import ListedOrigin from ..pattern import CredentialsType, StatelessLister logger = logging.getLogger(__name__) # Aliasing the page results returned by `get_pages` method from the lister. ArchListerPage = List[Dict[str, Any]] def size_to_bytes(size: str) -> int: """Convert human readable file size to bytes. Resulting value is an approximation as input value is in most case rounded. Args: size: A string representing a human readable file size (eg: '500K') Returns: A decimal representation of file size Examples:: >>> size_to_bytes("500") 500 >>> size_to_bytes("1K") 1000 """ units = { "K": 1000, "M": 1000**2, "G": 1000**3, "T": 1000**4, "P": 1000**5, "E": 1000**6, "Z": 1000**7, "Y": 1000**8, } if size.endswith(tuple(units)): v, u = (size[:-1], size[-1]) return int(v) * units[u] else: return int(size) class ArchLister(StatelessLister[ArchListerPage]): """List Arch linux origins from 'core', 'extra', and 'community' repositories For 'official' Arch Linux it downloads core.tar.gz, extra.tar.gz and community.tar.gz from https://archive.archlinux.org/repos/last/ extract to a temp directory and then walks through each 'desc' files. Each 'desc' file describe the latest released version of a package and helps to build an origin url from where scrapping artifacts metadata. For 'arm' Arch Linux it follow the same discovery process parsing 'desc' files. The main difference is that we can't get existing versions of an arm package because https://archlinuxarm.org does not have an 'archive' website or api. """ LISTER_NAME = "arch" VISIT_TYPE = "arch" INSTANCE = "arch" DESTINATION_PATH = Path("/tmp/archlinux_archive") ARCH_PACKAGE_URL_PATTERN = "{base_url}/packages/{repo}/{arch}/{pkgname}" ARCH_PACKAGE_VERSIONS_URL_PATTERN = "{base_url}/packages/{pkgname[0]}/{pkgname}" ARCH_PACKAGE_DOWNLOAD_URL_PATTERN = ( "{base_url}/packages/{pkgname[0]}/{pkgname}/{filename}" ) ARCH_API_URL_PATTERN = "{base_url}/packages/{repo}/{arch}/{pkgname}/json" ARM_PACKAGE_URL_PATTERN = "{base_url}/packages/{arch}/{pkgname}" ARM_PACKAGE_DOWNLOAD_URL_PATTERN = "{base_url}/{arch}/{repo}/{filename}" def __init__( self, scheduler: SchedulerInterface, credentials: Optional[CredentialsType] = None, flavours: Dict[str, Any] = { "official": { "archs": ["x86_64"], "repos": ["core", "extra", "community"], "base_info_url": "https://archlinux.org", "base_archive_url": "https://archive.archlinux.org", "base_mirror_url": "", "base_api_url": "https://archlinux.org", }, "arm": { "archs": ["armv7h", "aarch64"], "repos": ["core", "extra", "community"], "base_info_url": "https://archlinuxarm.org", "base_archive_url": "", "base_mirror_url": "https://uk.mirror.archlinuxarm.org", "base_api_url": "", }, }, ): super().__init__( scheduler=scheduler, credentials=credentials, url=flavours["official"]["base_info_url"], instance=self.INSTANCE, ) self.flavours = flavours def scrap_package_versions( self, name: str, repo: str, base_url: str ) -> List[Dict[str, Any]]: """Given a package 'name' and 'repo', make an http call to origin url and parse its content to get package versions artifacts data. That method is suitable only for 'official' Arch Linux, not 'arm'. Args: name: Package name repo: The repository the package belongs to (one of self.repos) Returns: A list of dict of version Example:: [ {"url": "https://archive.archlinux.org/packages/d/dialog/dialog-1:1.3_20190211-1-x86_64.pkg.tar.xz", # noqa: B950 "arch": "x86_64", "repo": "core", "name": "dialog", "version": "1:1.3_20190211-1", "length": 180000, "filename": "dialog-1:1.3_20190211-1-x86_64.pkg.tar.xz", "last_modified": "2019-02-13T08:36:00"}, ] """ url = self.ARCH_PACKAGE_VERSIONS_URL_PATTERN.format( pkgname=name, base_url=base_url ) soup = BeautifulSoup(requests.get(url).text, "html.parser") links = soup.find_all("a", href=True) # drop the first line (used to go to up directory) if links[0].attrs["href"] == "../": links.pop(0) versions = [] for link in links: # filename displayed can be cropped if name is too long, get it from href instead filename = unquote(link.attrs["href"]) if filename.endswith((".tar.xz", ".tar.zst")): # Extract arch from filename arch_rex = re.compile( rf"^{re.escape(name)}-(?P<version>.*)-(?P<arch>any|i686|x86_64)" rf"(.pkg.tar.(?:zst|xz))$" ) m = arch_rex.match(filename) if m is None: logger.error( "Can not find a match for architecture in %(filename)s" % dict(filename=filename) ) else: arch = m.group("arch") version = m.group("version") # Extract last_modified and an approximate file size raw_text = link.next_sibling raw_text_rex = re.compile( r"^(?P<last_modified>\d+-\w+-\d+ \d\d:\d\d)\s+(?P<size>\w+)$" ) s = raw_text_rex.search(raw_text.strip()) if s is None: logger.error( "Can not find a match for 'last_modified' and/or " "'size' in '%(raw_text)s'" % dict(raw_text=raw_text) ) else: assert s.groups() assert len(s.groups()) == 2 last_modified_str, size = s.groups() # format as expected last_modified = datetime.datetime.strptime( last_modified_str, "%d-%b-%Y %H:%M" ).isoformat() length = size_to_bytes(size) # we want bytes # link url is relative, format a canonical one url = self.ARCH_PACKAGE_DOWNLOAD_URL_PATTERN.format( base_url=base_url, pkgname=name, filename=filename ) versions.append( dict( name=name, version=version, repo=repo, arch=arch, filename=filename, url=url, last_modified=last_modified, length=length, ) ) return versions def get_repo_archive(self, url: str, destination_path: Path) -> Path: """Given an url and a destination path, retrieve and extract .tar.gz archive which contains 'desc' file for each package. Each .tar.gz archive corresponds to an Arch Linux repo ('core', 'extra', 'community'). Args: url: url of the .tar.gz archive to download destination_path: the path on disk where to extract archive Returns: a directory Path where the archive has been extracted to. """ res = requests.get(url) destination_path.parent.mkdir(parents=True, exist_ok=True) destination_path.write_bytes(res.content) extract_to = Path(str(destination_path).split(".tar.gz")[0]) tar = tarfile.open(destination_path) tar.extractall(path=extract_to) tar.close() return extract_to def parse_desc_file( self, path: Path, repo: str, base_url: str, dl_url_fmt: str, ) -> Dict[str, Any]: """Extract package information from a 'desc' file. There are subtle differences between parsing 'official' and 'arm' des files Args: path: A path to a 'desc' file on disk repo: The repo the package belongs to Returns: A dict of metadata Example:: {'api_url': 'https://archlinux.org/packages/core/x86_64/dialog/json', 'arch': 'x86_64', 'base': 'dialog', 'builddate': '1650081535', 'csize': '203028', 'desc': 'A tool to display dialog boxes from shell scripts', 'filename': 'dialog-1:1.3_20220414-1-x86_64.pkg.tar.zst', 'isize': '483988', 'license': 'LGPL2.1', 'md5sum': '06407c0cb11c50d7bf83d600f2e8107c', 'name': 'dialog', 'packager': 'Evangelos Foutras <foutrelis@archlinux.org>', 'pgpsig': 'pgpsig content xxx', 'project_url': 'https://invisible-island.net/dialog/', 'provides': 'libdialog.so=15-64', 'repo': 'core', 'sha256sum': 'ef8c8971f591de7db0f455970ef5d81d5aced1ddf139f963f16f6730b1851fa7', 'url': 'https://archive.archlinux.org/packages/.all/dialog-1:1.3_20220414-1-x86_64.pkg.tar.zst', # noqa: B950 'version': '1:1.3_20220414-1'} """ rex = re.compile(r"^\%(?P<k>\w+)\%\n(?P<v>.*)\n$", re.M) with path.open("rb") as content: parsed = rex.findall(content.read().decode()) data = {entry[0].lower(): entry[1] for entry in parsed} if "url" in data.keys(): data["project_url"] = data["url"] assert data["name"] assert data["filename"] assert data["arch"] data["repo"] = repo data["url"] = urljoin( base_url, dl_url_fmt.format( base_url=base_url, pkgname=data["name"], filename=data["filename"], arch=data["arch"], repo=repo, ), ) assert data["md5sum"] assert data["sha256sum"] data["checksums"] = { "md5sum": hash_to_hex(data["md5sum"]), "sha256sum": hash_to_hex(data["sha256sum"]), } return data def get_pages(self) -> Iterator[ArchListerPage]: """Yield an iterator sorted by name in ascending order of pages. Each page is a list of package belonging to a flavour ('official', 'arm'), and a repo ('core', 'extra', 'community') """ for name, flavour in self.flavours.items(): for arch in flavour["archs"]: for repo in flavour["repos"]: page = [] if name == "official": prefix = urljoin(flavour["base_archive_url"], "/repos/last/") filename = f"{repo}.files.tar.gz" archive_url = urljoin(prefix, f"{repo}/os/{arch}/{filename}") destination_path = Path(self.DESTINATION_PATH, arch, filename) base_url = flavour["base_archive_url"] dl_url_fmt = self.ARCH_PACKAGE_DOWNLOAD_URL_PATTERN base_info_url = flavour["base_info_url"] info_url_fmt = self.ARCH_PACKAGE_URL_PATTERN elif name == "arm": filename = f"{repo}.files.tar.gz" archive_url = urljoin( flavour["base_mirror_url"], f"{arch}/{repo}/{filename}" ) destination_path = Path(self.DESTINATION_PATH, arch, filename) base_url = flavour["base_mirror_url"] dl_url_fmt = self.ARM_PACKAGE_DOWNLOAD_URL_PATTERN base_info_url = flavour["base_info_url"] info_url_fmt = self.ARM_PACKAGE_URL_PATTERN archive = self.get_repo_archive( url=archive_url, destination_path=destination_path ) assert archive packages_desc = list(archive.glob("**/desc")) logger.debug( "Processing %(instance)s source packages info from " "%(flavour)s %(arch)s %(repo)s repository, " "(%(qty)s packages)." % dict( instance=self.instance, flavour=name, arch=arch, repo=repo, qty=len(packages_desc), ) ) for package_desc in packages_desc: data = self.parse_desc_file( path=package_desc, repo=repo, base_url=base_url, dl_url_fmt=dl_url_fmt, ) assert data["builddate"] last_modified = datetime.datetime.fromtimestamp( float(data["builddate"]), tz=datetime.timezone.utc ) assert data["name"] assert data["filename"] assert data["arch"] url = info_url_fmt.format( base_url=base_info_url, pkgname=data["name"], filename=data["filename"], repo=repo, arch=data["arch"], ) assert data["version"] if name == "official": # find all versions of a package scrapping archive versions = self.scrap_package_versions( name=data["name"], repo=repo, base_url=base_url, ) elif name == "arm": # There is no way to get related versions of a package, # but 'data' represents the latest released version, # use it in this case assert data["builddate"] assert data["csize"] assert data["url"] versions = [ dict( name=data["name"], version=data["version"], repo=repo, arch=data["arch"], filename=data["filename"], url=data["url"], last_modified=last_modified.replace( tzinfo=None ).isoformat(timespec="seconds"), length=int(data["csize"]), ) ] package = { "name": data["name"], "version": data["version"], "last_modified": last_modified, "url": url, "versions": versions, "data": data, } page.append(package) yield page def get_origins_from_page(self, page: ArchListerPage) -> Iterator[ListedOrigin]: """Iterate on all arch pages and yield ListedOrigin instances.""" assert self.lister_obj.id is not None for origin in page: yield ListedOrigin( lister_id=self.lister_obj.id, visit_type=self.VISIT_TYPE, url=origin["url"], last_update=origin["last_modified"], extra_loader_arguments={ "artifacts": origin["versions"], }, )
swh/lister/arch/lister.py
codereval_python_data_124
Combine values of the dictionaries supplied by iterable dicts. >>> _dictsum([{'a': 1, 'b': 2}, {'a': 5, 'b': 0}]) {'a': 6, 'b': 2} def _dictsum(dicts): """ Combine values of the dictionaries supplied by iterable dicts. >>> _dictsum([{'a': 1, 'b': 2}, {'a': 5, 'b': 0}]) {'a': 6, 'b': 2} """ it = iter(dicts) first = next(it).copy() for d in it: for k, v in d.items(): first[k] += v return first #!/usr/bin/env python3 import logging import os import re import signal import sys import threading import traceback import warnings from argparse import ArgumentParser from collections import OrderedDict from configparser import RawConfigParser, SectionProxy from datetime import datetime, timezone from hashlib import md5 from tempfile import NamedTemporaryFile from time import time from unittest import TestCase try: from swiftclient import Connection except ImportError: warnings.warn('No swiftclient? You probably need to {!r}'.format( 'apt-get install python3-swiftclient --no-install-recommends')) else: from swiftclient.exceptions import ClientException # TODO: when stopping mid-add, we get lots of "ValueError: early abort" # backtraces polluting the log; should do without error SAMPLE_INIFILE = r"""\ [acme_swift_v1_config] ; Use rclonse(1) to see the containers: `rclone lsd acme_swift_v1_config:` type = swift user = NAMESPACE:USER key = KEY auth = https://AUTHSERVER/auth/v1.0 ; You can use one or more 'planb_translate' or use 'planb_translate_<N>' ; to define filename translation rules. They may be needed to circumvent ; local filesystem limits (like not allowing trailing / in a filename). ; GUID-style (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) to "ID/GU/FULLGUID". planb_translate_0 = document= ^([0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{8}([0-9a-f]{2})([0-9a-f]{2}))$= \4/\3/\1 ; BEWARE ^^ remove excess linefeeds and indentation from this example ^^ ; Translate in the 'wsdl' container all paths that start with "YYYYMMDD" ; to "YYYY/MM/DD/" planb_translate_1 = wsdl=^(\d{4})(\d{2})(\d{2})/=\1/\2/\3/ ; Translate in all containers all paths (files) that end with a slash to %2F. ; (This will conflict with files actually having a %2F there, but that ; is not likely to happen.) planb_translate_2 = *=/$=%2F [acme_swift_v3_config] type = swift domain = USER_DOMAIN user = USER key = KEY auth = https://AUTHSERVER/v3/ tenant = PROJECT tenant_domain = PROJECT_DOMAIN auth_version = 3 ; Set this to always to skip autodetection of DLO segment support: not all DLO ; segments are stored in a separate <container>_segments container. ; (You may need to clear the planb-swiftsync.new cache after setting this.) planb_container_has_segments = always """ logging.basicConfig( level=logging.INFO, format=( '%(asctime)s [planb-swiftsync:%(threadName)-10.10s] ' '[%(levelname)-3.3s] %(message)s'), handlers=[logging.StreamHandler()]) log = logging.getLogger() def _signal_handler(signo, _stack_frame): global _MT_ABORT, _MT_HAS_THREADS _MT_ABORT = signo log.info('Got signal %d', signo) if not _MT_HAS_THREADS: # If we have no threads, we can abort immediately. log.info('Killing self because of signal %d', signo) sys.exit(128 + signo) # raises SystemExit() _MT_ABORT = 0 # noqa -- aborting? _MT_HAS_THREADS = False # do we have threads at all? signal.signal(signal.SIGHUP, _signal_handler) signal.signal(signal.SIGINT, _signal_handler) signal.signal(signal.SIGTERM, _signal_handler) signal.signal(signal.SIGQUIT, _signal_handler) class PathTranslator: """ Translates path from remote_path to local_path. When single_container=True, the container name is not added into the local_path. Test using: planb_storage_destination=$(pwd)/data \ ./planb-swiftsync -c planb-swiftsync.conf SECTION \ --test-path-translate CONTAINERNAME (provide remote paths on stdin) """ def __init__(self, data_path, container, translations, single_container): assert '/' not in container, container assert isinstance(single_container, bool) self.data_path = data_path self.container = container self.single_container = single_container self.replacements = [] for translation in translations: container_match, needle, replacement = translation.split('=') if container == container_match or container_match == '*': self.replacements.append(( re.compile(needle), replacement)) def __call__(self, remote_path): for needle, replacement in self.replacements: local_path = needle.sub(replacement, remote_path) if local_path != remote_path: break else: local_path = remote_path # Single container: LOCAL_BASE + TRANSLATED_REMOTE_PATH if self.single_container: return os.path.join(self.data_path, local_path) # Multiple containers: LOCAL_BASE + CONTAINER + TRANSLATED_REMOTE_PATH return os.path.join(self.data_path, self.container, local_path) class ConfigParserMultiValues(OrderedDict): """ Accept duplicate keys in the RawConfigParser. """ def __setitem__(self, key, value): # The RawConfigParser does a second pass. First lists are passed. # Secondly concatenated strings are passed. assert isinstance(value, ( ConfigParserMultiValues, SectionProxy, list, str)), ( key, value, type(value)) # For the second pass, we could do an optional split by LF. But that # makes it harder to notice when this breaks. Instead, just skip the # str-setting. if isinstance(value, str): # and '\n' in value: # super().__setitem__(key, value.split('\n')) return if key in self and isinstance(value, list): self[key].extend(value) else: super().__setitem__(key, value) class SwiftSyncConfig: def __init__(self, inifile, section): self.read_inifile(inifile, section) self.read_environment() def read_inifile(self, inifile, section): configparser = RawConfigParser( strict=False, empty_lines_in_values=False, dict_type=ConfigParserMultiValues) configparser.read([inifile]) try: config = configparser[section] except KeyError: raise ValueError( 'no section {!r} found in {!r}'.format(section, inifile)) type_ = config.get('type', None) assert type_ == ['swift'], type_ self.swift_authver = config.get('auth_version', ['1'])[-1] self.swift_auth = config['auth'][-1] # authurl self.swift_user = config['user'][-1] self.swift_key = config['key'][-1] # auth_version v3: self.swift_project = config.get('tenant', [None])[-1] # project self.swift_pdomain = ( config.get('tenant_domain', [None])[-1]) # project-domain self.swift_udomain = ( config.get('domain', [None])[-1]) # user-domain self.swift_containers = [] # Accept multiple planb_translate keys. But also accept # planb_translate_<id> keys. If you use the rclone config tool, # rewriting the file would destroy duplicate keys, so using a # suffix is preferred. self.planb_translations = [] for key in sorted(config.keys()): if key == 'planb_translate' or key.startswith('planb_translate_'): self.planb_translations.extend(config[key]) # Sometimes segment autodetection can fail, resulting in: # > Filesize mismatch for '...': 0 != 9515 # This is probably because the object has X-Object-Manifest and is a # Dynamic Large Object (DLO). self.all_containers_have_segments = ( config.get('planb_container_has_segments', [''])[-1] == 'always') def read_environment(self): # /tank/customer-friendly_name/data storage = os.environ['planb_storage_destination'] # friendly_name = os.environ['planb_fileset_friendly_name'] # fileset_id = os.environ['planb_fileset_id'] if not storage.endswith('/data'): raise ValueError( 'expected storage path to end in /data, got {!r}'.format( storage)) if not os.path.exists(storage): raise ValueError( 'data_path does not exist: {!r}'.format(storage)) self.data_path = storage self.metadata_path = storage.rsplit('/', 1)[0] assert self.metadata_path.startswith('/'), self.metadata_path def get_swift(self): if self.swift_authver == '3': os_options = { 'project_name': self.swift_project, 'project_domain_name': self.swift_pdomain, 'user_domain_name': self.swift_udomain, } connection = Connection( auth_version='3', authurl=self.swift_auth, user=self.swift_user, key=self.swift_key, os_options=os_options) elif self.swift_authver == '1': connection = Connection( auth_version='1', authurl=self.swift_auth, user=self.swift_user, key=self.swift_key, tenant_name='UNUSED') else: raise NotImplementedError( 'auth_version? {!r}'.format(self.swift_authver)) return connection def get_translator(self, container, single_container): return PathTranslator( self.data_path, container, self.planb_translations, single_container) class SwiftSyncConfigPathTranslators(dict): def __init__(self, config, single_container): assert isinstance(single_container, bool) super().__init__() self._config = config self._single_container = single_container def get(self, *args, **kwargs): raise NotImplementedError() def __getitem__(self, container): try: translator = super().__getitem__(container) except KeyError: translator = self._config.get_translator( container, single_container=self._single_container) super().__setitem__(container, translator) return translator class SwiftContainer(str): # The OpenStack Swift canonical method for handling large objects, # is using Dynamic Large Objects (DLO) or Static Large Objects # (SLO). # # In both (DLO and SLO) cases, the CONTAINER file segments are # uploaded to a separate container called CONTAINER_segments. # When doing a listing over CONTAINER, the segmented files are # reported as having 0 size. When that happens, we have to do a HEAD # on those files to retreive the actual concatenated file size. # # This boolean allows us to skip those expensive lookups for all # containers X that do not have an X_segments helper container. has_segments = False class SwiftLine: def __init__(self, obj): # {'bytes': 107713, # 'last_modified': '2018-05-25T15:11:14.501890', # 'hash': '89602749f508fc9820ef575a52cbfaba', # 'name': '20170101/mr/administrative', # 'content_type': 'text/xml'}] self.obj = obj self.size = obj['bytes'] assert len(obj['last_modified']) == 26, obj assert obj['last_modified'][10] == 'T', obj self.modified = obj['last_modified'] self.path = obj['name'] assert not self.path.startswith(('\\', '/', './', '../')), self.path assert '/../' not in self.path, self.path # disallow harmful path assert '/./' not in self.path, self.path # disallow awkward path class ListLine: # >>> escaped_re.findall('containerx|file||name|0|1234\n') # ['containerx', '|', 'file||name', '|', '0', '|', '1234\n'] escaped_re = re.compile(r'(?P<part>(?:[^|]|(?:[|][|]))+|[|])') @classmethod def from_swift_head(cls, container, path, head_dict): """ {'server': 'nginx', 'date': 'Fri, 02 Jul 2021 13:04:35 GMT', 'content-type': 'image/jpg', 'content-length': '241190', 'etag': '7bc4ca634783b4c83cf506188cd7176b', 'x-object-meta-mtime': '1581604242', 'last-modified': 'Tue, 08 Jun 2021 07:03:34 GMT', 'x-timestamp': '1623135813.04310', 'accept-ranges': 'bytes', 'x-trans-id': 'txcxxx-xxx', 'x-openstack-request-id': 'txcxxx-xxx'} """ size = head_dict.get('content-length') assert size.isdigit(), head_dict assert all(i in '0123456789.' for i in head_dict['x-timestamp']), ( head_dict) tm = datetime.utcfromtimestamp(float(head_dict['x-timestamp'])) tms = tm.strftime('%Y-%m-%dT%H:%M:%S.%f') if container: assert '|' not in container, ( 'unescaping can only cope with pipe in path: {!r} + {!r}' .format(container, path)) return cls('{}|{}|{}|{}\n'.format( container, path.replace('|', '||'), tms, size)) return cls('{}|{}|{}\n'.format(path.replace('|', '||'), tms, size)) def __init__(self, line): # Line looks like: [container|]path|modified|size<LF> # But path may contain double pipes. if '||' not in line: # Simple matching. self.path, self._modified, self._size = line.rsplit('|', 2) if '|' in self.path: self.container, self.path = self.path.split('|', 1) else: self.container = None assert '|' not in self.path, 'bad line: {!r}'.format(line) else: # Complicated regex matching. Path may include double pipes. matches = self.escaped_re.findall(line) assert ''.join(matches) == line, (line, matches) if len(matches) == 7: path = ''.join(matches[0:3]) # move pipes to path self.container, path = path.split('|', 1) self._modified = matches[4] self._size = matches[6] elif len(matches) == 5: path = matches[0] self.container = None self._modified = matches[2] self._size = matches[4] else: assert False, 'bad line: {!r}'.format(line) self.path = path.replace('||', '|') assert self.container is None or self.container, ( 'bad container in line: {!r}'.format(line)) self.line = line self.container_path = (self.container, self.path) @property def size(self): # NOTE: _size has a trailing LF, but int() silently eats it for us. return int(self._size) @property def modified(self): # The time is zone agnostic, so let's assume UTC. if not hasattr(self, '_modified_cache'): dates, us = self._modified.split('.', 1) dates = int( datetime.strptime(dates, '%Y-%m-%dT%H:%M:%S') .replace(tzinfo=timezone.utc).timestamp()) assert len(us) == 6 self._modified_cache = 1000000000 * dates + 1000 * int(us) return self._modified_cache def __eq__(self, other): return (self.size == other.size and self.container == other.container and self.container_path == other.container_path and self.path == other.path) class SwiftSync: def __init__(self, config, container=None): self.config = config self.container = container # Init translators. They're done lazily, so we don't need to know which # containers exist yet. self._translators = SwiftSyncConfigPathTranslators( self.config, single_container=bool(container)) # Get data path. Chdir into it so no unmounting can take place. data_path = config.data_path os.chdir(data_path) # Get metadata path where we store listings. metadata_path = config.metadata_path self._filelock = os.path.join(metadata_path, 'planb-swiftsync.lock') self._path_cur = os.path.join(metadata_path, 'planb-swiftsync.cur') # ^-- this contains the local truth self._path_new = os.path.join(metadata_path, 'planb-swiftsync.new') # ^-- the unreached goal self._path_del = os.path.join(metadata_path, 'planb-swiftsync.del') self._path_add = os.path.join(metadata_path, 'planb-swiftsync.add') self._path_utime = os.path.join(metadata_path, 'planb-swiftsync.utime') # ^-- the work we have to do to reach the goal # NOTE: For changed files, we get an entry in both del and add. # Sometimes however, only the mtime is changed. For that case we # use the utime list, where we check the hash before # downloading/overwriting. def get_containers(self): if not hasattr(self, '_get_containers'): resp_headers, containers = ( self.config.get_swift().get_account()) # containers == [ # {'count': 350182, 'bytes': 78285833087, # 'name': 'containerA'}] container_names = set(i['name'] for i in containers) force_segments = self.config.all_containers_have_segments # Translate container set into containers with and without # segments. For example: # - containerA (has_segments=False) # - containerB (has_segments=True) # - containerB_segments (skipped, belongs with containerB) # - containerC_segments (has_segments=False) selected_containers = [] for name in sorted(container_names): # We're looking for a specific container. Only check whether a # X_segments exists. (Because of DLO/SLO we must do the # get_accounts() lookup even though we already know # which container to process.) if self.container: if self.container == name: new = SwiftContainer(name) if force_segments or ( '{}_segments'.format(name) in container_names): new.has_segments = True selected_containers.append(new) break # We're getting all containers. Check if X_segments exists for # it. And only add X_segments containers if there is no X # container. else: if (name.endswith('_segments') and name.rsplit('_', 1)[0] in container_names): # Don't add X_segments, because X exists. pass else: new = SwiftContainer(name) if force_segments or ( '{}_segments'.format(name) in container_names): new.has_segments = True selected_containers.append(new) # It's already sorted because we sort the container_names # before inserting. self._get_containers = selected_containers return self._get_containers def get_translators(self): return self._translators def sync(self): lock_fd = None try: # Get lock. lock_fd = os.open( self._filelock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) except FileExistsError: # Failed to get lock. log.error('Failed to get %r lock', self._filelock) sys.exit(1) else: # Do work. self.make_lists() failures = 0 failures += self.delete_from_list() failures += self.add_from_list() failures += self.update_from_list() # If we bailed out with failures, but without an exception, we'll # still clear out the list. Perhaps the list was bad and we simply # need to fetch a clean new one (on the next run, that is). self.clean_lists() if failures: raise SystemExit(1) finally: if lock_fd is not None: os.close(lock_fd) os.unlink(self._filelock) def make_lists(self): """ Build planb-swiftsync.add, planb-swiftsync.del, planb-swiftsync.utime. """ log.info('Building lists') # Only create new list if it didn't exist yet (because we completed # successfully the last time) or if it's rather old. try: last_modified = os.path.getmtime(self._path_new) except FileNotFoundError: last_modified = 0 if not last_modified or (time() - last_modified) > (18 * 3600.0): self._make_new_list() # Make the add/del/utime lists based off cur/new. # # * The add/del lists are obvious. Changed files get an entry in # both del and add. # # * The utime list is for cases when only the mtime has changed: # To avoid rewriting (duplicating) the file on COW storage (ZFS), # we'll want to check the file hash to avoid rewriting it if it's # the same. (Useful when the source files have been moved/copied # and the X-Timestamps have thus been renewed.) # self._make_diff_lists() def delete_from_list(self): """ Delete from planb-swiftsync.del. """ if os.path.getsize(self._path_del): log.info('Removing old files (SwiftSyncDeleter)') deleter = SwiftSyncDeleter(self, self._path_del) deleter.work() # NOTE: We don't expect any failures here, ever. This concerns # only local file deletions. If they fail, then something is # really wrong (bad filesystem, or datalist out of sync). return 0 # no (recoverable) failures def add_from_list(self): """ Add from planb-swiftsync.add. """ if os.path.getsize(self._path_add): log.info('Adding new files (SwiftSyncAdder)') adder = SwiftSyncAdder(self, self._path_add) adder.work() return adder.failures # (possibly recoverable) failure count return 0 # no (recoverable) failures def update_from_list(self): """ Check/update from planb-swiftsync.utime. """ if os.path.getsize(self._path_utime): log.info('Updating timestamp for updated files (SwiftSyncUpdater)') updater = SwiftSyncUpdater(self, self._path_utime) updater.work() return updater.failures # (possibly recoverable) failure count return 0 # no (recoverable) failures def clean_lists(self): """ Remove planb-swiftsync.new so we'll fetch a fresh one on the next run. """ os.unlink(self._path_new) # Also remove add/del/utime files; we don't need them anymore, and they # take up space. os.unlink(self._path_add) os.unlink(self._path_del) os.unlink(self._path_utime) log.info('Sync done') def _make_new_list(self): """ Create planb-swiftsync.new with the files we want to have. This can be slow as we may need to fetch many lines from swift. """ path_tmp = '{}.tmp'.format(self._path_new) swiftconn = self.config.get_swift() with open(path_tmp, 'w') as dest: os.chmod(path_tmp, 0o600) for container in self.get_containers(): assert '|' not in container, container assert '{' not in container, container if self.container: # only one container fmt = '{}|{}|{}\n' else: # multiple containers fmt = '{}|{{}}|{{}}|{{}}\n'.format(container) log.info('Fetching new list for %r', container) # full_listing: # if True, return a full listing, else returns a max of # 10000 listings; but that will eat memory, which we don't # want. marker = '' # "start _after_ marker" prev_marker = 'anything_except_the_empty_string' limit = 10000 while True: assert marker != prev_marker, marker # loop trap resp_headers, lines = swiftconn.get_container( container, full_listing=False, limit=limit, marker=marker) for idx, line in enumerate(lines): self._make_new_list_add_line( dest, fmt, swiftconn, container, line) if not lines or (idx + 1 < limit): break marker, prev_marker = line['name'], marker os.rename(path_tmp, self._path_new) def _make_new_list_add_line(self, dest, fmt, swiftconn, container, line): record = SwiftLine(line) if record.size == 0 and container.has_segments: # Do a head to get DLO/SLO stats. This is # only needed if this container has segments, # and if the apparent file size is 0. try: obj_stat = swiftconn.head_object(container, line['name']) # If this is still 0, then it's an empty file # anyway. record.size = int(obj_stat['content-length']) except ClientException as e: # 404? log.warning( 'File %r %r disappeared from under us ' 'when doing a HEAD (%s)', container, line['name'], e) # Skip record. return dest.write(fmt.format( record.path.replace('|', '||'), record.modified, record.size)) def _make_diff_lists(self): """ Create planb-swiftsync.add, planb-swiftsync.del and planb-swiftsync.utime based on planb-swiftsync.new and planb-swiftsync.cur. planb-swiftsync.del: Files that can be removed immediately. planb-swiftsync.add: Files that can be added immediately. planb-swiftsync.utime: Files that have the same name and filesize, but different timestamp. """ try: cur_fp = open(self._path_cur, 'r') except FileNotFoundError: with open(self._path_cur, 'w'): os.chmod(self._path_cur, 0o600) cur_fp = open(self._path_cur, 'r') try: with open(self._path_new, 'r') as new_fp, \ open(self._path_del, 'w') as del_fp, \ open(self._path_add, 'w') as add_fp, \ open(self._path_utime, 'w') as utime_fp: os.chmod(self._path_del, 0o600) os.chmod(self._path_add, 0o600) os.chmod(self._path_utime, 0o600) llc = _ListLineComm(cur_fp, new_fp) llc.act( # We already have it if in both: both=(lambda line: None), # We have it in both, but only the timestamp differs: difftime=(lambda leftline, rightline: ( utime_fp.write(rightline))), # Remove when only in cur_fp: leftonly=(lambda line: del_fp.write(line)), # Add when only in new_fp: rightonly=(lambda line: add_fp.write(line))) finally: cur_fp.close() def update_cur_list_from_added(self, added_fp): """ Update planb-swiftsync.cur by adding all from added_fp. """ path_tmp = '{}.tmp'.format(self._path_cur) with open(self._path_cur, 'r') as cur_fp, \ open(path_tmp, 'w') as tmp_fp: os.chmod(path_tmp, 0o600) llc = _ListLineComm(cur_fp, added_fp) llc.act( # Keep it if we already had it: leftonly=(lambda line: tmp_fp.write(line)), # Keep it if we added it now: rightonly=(lambda line: tmp_fp.write(line)), # This should not happen: both=None, # existed _and_ added? difftime=None) # existed _and_ changed? os.rename(path_tmp, self._path_cur) def update_cur_list_from_deleted(self, deleted_fp): """ Update planb-swiftsync.cur by removing all from deleted_fp. """ path_tmp = '{}.tmp'.format(self._path_cur) with open(self._path_cur, 'r') as cur_fp, \ open(path_tmp, 'w') as tmp_fp: os.chmod(path_tmp, 0o600) llc = _ListLineComm(cur_fp, deleted_fp) llc.act( # Drop it if in both (we deleted it now): both=(lambda line: None), # Keep it if we didn't touch it: leftonly=(lambda line: tmp_fp.write(line)), # This should not happen: difftime=None, # existed _and_ added? rightonly=None) # deleted something which didn't exist? os.rename(path_tmp, self._path_cur) def update_cur_list_from_updated(self, updated_fp): """ Update planb-swiftsync.cur by updating all from updated_fp. """ path_tmp = '{}.tmp'.format(self._path_cur) with open(self._path_cur, 'r') as cur_fp, \ open(path_tmp, 'w') as tmp_fp: os.chmod(path_tmp, 0o600) llc = _ListLineComm(cur_fp, updated_fp) llc.act( # Replace it if we updated it: difftime=(lambda leftline, rightline: ( tmp_fp.write(rightline))), # Keep it if we didn't touch it: leftonly=(lambda line: tmp_fp.write(line)), # This should not happen: both=None, rightonly=None) os.rename(path_tmp, self._path_cur) class SwiftSyncDeleter: def __init__(self, swiftsync, source): self._swiftsync = swiftsync self._source = source def work(self): with NamedTemporaryFile(delete=True, mode='w+') as success_fp: try: self._delete_old(success_fp) finally: success_fp.flush() success_fp.seek(0) self._swiftsync.update_cur_list_from_deleted(success_fp) def _delete_old(self, success_fp): """ Delete old files (from planb-swiftsync.del) and store which files we deleted in the success_fp. """ translators = self._swiftsync.get_translators() only_container = self._swiftsync.container with open(self._source, 'r') as del_fp: for record in _comm_lineiter(del_fp): # record.container is None for single_container syncs. container = record.container or only_container # Locate local path and remove. path = translators[container](record.path) os.unlink(path) # FIXME: should also try to delete unused directories? success_fp.write(record.line) class SwiftSyncMultiWorkerBase(threading.Thread): """ Multithreaded SwiftSyncWorkerBase class. """ class ProcessRecordFailure(Exception): pass def __init__(self, swiftsync, source, offset=0, threads=0): super().__init__() self._swiftsync = swiftsync self._source = source self._offset = offset self._threads = threads self._success_fp = None # If there were one or more failures, store them so they can be used by # the caller. self.failures = 0 def run(self): log.info('%s: Started thread', self.__class__.__name__) self._success_fp = NamedTemporaryFile(delete=True, mode='w+') try: self._process_source_list() finally: self._success_fp.flush() log.info('%s: Stopping thread', self.__class__.__name__) def take_success_file(self): """ You're allowed to take ownership of the file... once. """ ret, self._success_fp = self._success_fp, None return ret def process_record(self, record, container, dst_path): raise NotImplementedError() def process_record_success(self, record): """ Store success in the success list. """ self._success_fp.write(record.line) def _process_source_list(self): """ Process the source list, calling process_record() for each file. """ # Create this swift connection first in this thread on purpose. That # should minimise swiftclient library MT issues. self._swiftconn = self._swiftsync.config.get_swift() ProcessRecordFailure = self.ProcessRecordFailure translators = self._swiftsync.get_translators() only_container = self._swiftsync.container offset = self._offset threads = self._threads # Loop over the planb-swiftsync.add file, but only do our own files. with open(self._source, 'r') as add_fp: for idx, record in enumerate(_comm_lineiter(add_fp)): # When running with multiple threads, we don't use a # queue, but simply divide the files over all threads # fairly. if (idx % threads) != offset: continue # Make multi-thread ready. if _MT_ABORT: raise ValueError('early abort') # record.container is None for single_container syncs. container = record.container or only_container dst_path = translators[container](record.path) if dst_path.endswith('/'): log.warning( ('Skipping record %r (from %r) because of trailing ' 'slash'), dst_path, record.container_path) self.failures += 1 continue # Download the file into the appropriate directory. try: self.process_record(record, container, dst_path) except ProcessRecordFailure: self.failures += 1 else: self.process_record_success(record) if self.failures: log.warning('At list EOF, got %d failures', self.failures) def _add_new_record_dir(self, path): try: os.makedirs(os.path.dirname(path), 0o700) except FileExistsError: pass def _add_new_record_download(self, record, container, path): try: with open(path, 'wb') as out_fp: # resp_chunk_size - if defined, chunk size of data to read. # > If you specify a resp_chunk_size you must fully read # > the object's contents before making another request. resp_headers, obj = self._swiftconn.get_object( container, record.path, resp_chunk_size=(16 * 1024 * 1024)) if record.size == 0 and 'X-Object-Manifest' in resp_headers: raise NotImplementedError( '0-sized files with X-Object-Manifest? ' 'cont={!r}, path={!r}, size={!r}, hdrs={!r}'.format( container, record.path, record.size, resp_headers)) for data in obj: if _MT_ABORT: raise ValueError('early abort during {}'.format( record.container_path)) out_fp.write(data) except Exception as e: log.warning( 'Download failure for %r (from %r): %s', path, record.container_path, e) if isinstance(e, IsADirectoryError): pass else: try: # FIXME: also remove directories we just created? os.unlink(path) except FileNotFoundError: pass raise self.ProcessRecordFailure() def _add_new_record_valid(self, record, path): os.utime(path, ns=(record.modified, record.modified)) local_size = os.stat(path).st_size if local_size != record.size: log.error( 'Filesize mismatch for %r (from %r): %d != %d', path, record.container_path, record.size, local_size) try: # FIXME: also remove directories we just created? os.unlink(path) except FileNotFoundError: pass raise self.ProcessRecordFailure() class SwiftSyncMultiAdder(SwiftSyncMultiWorkerBase): def process_record(self, record, container, dst_path): """ Process a single record: download it. If there was an error, it cleans up after itself and raises a ProcessRecordFailure. """ self._add_new_record_dir(dst_path) self._add_new_record_download(record, container, dst_path) self._add_new_record_valid(record, dst_path) class SwiftSyncMultiUpdater(SwiftSyncMultiWorkerBase): """ Multithreaded SwiftSyncUpdater. """ def process_record(self, record, container, dst_path): """ Process a single record: download it. Raises ProcessRecordFailure on error. """ try: obj_stat = self._swiftconn.head_object(container, record.path) except ClientException as e: log.warning( 'File %r %r disappeared from under us when doing a HEAD (%s)', container, record.path, e) raise self.ProcessRecordFailure() etag = str(obj_stat.get('etag')) if len(etag) != 32 or any(i not in '0123456789abcdef' for i in etag): log.warning( 'File %r %r presented bad etag: %r', container, record.path, obj_stat) raise self.ProcessRecordFailure() # Note that guard against odd races, we must also check the record # against this new head. This also asserts that the file size is still # the same. new_record = ListLine.from_swift_head( record.container, record.path, obj_stat) if new_record.line != record.line: log.warning( 'File was updated in the mean time? %r != %r', record.line, new_record.line) raise self.ProcessRecordFailure() # Nice, we have an etag, and we were lured here with the prospect that # the file was equal to what we already had. md5digest = self._md5sum(dst_path) # should exist and succeed # If the hash is equal, then all is awesome. if md5digest == etag: return # If not, then we need to download a new file and overwrite it. # XXX: if this fails, we have invalid state! the file could be # removed while our lists will not have it. This needs fixing. self._add_new_record_download(record, container, dst_path) self._add_new_record_valid(record, dst_path) def _md5sum(self, path): m = md5() with open(path, 'rb') as fp: while True: buf = fp.read(128 * 1024) # larger is generally better if not buf: break m.update(buf) hexdigest = m.hexdigest() assert ( len(hexdigest) == 32 and all(i in '0123456789abcdef' for i in hexdigest)), hexdigest return hexdigest class SwiftSyncBase: worker_class = NotImplemented def __init__(self, swiftsync, source): self._swiftsync = swiftsync self._source = source self._thread_count = 7 def work(self): global _MT_ABORT, _MT_HAS_THREADS log.info( '%s: Starting %d %s downloader threads', self.__class__.__name__, self._thread_count, self.worker_class.__name__) threads = [ self.worker_class( swiftsync=self._swiftsync, source=self._source, offset=idx, threads=self._thread_count) for idx in range(self._thread_count)] if self._thread_count == 1: try: threads[0].run() finally: self.merge_success(threads[0].take_success_file()) else: _MT_HAS_THREADS = True for thread in threads: thread.start() for thread in threads: thread.join() _MT_HAS_THREADS = False success_fps = [th.take_success_file() for th in threads] success_fps = [fp for fp in success_fps if fp is not None] self._merge_multi_success(success_fps) del success_fps if _MT_ABORT: raise SystemExit(_MT_ABORT) # Collect and sum failure count to signify when not everything is fine, # even though we did our best. If we're here, all threads ended # successfully, so they all have a valid failures count. self.failures = sum(th.failures for th in threads) def merge_success(self, success_fp): raise NotImplementedError() def _merge_multi_success(self, success_fps): """ Merge all success_fps into cur. This is useful because we oftentimes download only a handful of files. First merge those, before we merge them into the big .cur list. NOTE: _merge_multi_success will close all success_fps. """ try: success_fp = self._create_combined_success(success_fps) self.merge_success(success_fp) finally: for fp in success_fps: fp.close() def _create_combined_success(self, success_fps): """ Merge all success_fps into a single success_fp. Returns a new success_fp. """ combined_fp = prev_fp = None combined_fp = NamedTemporaryFile(delete=True, mode='w+') try: prev_fp = NamedTemporaryFile(delete=True, mode='w+') # start blank # Add all success_fps into combined_fp. Update prev_fp to # hold combined_fp. for added_fp in success_fps: if added_fp is None: continue added_size = added_fp.tell() added_fp.seek(0) if added_size: prev_size = prev_fp.tell() prev_fp.seek(0) log.info( '%s: Merging success lists (%d into %d)', self.__class__.__name__, added_size, prev_size) llc = _ListLineComm(prev_fp, added_fp) llc.act( # Die if we encounter a file twice: both=None, difftime=None, # Keep it if we already had it: leftonly=(lambda line: combined_fp.write(line)), # Keep it if we added it now: rightonly=(lambda line: combined_fp.write(line))) combined_fp.flush() # We don't need left anymore. Make combined the new left. # Create new combined where we merge the next success_fp. prev_fp.close() prev_fp, combined_fp = combined_fp, None combined_fp = NamedTemporaryFile(delete=True, mode='w+') # We want combined_fp at this point, but it's currently in # prev_fp. Note that the new combined_fp is at EOF (unseeked). combined_fp.close() combined_fp, prev_fp = prev_fp, None except Exception: if prev_fp: prev_fp.close() if combined_fp: combined_fp.close() raise return combined_fp class SwiftSyncAdder(SwiftSyncBase): worker_class = SwiftSyncMultiAdder def merge_success(self, success_fp): """ Merge "add" success_fp into (the big) .cur list. NOTE: merge_success will close success_fp. """ if success_fp is None: return try: size = success_fp.tell() success_fp.seek(0) if size: log.info( '%s: Merging %d bytes of added files into current', self.__class__.__name__, size) success_fp.seek(0) self._swiftsync.update_cur_list_from_added(success_fp) finally: success_fp.close() class SwiftSyncUpdater(SwiftSyncBase): worker_class = SwiftSyncMultiUpdater def merge_success(self, success_fp): """ Merge "update" success_fp into (the big) .cur list. NOTE: merge_success will close success_fp. """ if success_fp is None: return try: size = success_fp.tell() success_fp.seek(0) if size: log.info( '%s: Merging %d bytes of updated files into current', self.__class__.__name__, size) success_fp.seek(0) self._swiftsync.update_cur_list_from_updated(success_fp) finally: success_fp.close() def _dictsum(dicts): """ Combine values of the dictionaries supplied by iterable dicts. >>> _dictsum([{'a': 1, 'b': 2}, {'a': 5, 'b': 0}]) {'a': 6, 'b': 2} """ it = iter(dicts) first = next(it).copy() for d in it: for k, v in d.items(): first[k] += v return first def _comm_lineiter(fp): """ Line iterator for _comm. Yields ListLine instances. """ it = iter(fp) # Do one manually, so we get prev_path. try: line = next(it) except StopIteration: return record = ListLine(line) yield record prev_record = record # Do the rest through normal iteration. for line in it: record = ListLine(line) if prev_record.container_path >= record.container_path: raise ValueError('data (sorting?) error: {!r} vs. {!r}'.format( prev_record.container_path, record.container_path)) yield record prev_record = record class _ListLineComm: """ Like comm(1) - compare two sorted files line by line - using the _comm_lineiter iterator. Usage:: llc = _ListLineComm(cur_fp, new_fp) llc.act( # We already have it if in both: both=(lambda line: None), # Both, but the mtime is different: difftime=(lambda leftline, rightline: utime_fp.write(rightline)), # Remove when only in cur_fp: leftonly=(lambda line: del_fp.write(line)), # Add when only in new_fp: rightonly=(lambda line: add_fp.write(line))) """ def __init__(self, left, right): self._left_src = left self._right_src = right def act(self, both, difftime, leftonly, rightonly): self._act_both = both self._act_difftime = difftime self._act_leftonly = leftonly self._act_rightonly = rightonly self._process_main() self._process_tail() def _setup(self, source): it = _comm_lineiter(source) try: elem = next(it) except StopIteration: elem = it = None return it, elem def _process_main(self): # Make local act_both, act_difftime, act_leftonly, act_rightonly = ( self._act_both, self._act_difftime, self._act_leftonly, self._act_rightonly) left_iter, left = self._setup(self._left_src) right_iter, right = self._setup(self._right_src) while left_iter and right_iter: if left.container_path < right.container_path: # Current is lower, remove and seek current. act_leftonly(left.line) try: left = next(left_iter) except StopIteration: left = left_iter = None elif right.container_path < left.container_path: # New is lower, add and seek right. act_rightonly(right.line) try: right = next(right_iter) except StopIteration: right = right_iter = None else: # filename and container are equal if left.line == right.line: # 100% equal? act_both(right.line) elif left.size == right.size: # Size is equal. Then mtime must be unequal. assert left.modified != right.modified, (left, right) act_difftime(left.line, right.line) else: # Size is different, mtime is irrelevant. act_leftonly(left.line) act_rightonly(right.line) # Seek both to get to the next filename. try: left = next(left_iter) except StopIteration: left = left_iter = None try: right = next(right_iter) except StopIteration: right = right_iter = None # Store self._left_iter, self._left = left_iter, left self._right_iter, self._right = right_iter, right def _process_tail(self): if self._left_iter: act_leftonly = self._act_leftonly act_leftonly(self._left.line) for left in self._left_iter: act_leftonly(left.line) if self._right_iter: act_rightonly = self._act_rightonly act_rightonly(self._right.line) for right in self._right_iter: act_rightonly(right.line) class _ListLineTest(TestCase): def _eq(self, line, cont, path, mod, size): ll = ListLine(line) self.assertEqual(ll.container, cont) self.assertEqual(ll.container_path, (cont, path)) self.assertEqual(ll.path, path) self.assertEqual(ll.modified, mod) self.assertEqual(ll.size, size) def test_pipe_in_path(self): self._eq( 'containerx|path/to||esc|2021-02-03T12:34:56.654321|1234', 'containerx', 'path/to|esc', 1612355696654321000, 1234) self._eq( 'path/to||esc|2021-02-03T12:34:56.654321|1234', None, 'path/to|esc', 1612355696654321000, 1234) self._eq( '||path/with/starting/pipe|2021-02-03T12:34:56.654321|1234', None, '|path/with/starting/pipe', 1612355696654321000, 1234) self._eq( 'path/with/ending/pipe|||2021-02-03T12:34:56.654321|1234', None, 'path/with/ending/pipe|', 1612355696654321000, 1234) self._eq( '||path/with/both|||2021-02-03T12:34:56.654321|1234', None, '|path/with/both|', 1612355696654321000, 1234) self._eq( 'container|||||pipefest|||2021-02-03T12:34:56.654321|1234', 'container', '||pipefest|', 1612355696654321000, 1234) self.assertRaises( Exception, ListLine, 'too|few') self.assertRaises( AssertionError, ListLine, 'lots|of|unescaped|2021-02-03T12:34:56.654321|1234') self.assertRaises( AssertionError, ListLine, 'lots|of|one||escaped|2021-02-03T12:34:56.654321|1234') self.assertRaises( AssertionError, ListLine, '|emptycontainer|2021-02-03T12:34:56.654321|1234') def test_with_container(self): ll = ListLine( 'contx|path/to/somewhere|2021-02-03T12:34:56.654321|1234') self.assertEqual(ll.container, 'contx') self.assertEqual(ll.container_path, ('contx', 'path/to/somewhere')) self.assertEqual(ll.path, 'path/to/somewhere') self.assertEqual(ll.modified, 1612355696654321000) self.assertEqual(ll.size, 1234) def test_no_container(self): ll = ListLine( 'nocontainer/to/somewhere|2021-02-03T12:34:57.654321|12345') self.assertEqual(ll.container, None) self.assertEqual(ll.container_path, (None, 'nocontainer/to/somewhere')) self.assertEqual(ll.path, 'nocontainer/to/somewhere') self.assertEqual(ll.modified, 1612355697654321000) self.assertEqual(ll.size, 12345) def test_comm_lineiter_good(self): a = '''\ contx|a|2021-02-03T12:34:56.654321|1234 contx|ab|2021-02-03T12:34:56.654321|1234 contx|b|2021-02-03T12:34:56.654321|1234 conty|a|2021-02-03T12:34:56.654321|1234'''.split('\n') it = _comm_lineiter(a) values = [i for i in it] self.assertEqual(values, [ ListLine('contx|a|2021-02-03T12:34:56.654321|1234'), ListLine('contx|ab|2021-02-03T12:34:56.654321|1234'), ListLine('contx|b|2021-02-03T12:34:56.654321|1234'), ListLine('conty|a|2021-02-03T12:34:56.654321|1234')]) def test_comm_lineiter_error(self): a = '''\ contx|a|2021-02-03T12:34:56.654321|1234 contx|c|2021-02-03T12:34:56.654321|1234 contx|b|2021-02-03T12:34:56.654321|1234'''.split('\n') it = _comm_lineiter(a) self.assertRaises(ValueError, list, it) class _ListLineCommTest(TestCase): def test_mixed(self): a = '''\ a|2021-02-03T12:34:56.654321|1234 b|2021-02-03T12:34:56.654321|1234 c|2021-02-03T12:34:56.654321|1234'''.split('\n') b = '''\ a|2021-02-03T12:34:56.654321|1234 b2|2021-02-03T12:34:56.654321|1234 b3|2021-02-03T12:34:56.654321|1234 c|2021-02-03T12:34:56.654321|1234 c2|2021-02-03T12:34:56.654321|1234'''.split('\n') act_both, act_left, act_right = [], [], [] llc = _ListLineComm(a, b) llc.act( both=(lambda line: act_both.append(line)), difftime=None, leftonly=(lambda line: act_left.append(line)), rightonly=(lambda line: act_right.append(line))) self.assertEqual(act_both, [ 'a|2021-02-03T12:34:56.654321|1234', 'c|2021-02-03T12:34:56.654321|1234']) self.assertEqual(act_left, [ 'b|2021-02-03T12:34:56.654321|1234']) self.assertEqual(act_right, [ 'b2|2021-02-03T12:34:56.654321|1234', 'b3|2021-02-03T12:34:56.654321|1234', 'c2|2021-02-03T12:34:56.654321|1234']) def test_oneonly(self): a = '''\ a|2021-02-03T12:34:56.654321|1234 b|2021-02-03T12:34:56.654321|1234 c|2021-02-03T12:34:56.654321|1234'''.split('\n') act_both, act_left, act_right = [], [], [] llc = _ListLineComm(a, []) llc.act( both=(lambda line: act_both.append(line)), difftime=None, leftonly=(lambda line: act_left.append(line)), rightonly=(lambda line: act_right.append(line))) self.assertEqual((act_both, act_left, act_right), ([], a, [])) act_both, act_left, act_right = [], [], [] llc = _ListLineComm([], a) llc.act( both=(lambda line: act_both.append(line)), difftime=None, leftonly=(lambda line: act_left.append(line)), rightonly=(lambda line: act_right.append(line))) self.assertEqual((act_both, act_left, act_right), ([], [], a)) def test_difftime(self): a = '''\ a|2021-02-03T12:34:56.654321|1234 b|2021-02-03T12:34:56.654321|1234 c|2021-02-03T12:34:56.654321|1234'''.split('\n') b = '''\ a|2021-02-03T12:34:56.654322|1234 b2|2021-02-03T12:34:56.654321|1234 b3|2021-02-03T12:34:56.654321|1234 c|2021-02-03T12:34:56.654322|1234 c2|2021-02-03T12:34:56.654321|1234'''.split('\n') act_both, act_difftime, act_left, act_right = [], [], [], [] llc = _ListLineComm(a, b) llc.act( both=(lambda line: act_both.append(line)), difftime=(lambda leftline, rightline: ( act_difftime.append((leftline, rightline)))), leftonly=(lambda line: act_left.append(line)), rightonly=(lambda line: act_right.append(line))) self.assertEqual(act_both, []) self.assertEqual(act_difftime, [ ('a|2021-02-03T12:34:56.654321|1234', 'a|2021-02-03T12:34:56.654322|1234'), ('c|2021-02-03T12:34:56.654321|1234', 'c|2021-02-03T12:34:56.654322|1234')]) self.assertEqual(act_left, [ 'b|2021-02-03T12:34:56.654321|1234']) self.assertEqual(act_right, [ 'b2|2021-02-03T12:34:56.654321|1234', 'b3|2021-02-03T12:34:56.654321|1234', 'c2|2021-02-03T12:34:56.654321|1234']) class Cli: def __init__(self): parser = ArgumentParser() parser.add_argument( '-c', '--config', metavar='configpath', default='~/.rclone.conf', help='inifile location') parser.add_argument('inisection') parser.add_argument( '--test-path-translate', metavar='testcontainer', help='test path translation with paths from stdin') parser.add_argument('container', nargs='?') parser.add_argument('--all-containers', action='store_true') self.args = parser.parse_args() if not self.args.test_path_translate: if not (bool(self.args.container) ^ bool(self.args.all_containers)): parser.error('either specify a container or --all-containers') @property def config(self): if not hasattr(self, '_config'): self._config = SwiftSyncConfig( os.path.expanduser(self.args.config), self.args.inisection) return self._config def execute(self): if self.args.test_path_translate: self.test_path_translate(self.args.test_path_translate) elif self.args.container: self.sync_container(self.args.container) elif self.args.all_containers: self.sync_all_containers() else: raise NotImplementedError() def sync_container(self, container_name): swiftsync = SwiftSync(self.config, container_name) swiftsync.sync() def sync_all_containers(self): swiftsync = SwiftSync(self.config) swiftsync.sync() def test_path_translate(self, container): translator = self.config.get_translator(container) try: while True: rpath = input() lpath = translator(rpath) print('{!r} => {!r}'.format(rpath, lpath)) except EOFError: pass if __name__ == '__main__': # Test using: python3 -m unittest contrib/planb-swiftsync.py cli = Cli() try: cli.execute() except SystemExit as e: # When it is not handled, the Python interpreter exits; no stack # traceback is printed. Print it ourselves. if e.code != 0: traceback.print_exc() sys.exit(e.code)
contrib/planb-swiftsync.py
codereval_python_data_125
Replace any custom string URL items with values in args def _replace_url_args(url, url_args): """Replace any custom string URL items with values in args""" if url_args: for key, value in url_args.items(): url = url.replace(f"{key}/", f"{value}/") return url #!/usr/bin/env python """ copyright (c) 2016 Earth Advantage. All rights reserved. ..codeauthor::Paul Munday <paul@paulmunday.net> Functionality for calls to external API's""" # Imports from Standard Library import re # Imports from Third Party Modules # Imports from External Modules import requests # Local Imports # Public Functions and Classes # Helper functions for use by BaseAPI subclasses from pyseed.exceptions import APIClientError def add_pk(url, pk, required=True, slash=False): """Add id/primary key to url""" if required and not pk: raise APIClientError('id/pk must be supplied') if pk: if isinstance(pk, str) and not pk.isdigit(): raise TypeError('id/pk must be a positive integer') elif not isinstance(pk, (int, str)) or int(pk) < 0: raise TypeError('id/pk must be a positive integer') if not url.endswith('/'): url = "{}/{}".format(url, pk) else: url = "{}{}".format(url, pk) if slash: # Only add the trailing slash if it's not already there if not url.endswith('/'): url = "{}/".format(url) return url def _replace_url_args(url, url_args): """Replace any custom string URL items with values in args""" if url_args: for key, value in url_args.items(): url = url.replace(f"{key}/", f"{value}/") return url class BaseAPI(object): """ Base class for API Calls """ # pylint: disable=too-few-public-methods, too-many-instance-attributes def __init__(self, url=None, use_ssl=True, timeout=None, use_json=False, use_auth=False, auth=None, **kwargs): # pylint: disable=too-many-arguments """Set url,api key, auth usage, ssl usage, timeout etc. :param url: url to use, http(s)://can be omitted, an error will will be used if it is supplied and dose not match use_ssl :param: use_ssl: connect over https, defaults to true :param use_auth: use authentication ..Note: if use_auth is True the default is to use http basic authentication if self.auth is not set. (You will need to to this by overriding __init__ and setting this before calling super. This requires username and password to be supplied as keyword arguments. N.B. api keys using basic auth e.g. SEED should be supplied as password. To use Digest Authentication set auth_method='digest' If use_ssl is False and the url you supply starts with https an error will be thrown. """ self.timeout = timeout self.use_ssl = use_ssl self.use_json = use_json self.use_auth = use_auth self.auth = auth self.url = None self.url = self._construct_url(url) if url else None for key, val in kwargs.items(): setattr(self, key, val) def _construct_payload(self, params): """Construct parameters for an api call. . :param params: An dictionary of key-value pairs to include in the request. :return: A dictionary of k-v pairs to send to the server in the request. """ compulsory = getattr(self, 'compulsory_params', []) for param in compulsory: if param not in params: try: params[param] = getattr(self, param) except AttributeError: msg = "{} is a compulsory field".format(param) raise APIClientError(msg) return params def _construct_url(self, urlstring, use_ssl=None): """Construct url""" # self.use_ssl takes priority to enforce ssl use use_ssl = self.use_ssl if self.use_ssl is not None else use_ssl if not urlstring and not self.url: raise APIClientError('No url set') elif not urlstring: url = self.url else: if urlstring.startswith('https://') and not use_ssl: # We strip off url prefix # raise an error if https is used in url without use_ssl raise APIClientError( 'use_ssl is false but url starts with https' ) elif urlstring.startswith('http://') and use_ssl: # We strip off url prefix # raise an error if http is used in url with use_ssl raise APIClientError( 'use_ssl is true but url does not starts with https' ) else: # strip http(s):// off url regex = re.compile('^https?://') urlstring = regex.sub('', urlstring) if use_ssl: start = 'https://' else: start = 'http://' url = "{}{}".format(start, urlstring) return url def check_call_success(self, response): """Return true if api call was successful.""" # pylint: disable=no-self-use, no-member return response.status_code == requests.codes.ok def _get(self, url=None, use_ssl=None, **kwargs): """Internal method to make api calls using GET.""" url = self._construct_url(url, use_ssl=use_ssl) params = self._construct_payload(kwargs) payload = { 'timeout': self.timeout, 'headers': params.pop('headers', None) } if params: payload['params'] = params if self.auth: # pragma: no cover payload['auth'] = self.auth api_call = requests.get(url, **payload) return api_call def _post(self, url=None, use_ssl=None, params=None, files=None, **kwargs): """Internal method to make api calls using POST.""" url = self._construct_url(url, use_ssl=use_ssl) if not params: params = {} params = self._construct_payload(params) payload = { 'timeout': self.timeout, 'headers': params.pop('headers', None) } if params: payload['params'] = params if files: payload['files'] = files if self.auth: # pragma: no cover payload['auth'] = self.auth if self.use_json: data = kwargs.pop('json', None) if data: payload['json'] = data else: # just put the remaining kwargs into the json field payload['json'] = kwargs else: data = kwargs.pop('data', None) if data: payload['data'] = data else: # just put the remaining kwargs into the data field payload['data'] = kwargs # if there are any remaining kwargs, then put them into the params if 'params' not in payload: payload['params'] = {} payload['params'].update(**kwargs) # now do the actual call to post! api_call = requests.post(url, **payload) return api_call def _put(self, url=None, use_ssl=None, params=None, files=None, **kwargs): """Internal method to make api calls using PUT.""" url = self._construct_url(url, use_ssl=use_ssl) if not params: params = {} params = self._construct_payload(params) payload = { 'timeout': self.timeout, 'headers': params.pop('headers', None) } if params: payload['params'] = params if files: # pragma: no cover payload['files'] = files if self.auth: # pragma: no cover payload['auth'] = self.auth if self.use_json: data = kwargs.pop('json', None) if data: payload['json'] = data else: # just put the remaining kwargs into the json field payload['json'] = kwargs else: data = kwargs.pop('data', None) if data: payload['data'] = data else: # just put the remaining kwargs into the data field payload['data'] = kwargs # if there are any remaining kwargs, then put them into the params if 'params' not in payload: payload['params'] = {} payload['params'].update(**kwargs) api_call = requests.put(url, **payload) return api_call def _patch(self, url=None, use_ssl=None, params=None, files=None, **kwargs): """Internal method to make api calls using PATCH.""" url = self._construct_url(url, use_ssl=use_ssl) if not params: params = {} params = self._construct_payload(params) payload = { 'timeout': self.timeout, 'headers': params.pop('headers', None) } if params: payload['params'] = params if files: payload['files'] = files if self.auth: # pragma: no cover payload['auth'] = self.auth if self.use_json: data = kwargs.pop('json', None) if data: payload['json'] = data else: # just put the remaining kwargs into the json field payload['json'] = kwargs else: data = kwargs.pop('data', None) if data: payload['data'] = data else: # just put the remaining kwargs into the data field payload['data'] = kwargs # if there are any remaining kwargs, then put them into the params if 'params' not in payload: payload['params'] = {} payload['params'].update(**kwargs) api_call = requests.patch(url, **payload) return api_call def _delete(self, url=None, use_ssl=None, **kwargs): """Internal method to make api calls using DELETE.""" url = self._construct_url(url, use_ssl=use_ssl) params = self._construct_payload(kwargs) payload = { 'timeout': self.timeout, 'headers': params.pop('headers', None) } if params: payload['params'] = params if self.auth: # pragma: no cover payload['auth'] = self.auth api_call = requests.delete(url, **payload) return api_call class JSONAPI(BaseAPI): """ Base class for Json API Calls. See BaseAPI for documentation. """ # pylint: disable=too-few-public-methods, too-many-arguments def __init__(self, url=None, use_ssl=True, timeout=None, use_auth=False, auth=None, **kwargs): super(JSONAPI, self).__init__( url=url, use_ssl=use_ssl, timeout=timeout, use_json=True, use_auth=use_auth, auth=auth, **kwargs ) class UserAuthMixin(object): """ Mixin to provide basic or digest api client authentication via username and password(or api_key).""" # pylint:disable=too-few-public-methods def _get_auth(self): """Get basic or digest auth by username/password""" username = getattr(self, 'username', None) password = getattr(self, 'password', None) # support using api_key as password in basic auth # as used by SEED (if supplied as api_key not password) if not password: password = getattr(self, 'api_key', None) if getattr(self, 'auth_method', None) == 'digest': auth = requests.auth.HTTPDigestAuth(username, password) else: auth = requests.auth.HTTPBasicAuth(username, password) return auth def _construct_payload(self, params): """Construct parameters for an api call. . :param params: An dictionary of key-value pairs to include in the request. :return: A dictionary of k-v pairs to send to the server in the request. """ if getattr(self, 'use_auth', None) and not getattr(self, 'auth', None): self.auth = self._get_auth() return super(UserAuthMixin, self)._construct_payload(params) class OAuthMixin(object): """ Mixin to provide api client authentication via OAuth access tokens based on the JWTGrantClient found in jwt-oauth2lib. see https://github.com/GreenBuildingRegistry/jwt_oauth2 """ _token_type = "Bearer" oauth_client = None def _get_access_token(self): """Generate OAuth access token""" private_key_file = getattr(self, 'private_key_location', None) client_id = getattr(self, 'client_id', None) username = getattr(self, 'username', None) with open(private_key_file, 'r') as pk_file: sig = pk_file.read() oauth_client = self.oauth_client( sig, username, client_id, pvt_key_password=getattr(self, 'pvt_key_password', None) ) return oauth_client.get_access_token() def _construct_payload(self, params): """Construct parameters for an api call. . :param params: An dictionary of key-value pairs to include in the request. :return: A dictionary of k-v pairs to send to the server in the request. """ params = super(OAuthMixin, self)._construct_payload(params) token = getattr(self, 'token', None) or self._get_access_token() params['headers'] = { 'Authorization': '{} {}'.format(self._token_type, token) } return params
pyseed/apibase.py
codereval_python_data_126
Check if a string represents a None value. def is_none_string(val: any) -> bool: """Check if a string represents a None value.""" if not isinstance(val, str): return False return val.lower() == 'none' # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import annotations import typing from typing import Any, Generator, Iterable, Optional, Union # noqa: H301 from keystoneauth1 import exceptions as ks_exc from keystoneauth1 import identity from keystoneauth1 import loading as ka_loading from keystoneclient import client from oslo_config import cfg from oslo_log import log as logging from oslo_utils import strutils import webob from webob import exc if typing.TYPE_CHECKING: # conditional import to avoid a circular import problem from cinderlib from cinder import context from cinder import exception from cinder.i18n import _ CONF = cfg.CONF CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token.__init__') LOG = logging.getLogger(__name__) def _parse_is_public(is_public: Optional[str]) -> Optional[bool]: """Parse is_public into something usable. * True: List public volume types only * False: List private volume types only * None: List both public and private volume types """ if is_public is None: # preserve default value of showing only public types return True elif is_none_string(is_public): return None else: try: return strutils.bool_from_string(is_public, strict=True) except ValueError: msg = _('Invalid is_public filter [%s]') % is_public raise exc.HTTPBadRequest(explanation=msg) def is_none_string(val: Any) -> bool: """Check if a string represents a None value.""" if not isinstance(val, str): return False return val.lower() == 'none' def remove_invalid_filter_options( context: 'context.RequestContext', filters: dict, allowed_search_options: Iterable[str]) -> None: """Remove search options that are not valid for non-admin API/context.""" if context.is_admin: # Allow all options return # Otherwise, strip out all unknown options unknown_options = [opt for opt in filters if opt not in allowed_search_options] bad_options = ", ".join(unknown_options) LOG.debug("Removing options '%s' from query.", bad_options) for opt in unknown_options: del filters[opt] _visible_admin_metadata_keys = ['readonly', 'attached_mode'] def add_visible_admin_metadata(volume) -> None: """Add user-visible admin metadata to regular metadata. Extracts the admin metadata keys that are to be made visible to non-administrators, and adds them to the regular metadata structure for the passed-in volume. """ visible_admin_meta = {} if volume.get('volume_admin_metadata'): if isinstance(volume['volume_admin_metadata'], dict): volume_admin_metadata = volume['volume_admin_metadata'] for key in volume_admin_metadata: if key in _visible_admin_metadata_keys: visible_admin_meta[key] = volume_admin_metadata[key] else: for item in volume['volume_admin_metadata']: if item['key'] in _visible_admin_metadata_keys: visible_admin_meta[item['key']] = item['value'] # avoid circular ref when volume is a Volume instance elif (volume.get('admin_metadata') and isinstance(volume.get('admin_metadata'), dict)): for key in _visible_admin_metadata_keys: if key in volume['admin_metadata'].keys(): visible_admin_meta[key] = volume['admin_metadata'][key] if not visible_admin_meta: return # NOTE(zhiyan): update visible administration metadata to # volume metadata, administration metadata will rewrite existing key. if volume.get('volume_metadata'): orig_meta = list(volume.get('volume_metadata')) for item in orig_meta: if item['key'] in visible_admin_meta.keys(): item['value'] = visible_admin_meta.pop(item['key']) for key, value in visible_admin_meta.items(): orig_meta.append({'key': key, 'value': value}) volume['volume_metadata'] = orig_meta # avoid circular ref when vol is a Volume instance elif (volume.get('metadata') and isinstance(volume.get('metadata'), dict)): volume['metadata'].update(visible_admin_meta) else: volume['metadata'] = visible_admin_meta def validate_integer(value: int, name: str, min_value: Optional[int] = None, max_value: Optional[int] = None) -> int: """Make sure that value is a valid integer, potentially within range. :param value: the value of the integer :param name: the name of the integer :param min_value: the min value of the integer :param max_value: the max value of the integer :returns: integer """ try: value = strutils.validate_integer(value, name, min_value, max_value) return value except ValueError as e: raise webob.exc.HTTPBadRequest(explanation=str(e)) def walk_class_hierarchy(clazz: type, encountered: Optional[list[type]] = None) -> \ Generator[type, None, None]: """Walk class hierarchy, yielding most derived classes first.""" if not encountered: encountered = [] for subclass in clazz.__subclasses__(): if subclass not in encountered: encountered.append(subclass) # drill down to leaves first for subsubclass in walk_class_hierarchy(subclass, encountered): yield subsubclass yield subclass def _keystone_client(context: 'context.RequestContext', version: tuple[int, int] = (3, 0)) -> client.Client: """Creates and returns an instance of a generic keystone client. :param context: The request context :param version: version of Keystone to request :return: keystoneclient.client.Client object """ if context.system_scope is not None: auth_plugin = identity.Token( auth_url=CONF.keystone_authtoken.auth_url, token=context.auth_token, system_scope=context.system_scope ) elif context.domain_id is not None: auth_plugin = identity.Token( auth_url=CONF.keystone_authtoken.auth_url, token=context.auth_token, domain_id=context.domain_id ) elif context.project_id is not None: auth_plugin = identity.Token( auth_url=CONF.keystone_authtoken.auth_url, token=context.auth_token, project_id=context.project_id ) else: # We're dealing with an unscoped token from keystone that doesn't # carry any authoritative power outside of the user simplify proving # they know their own password. This token isn't associated with any # authorization target (e.g., system, domain, or project). auth_plugin = context.get_auth_plugin() client_session = ka_loading.session.Session().load_from_options( auth=auth_plugin, insecure=CONF.keystone_authtoken.insecure, cacert=CONF.keystone_authtoken.cafile, key=CONF.keystone_authtoken.keyfile, cert=CONF.keystone_authtoken.certfile, split_loggers=CONF.service_user.split_loggers) return client.Client(auth_url=CONF.keystone_authtoken.auth_url, session=client_session, version=version) class GenericProjectInfo(object): """Abstraction layer for Keystone V2 and V3 project objects""" def __init__(self, project_id: str, project_keystone_api_version: str, domain_id: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None): self.id = project_id self.keystone_api_version = project_keystone_api_version self.domain_id = domain_id self.name = name self.description = description def get_project(context: 'context.RequestContext', project_id: str) -> GenericProjectInfo: """Method to verify project exists in keystone""" keystone = _keystone_client(context) generic_project = GenericProjectInfo(project_id, keystone.version) project = keystone.projects.get(project_id) generic_project.domain_id = project.domain_id generic_project.name = project.name generic_project.description = project.description return generic_project def validate_project_and_authorize(context: 'context.RequestContext', project_id: str, policy_check: str, validate_only: bool = False) -> None: target_project: Union[GenericProjectInfo, dict] try: target_project = get_project(context, project_id) if not validate_only: target_project = {'project_id': target_project.id} context.authorize(policy_check, target=target_project) except ks_exc.http.NotFound: explanation = _("Project with id %s not found." % project_id) raise exc.HTTPNotFound(explanation=explanation) except exception.NotAuthorized: explanation = _("You are not authorized to perform this " "operation.") raise exc.HTTPForbidden(explanation=explanation)
cinder/api/api_utils.py
codereval_python_data_127
Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in action.option_strings) import pkg_resources from borgmatic.commands import arguments UPGRADE_MESSAGE = ''' Your bash completions script is from a different version of borgmatic than is currently installed. Please upgrade your script so your completions match the command-line flags in your installed borgmatic! Try this to upgrade: sudo sh -c "borgmatic --bash-completions > $BASH_SOURCE" source $BASH_SOURCE ''' def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in action.option_strings) def bash_completion(): ''' Return a bash completion script for the borgmatic command. Produce this by introspecting borgmatic's command-line argument parsers. ''' top_level_parser, subparsers = arguments.make_parsers() global_flags = parser_flags(top_level_parser) actions = ' '.join(subparsers.choices.keys()) borgmatic_version = pkg_resources.require('borgmatic')[0].version # Avert your eyes. return '\n'.join( ( 'check_version() {', ' local installed_version="$(borgmatic --version 2> /dev/null)"', ' if [ "$installed_version" != "%s" ] && [ "$installed_version" != "" ];' % borgmatic_version, ' then cat << EOF\n%s\nEOF' % UPGRADE_MESSAGE, ' fi', '}', 'complete_borgmatic() {', ) + tuple( ''' if [[ " ${COMP_WORDS[*]} " =~ " %s " ]]; then COMPREPLY=($(compgen -W "%s %s %s" -- "${COMP_WORDS[COMP_CWORD]}")) return 0 fi''' % (action, parser_flags(subparser), actions, global_flags) for action, subparser in subparsers.choices.items() ) + ( ' COMPREPLY=($(compgen -W "%s %s" -- "${COMP_WORDS[COMP_CWORD]}"))' % (actions, global_flags), ' (check_version &)', '}', '\ncomplete -F complete_borgmatic borgmatic', ) )
borgmatic/commands/completion.py
codereval_python_data_128
Check if a file or directory has already been processed. To prevent recursion, expand the path name to an absolution path call this function with a set that will store all the entries and the entry to test. If the entry is already in the set, report the issue and return ``True``. Otherwise, add the entry to the set and return ``False`` to allow the path to be processed. Args: processed: Set to store processed pathnames path_name: Path to a directory or file verbose: True if verbose output is requested Returns: True if it's already in the set. False if not. def was_processed(processed, path_name, verbose): """ Check if a file or directory has already been processed. To prevent recursion, expand the path name to an absolution path call this function with a set that will store all the entries and the entry to test. If the entry is already in the set, report the issue and return ``True``. Otherwise, add the entry to the set and return ``False`` to allow the path to be processed. Args: processed: Set to store processed pathnames path_name: Path to a directory or file verbose: True if verbose output is requested Returns: True if it's already in the set. False if not. """ # Test for recursion if path_name in processed: if verbose: print('{} has already been processed'.format(path_name)) return True # Mark this list as "processed" to prevent recursion if verbose: print('Processing {}.'.format(path_name)) processed.add(path_name) return False #!/usr/bin/env python # -*- coding: utf-8 -*- """ The util module contains subroutines used everywhere. @package makeprojects.util """ from __future__ import absolute_import, print_function, unicode_literals import os import re import fnmatch from burger import string_to_bool, is_string, import_py_script from .enums import FileTypes from .config import DEFAULT_BUILD_RULES # pylint: disable=consider-using-f-string ######################################## def validate_enum_type(value, data_type): """ Verify a value is a specific data type. Check if the value is either None or an instance of a specfic data type. If so, return immediately. If the value is a string, call the lookup() function of the data type for conversion. Args: value: Value to check. data_type: Type instance of the class type to match. Returns: Value converted to data_type or None. Raises: TypeError """ if value is not None: # Perform the lookup new_value = data_type.lookup(value) if new_value is None: msg = '"{}" must be of type "{}".'.format( value, data_type.__name__) raise TypeError(msg) # Save the converted type value = new_value return value ######################################## def regex_dict(item): """ Convert *.cpp keys to regex keys Given a dict where the keys are all filenames with wildcards, convert only the keys into equivalent regexes and leave the values intact. Examples: rules = { '*.cpp': {'a': 'arf', 'b': 'bark', 'c': 'coo'}, '*.h': {'h': 'help'} } regex_keys = regex_dict(rules) Args: item: dict to convert Returns: dict with keys converted to regexes """ output = {} for key in item: output[re.compile(fnmatch.translate(key)).match] = item[key] return output ######################################## def validate_boolean(value): """ Verify a value is a boolean. Check if the value can be converted to a bool, if so, return the value as bool. None is converted to False. Args: value: Value to check. Returns: Value converted to data_type or None. Raises: ValueError """ if value is not None: # Convert to bool value = string_to_bool(value) return value ######################################## def validate_string(value): """ Verify a value is a string. Check if the value is a string, if so, return the value as is or None. Args: value: Value to check. Returns: Value is string or None. Raises: ValueError """ if value is not None: # Convert to bool if not is_string(value): raise ValueError('"{}" must be a string.'.format(value)) return value ######################################## def source_file_filter(file_list, file_type_list): """ Prune the file list for a specific type. Note: file_type_list can either be a single enums.FileTypes enum or an iterable list of enums.FileTypes Args: file_list: list of core.SourceFile entries. file_type_list: enums.FileTypes to match. Returns: list of matching core.SourceFile entries. """ result_list = [] # If a single item was passed, use a simple loop if isinstance(file_type_list, FileTypes): for item in file_list: if item.type is file_type_list: result_list.append(item) else: # A list was passed, so test against the list for item in file_list: if item.type in file_type_list: result_list.append(item) return result_list ######################################## def add_build_rules(build_rules_list, file_name, verbose, is_root, basename): """ Load in the file ``build_rules.py`` Load the build_rules.py file. If the variable ``*_GENERIC`` is ``True`` or if ``is_root`` is ``True``, append the module to ``build_rules_list``. If the variable ``*_CONTINUE`` was found in the file, check if it is set to ``True``. If so, return ``True`` to allow processing to continue. If the file is not found, return ``True`` to allow processing the parent folder. Since this is called from ``buildme``, ``cleanme``, and ``makeprojects``, the prefix needed for the tool is passed in ``basename``. An example is "CLEANME". Args: build_rules_list: List to add ``build_rules.py`` instances. file_name: Full path name of the build_rules.py to load. verbose: True for verbose output. is_root: True if *_GENERIC is ignored. basename: Variable prefix to substitute * in *_GENERIC Returns: True if the parent folder should be checked, False if not. """ # Ensure the absolute path is used. file_name = os.path.abspath(file_name) build_rules = import_py_script(file_name) # Not found? Continue parsing folders. if not build_rules: return True if is_root or getattr(build_rules, basename + "_GENERIC", False) or getattr(build_rules, "GENERIC", False): # Add to the list build_rules_list.append(build_rules) if verbose: print('Using configuration file {}'.format(file_name)) # Test if this is considered the last one in the chain. result = getattr(build_rules, basename + "_CONTINUE", None) # Not found? if result is None: # Try the catch all version result = getattr(build_rules, "CONTINUE", False) return result ######################################## def get_build_rules(working_directory, verbose, build_rules_name, basename): """ Find all ``build_rules.py`` files that apply to this directory. If no files are found, return an empty list. Args: working_directory: Directory to scan for ``build_rules.py`` verbose: True if verbose output is desired build_rules_name: ``build_rules.py`` or an override basename: "CLEANME", "BUILDME", etc. Returns: List of loaded ``build_rules.py`` file modules """ # Test if there is a specific build rule build_rules_list = [] # Load the configuration file at the current directory temp_dir = os.path.abspath(working_directory) # Is this the first pass? is_root = True while True: # Attempt to load in the build rules. if not add_build_rules( build_rules_list, os.path.join( temp_dir, build_rules_name), verbose, is_root, basename): # Abort if *_CONTINUE = False break # Directory traversal is active, require CLEANME_GENERIC is_root = False # Pop a folder to check for higher level build_rules.py temp_dir2 = os.path.dirname(temp_dir) # Already at the top of the directory? if temp_dir2 is None or temp_dir2 == temp_dir: add_build_rules( build_rules_list, DEFAULT_BUILD_RULES, verbose, True, basename) break # Use the new folder temp_dir = temp_dir2 return build_rules_list ######################################## def getattr_build_rules(build_rules_list, attributes, value): """ Find an attribute in a list of build rules. Iterate over the build rules list until an entry has an attribute value. It will return the first one found. If none are found, or there were no entries in ``build_rules_list``, this function returns ``value``. Args: build_rules_list: List of ``build_rules.py`` instances. attributes: Attribute name(s) to check for. value: Value to return if the attribute was not found. Returns: Attribute value found in ``build_rules_list`` entry, or ``value``. """ # Ensure if it is a single string if is_string(attributes): for build_rules in build_rules_list: # Does the entry have this attribute? try: return getattr(build_rules, attributes) except AttributeError: pass else: # Assume attributes is an iterable of strings for build_rules in build_rules_list: # Does the rules file have this attribute? for attribute in attributes: try: return getattr(build_rules, attribute) except AttributeError: pass # Return the default value return value ######################################## def remove_ending_os_sep(input_list): """ Iterate over a string list and remove trailing os seperator characters. Each string is tested if its length is greater than one and if the last character is the pathname seperator. If so, the pathname seperator character is removed. Args: input_list: list of strings Returns: Processed list of strings Raises: TypeError """ # Input could be None, so test for that case if input_list is None: return [] return [item[:-1] if len(item) >= 2 and item.endswith(os.sep) else item for item in input_list] ######################################## def was_processed(processed, path_name, verbose): """ Check if a file or directory has already been processed. To prevent recursion, expand the path name to an absolution path call this function with a set that will store all the entries and the entry to test. If the entry is already in the set, report the issue and return ``True``. Otherwise, add the entry to the set and return ``False`` to allow the path to be processed. Args: processed: Set to store processed pathnames path_name: Path to a directory or file verbose: True if verbose output is requested Returns: True if it's already in the set. False if not. """ # Test for recursion if path_name in processed: if verbose: print('{} has already been processed'.format(path_name)) return True # Mark this list as "processed" to prevent recursion if verbose: print('Processing {}.'.format(path_name)) processed.add(path_name) return False
makeprojects/util.py
codereval_python_data_129
return 3 points for each vertex of the polygon. This will include the vertex and the 2 points on both sides of the vertex:: polygon with vertices ABCD Will return DAB, ABC, BCD, CDA -> returns 3tuples #A B C D -> of vertices def vertex3tuple(vertices): """return 3 points for each vertex of the polygon. This will include the vertex and the 2 points on both sides of the vertex:: polygon with vertices ABCD Will return DAB, ABC, BCD, CDA -> returns 3tuples #A B C D -> of vertices """ asvertex_list = [] for i in range(len(vertices)): try: asvertex_list.append((vertices[i-1], vertices[i], vertices[i+1])) except IndexError as e: asvertex_list.append((vertices[i-1], vertices[i], vertices[0])) return asvertex_list # Copyright (c) 2012 Tuan Tran # Copyright (c) 2020 Cheng Cui # This file is part of eppy. # ======================================================================= # Distributed under the MIT License. # (See accompanying file LICENSE or copy at # http://opensource.org/licenses/MIT) # ======================================================================= """This module is used for assisted calculations on E+ surfaces""" # Wrote by Tuan Tran trantuan@hawaii.edu / tranhuuanhtuan@gmail.com # School of Architecture, University of Hawaii at Manoa # The following code within the block # credited by ActiveState Code Recipes code.activestate.com ## {{{ http://code.activestate.com/recipes/578276/ (r1) from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals try: import numpy as np from numpy import arccos as acos except ImportError as err: from tinynumpy import tinynumpy as np from tinynumpy import tinylinalg as linalg from math import acos as acos import math def area(poly): """Area of a polygon poly""" if len(poly) < 3: # not a plane - no area return 0 total = [0, 0, 0] num = len(poly) for i in range(num): vi1 = poly[i] vi2 = poly[(i + 1) % num] prod = np.cross(vi1, vi2) total[0] += prod[0] total[1] += prod[1] total[2] += prod[2] if total == [0, 0, 0]: # points are in a straight line - no area return 0 try: the_unitnormal = get_an_unit_normal(poly) except ZeroDivisionError as e: return 0 # all the points in the poly are in a straight line result = np.dot(total, the_unitnormal) # result = np.dot(total, unit_normal(poly[0], poly[1], poly[2])) return abs(result / 2) def vertex3tuple(vertices): """return 3 points for each vertex of the polygon. This will include the vertex and the 2 points on both sides of the vertex:: polygon with vertices ABCD Will return DAB, ABC, BCD, CDA -> returns 3tuples #A B C D -> of vertices """ asvertex_list = [] for i in range(len(vertices)): try: asvertex_list.append((vertices[i-1], vertices[i], vertices[i+1])) except IndexError as e: asvertex_list.append((vertices[i-1], vertices[i], vertices[0])) return asvertex_list def get_an_unit_normal(poly): """try each vertex of the poly for a unit_normal. Return the unit_normal on sucess""" for three_t in vertex3tuple(poly): try: return unit_normal(three_t[0], three_t[1], three_t[2]) except ZeroDivisionError as e: continue # these 3 points are in a striaght line. try next three raise ZeroDivisionError # all points are in a striaght line def unit_normal(pt_a, pt_b, pt_c): """unit normal vector of plane defined by points pt_a, pt_b, and pt_c""" x_val = np.linalg.det( [[1, pt_a[1], pt_a[2]], [1, pt_b[1], pt_b[2]], [1, pt_c[1], pt_c[2]]] ) y_val = np.linalg.det( [[pt_a[0], 1, pt_a[2]], [pt_b[0], 1, pt_b[2]], [pt_c[0], 1, pt_c[2]]] ) z_val = np.linalg.det( [[pt_a[0], pt_a[1], 1], [pt_b[0], pt_b[1], 1], [pt_c[0], pt_c[1], 1]] ) magnitude = (x_val ** 2 + y_val ** 2 + z_val ** 2) ** 0.5 mag = (x_val / magnitude, y_val / magnitude, z_val / magnitude) if magnitude < 0.00000001: mag = (0, 0, 0) return mag ## end of http://code.activestate.com/recipes/578276/ }}} # distance between two points def dist(pt1, pt2): """Distance between two points""" return ( (pt2[0] - pt1[0]) ** 2 + (pt2[1] - pt1[1]) ** 2 + (pt2[2] - pt1[2]) ** 2 ) ** 0.5 # width of a rectangular polygon def width(poly): """Width of a polygon poly""" num = len(poly) - 1 if abs(poly[num][2] - poly[0][2]) < abs(poly[1][2] - poly[0][2]): return dist(poly[num], poly[0]) elif abs(poly[num][2] - poly[0][2]) > abs(poly[1][2] - poly[0][2]): return dist(poly[1], poly[0]) else: return max(dist(poly[num], poly[0]), dist(poly[1], poly[0])) # height of a polygon poly def height(poly): """Height of a polygon poly""" num = len(poly) - 1 if abs(poly[num][2] - poly[0][2]) > abs(poly[1][2] - poly[0][2]): return dist(poly[num], poly[0]) elif abs(poly[num][2] - poly[0][2]) < abs(poly[1][2] - poly[0][2]): return dist(poly[1], poly[0]) else: return min(dist(poly[num], poly[0]), dist(poly[1], poly[0])) def angle2vecs(vec1, vec2): """angle between two vectors""" # vector a * vector b = |a|*|b|* cos(angle between vector a and vector b) dot = np.dot(vec1, vec2) vec1_modulus = np.sqrt(np.multiply(vec1, vec1).sum()) vec2_modulus = np.sqrt(np.multiply(vec2, vec2).sum()) if (vec1_modulus * vec2_modulus) == 0: cos_angle = 1 else: cos_angle = dot / (vec1_modulus * vec2_modulus) return math.degrees(acos(cos_angle)) # orienation of a polygon poly def azimuth(poly): """Azimuth of a polygon poly""" num = len(poly) - 1 vec = unit_normal(poly[0], poly[1], poly[num]) vec_azi = np.array([vec[0], vec[1], 0]) vec_n = np.array([0, 1, 0]) # update by Santosh # angle2vecs gives the smallest angle between the vectors # so for a west wall angle2vecs will give 90 # the following 'if' statement will make sure 270 is returned x_vector = vec_azi[0] if x_vector < 0: return 360 - angle2vecs(vec_azi, vec_n) else: return angle2vecs(vec_azi, vec_n) def true_azimuth(bldg_north, zone_rel_north, surf_azimuth): """True azimuth of a building surface""" bldg_north = 0 if bldg_north == "" else bldg_north zone_rel_north = 0 if zone_rel_north == "" else zone_rel_north return (bldg_north + zone_rel_north + surf_azimuth) % 360 def tilt(poly): """Tilt of a polygon poly""" num = len(poly) - 1 vec = unit_normal(poly[0], poly[1], poly[num]) vec_alt = np.array([vec[0], vec[1], vec[2]]) vec_z = np.array([0, 0, 1]) return angle2vecs(vec_alt, vec_z)
eppy/geometry/surface.py
codereval_python_data_130
Convert a number to a string, using the given alphabet. The output has the most significant digit first. def int_to_string(number: int, alphabet: List[str], padding: Optional[int] = None) -> str: """ Convert a number to a string, using the given alphabet. The output has the most significant digit first. """ output = "" alpha_len = len(alphabet) while number: number, digit = divmod(number, alpha_len) output += alphabet[digit] if padding: remainder = max(padding - len(output), 0) output = output + alphabet[0] * remainder return output[::-1] """Concise UUID generation.""" import binascii import math import os import uuid as _uu from typing import List, Optional def int_to_string(number: int, alphabet: List[str], padding: Optional[int] = None) -> str: """ Convert a number to a string, using the given alphabet. The output has the most significant digit first. """ output = "" alpha_len = len(alphabet) while number: number, digit = divmod(number, alpha_len) output += alphabet[digit] if padding: remainder = max(padding - len(output), 0) output = output + alphabet[0] * remainder return output[::-1] def string_to_int(string: str, alphabet: List[str]) -> int: """ Convert a string to a number, using the given alphabet. The input is assumed to have the most significant digit first. """ number = 0 alpha_len = len(alphabet) for char in string: number = number * alpha_len + alphabet.index(char) return number class ShortUUID(object): def __init__(self, alphabet: Optional[List[str]] = None) -> None: if alphabet is None: alphabet = list( "23456789ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz" ) self.set_alphabet(alphabet) @property def _length(self) -> int: """Return the necessary length to fit the entire UUID given the current alphabet.""" return int(math.ceil(math.log(2 ** 128, self._alpha_len))) def encode(self, uuid: _uu.UUID, pad_length: Optional[int] = None) -> str: """ Encode a UUID into a string (LSB first) according to the alphabet. If leftmost (MSB) bits are 0, the string might be shorter. """ if not isinstance(uuid, _uu.UUID): raise ValueError("Input `uuid` must be a UUID object.") if pad_length is None: pad_length = self._length return int_to_string(uuid.int, self._alphabet, padding=pad_length) def decode(self, string: str, legacy: bool = False) -> _uu.UUID: """ Decode a string according to the current alphabet into a UUID. Raises ValueError when encountering illegal characters or a too-long string. If string too short, fills leftmost (MSB) bits with 0. Pass `legacy=True` if your UUID was encoded with a ShortUUID version prior to 1.0.0. """ if not isinstance(string, str): raise ValueError("Input `string` must be a str.") if legacy: string = string[::-1] return _uu.UUID(int=string_to_int(string, self._alphabet)) def uuid(self, name: Optional[str] = None, pad_length: Optional[int] = None) -> str: """ Generate and return a UUID. If the name parameter is provided, set the namespace to the provided name and generate a UUID. """ if pad_length is None: pad_length = self._length # If no name is given, generate a random UUID. if name is None: u = _uu.uuid4() elif name.lower().startswith(("http://", "https://")): u = _uu.uuid5(_uu.NAMESPACE_URL, name) else: u = _uu.uuid5(_uu.NAMESPACE_DNS, name) return self.encode(u, pad_length) def random(self, length: Optional[int] = None) -> str: """Generate and return a cryptographically secure short random string of `length`.""" if length is None: length = self._length random_num = int(binascii.b2a_hex(os.urandom(length)), 16) return int_to_string(random_num, self._alphabet, padding=length)[:length] def get_alphabet(self) -> str: """Return the current alphabet used for new UUIDs.""" return "".join(self._alphabet) def set_alphabet(self, alphabet: str) -> None: """Set the alphabet to be used for new UUIDs.""" # Turn the alphabet into a set and sort it to prevent duplicates # and ensure reproducibility. new_alphabet = list(sorted(set(alphabet))) if len(new_alphabet) > 1: self._alphabet = new_alphabet self._alpha_len = len(self._alphabet) else: raise ValueError("Alphabet with more than " "one unique symbols required.") def encoded_length(self, num_bytes: int = 16) -> int: """Return the string length of the shortened UUID.""" factor = math.log(256) / math.log(self._alpha_len) return int(math.ceil(factor * num_bytes)) # For backwards compatibility _global_instance = ShortUUID() encode = _global_instance.encode decode = _global_instance.decode uuid = _global_instance.uuid random = _global_instance.random get_alphabet = _global_instance.get_alphabet set_alphabet = _global_instance.set_alphabet
shortuuid/main.py
codereval_python_data_131
Replace value from flows to given register number 'register_value' key in dictionary will be replaced by register number given by 'register_number' :param flow_params: Dictionary containing defined flows :param register_number: The number of register where value will be stored :param register_value: Key to be replaced by register number def _replace_register(flow_params, register_number, register_value): """Replace value from flows to given register number 'register_value' key in dictionary will be replaced by register number given by 'register_number' :param flow_params: Dictionary containing defined flows :param register_number: The number of register where value will be stored :param register_value: Key to be replaced by register number """ try: reg_port = flow_params[register_value] del flow_params[register_value] flow_params['reg{:d}'.format(register_number)] = reg_port except KeyError: pass return flow_params # expose the observer to the test_module # Copyright 2022 # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron_lib.agent.common import constants def _replace_register(flow_params, register_number, register_value): """Replace value from flows to given register number 'register_value' key in dictionary will be replaced by register number given by 'register_number' :param flow_params: Dictionary containing defined flows :param register_number: The number of register where value will be stored :param register_value: Key to be replaced by register number """ try: reg_port = flow_params[register_value] del flow_params[register_value] flow_params['reg{:d}'.format(register_number)] = reg_port except KeyError: pass def create_reg_numbers(flow_params): """Replace reg_(port|net) values with defined register numbers""" _replace_register(flow_params, constants.REG_PORT, constants.PORT_REG_NAME) _replace_register(flow_params, constants.REG_NET, constants.NET_REG_NAME) _replace_register(flow_params, constants.REG_REMOTE_GROUP, constants.REMOTE_GROUP_REG_NAME) _replace_register(flow_params, constants.REG_MIN_BW, constants.MIN_BW_REG_NAME) _replace_register(flow_params, constants.REG_INGRESS_BW_LIMIT, constants.INGRESS_BW_LIMIT_REG_NAME)
neutron_lib/agent/common/utils.py
codereval_python_data_132
Replaces all values of '.' to arg from the given string def replace_dots(value, arg): """Replaces all values of '.' to arg from the given string""" return value.replace(".", arg) # Copyright (C) 2022 The Sipwise Team - http://sipwise.com # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def replace_dots(value, arg): """Replaces all values of '.' to arg from the given string""" return value.replace(".", arg)
release_dashboard/templatetags/rd_extras.py
codereval_python_data_133
Return all subclasses of a class, recursively def subclasses(cls): """Return all subclasses of a class, recursively""" children = cls.__subclasses__() return set(children).union( set(grandchild for child in children for grandchild in subclasses(child)) ) # coding: utf-8 # Copyright 2014-2020 Álvaro Justen <https://github.com/turicas/rows/> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import cgi import csv import gzip import io import mimetypes import os import re import shlex import sqlite3 import subprocess import tempfile from collections import OrderedDict from dataclasses import dataclass from itertools import islice from pathlib import Path from textwrap import dedent import six try: import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry except ImportError: requests = None try: from tqdm import tqdm except ImportError: tqdm = None import rows from rows.plugins.utils import make_header try: import lzma except ImportError: lzma = None try: import bz2 except ImportError: bz2 = None try: from urlparse import urlparse # Python 2 except ImportError: from urllib.parse import urlparse # Python 3 try: import magic except (ImportError, TypeError): magic = None else: if not hasattr(magic, "detect_from_content"): # This is not the file-magic library magic = None if requests: chardet = requests.compat.chardet try: import urllib3 except ImportError: from requests.packages import urllib3 else: try: urllib3.disable_warnings() except AttributeError: # old versions of urllib3 or requests pass else: chardet = None # TODO: should get this information from the plugins COMPRESSED_EXTENSIONS = ("gz", "xz", "bz2") TEXT_PLAIN = { "txt": "text/txt", "text": "text/txt", "csv": "text/csv", "json": "application/json", } OCTET_STREAM = { "microsoft ooxml": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "par archive data": "application/parquet", } FILE_EXTENSIONS = { "csv": "text/csv", "db": "application/x-sqlite3", "htm": "text/html", "html": "text/html", "json": "application/json", "ods": "application/vnd.oasis.opendocument.spreadsheet", "parquet": "application/parquet", "sqlite": "application/x-sqlite3", "text": "text/txt", "tsv": "text/csv", "txt": "text/txt", "xls": "application/vnd.ms-excel", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pdf": "application/pdf", } MIME_TYPE_TO_PLUGIN_NAME = { "application/json": "json", "application/parquet": "parquet", "application/vnd.ms-excel": "xls", "application/vnd.oasis.opendocument.spreadsheet": "ods", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx", "application/x-sqlite3": "sqlite", "text/csv": "csv", "text/html": "html", "text/txt": "txt", "application/pdf": "pdf", } regexp_sizes = re.compile("([0-9,.]+ [a-zA-Z]+B)") MULTIPLIERS = {"B": 1, "KiB": 1024, "MiB": 1024 ** 2, "GiB": 1024 ** 3} def subclasses(cls): """Return all subclasses of a class, recursively""" children = cls.__subclasses__() return set(children).union( set(grandchild for child in children for grandchild in subclasses(child)) ) class ProgressBar: def __init__(self, prefix, pre_prefix="", total=None, unit=" rows"): self.prefix = prefix self.progress = tqdm( desc=pre_prefix, total=total, unit=unit, unit_scale=True, dynamic_ncols=True ) self.started = False def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() @property def description(self): return self.progress.desc @description.setter def description(self, value): self.progress.desc = value self.progress.refresh() @property def total(self): return self.progress.total @total.setter def total(self, value): self.progress.total = value self.progress.refresh() def update(self, last_done=1, total_done=None): if not last_done and not total_done: raise ValueError("Either last_done or total_done must be specified") if not self.started: self.started = True self.progress.desc = self.prefix self.progress.unpause() if last_done: self.progress.n += last_done else: self.progress.n = total_done self.progress.refresh() def close(self): self.progress.close() @dataclass class Source(object): "Define a source to import a `rows.Table`" uri: (str, Path) plugin_name: str encoding: str fobj: object = None compressed: bool = None should_delete: bool = False should_close: bool = False is_file: bool = None local: bool = None @classmethod def from_file( cls, filename_or_fobj, plugin_name=None, encoding=None, mode="rb", compressed=None, should_delete=False, should_close=None, is_file=True, local=True, ): """Create a `Source` from a filename or fobj""" if isinstance(filename_or_fobj, Source): return filename_or_fobj elif isinstance(filename_or_fobj, (six.binary_type, six.text_type, Path)): fobj = open_compressed(filename_or_fobj, mode=mode) filename = filename_or_fobj should_close = True if should_close is None else should_close else: # Don't know exactly what is, assume file-like object fobj = filename_or_fobj filename = getattr(fobj, "name", None) if not isinstance( filename, (six.binary_type, six.text_type) ): # BytesIO object filename = None should_close = False if should_close is None else should_close if is_file and local and filename and not isinstance(filename, Path): filename = Path(filename) return Source( compressed=compressed, encoding=encoding, fobj=fobj, is_file=is_file, local=local, plugin_name=plugin_name, should_close=should_close, should_delete=should_delete, uri=filename, ) def plugin_name_by_uri(uri): "Return the plugin name based on the URI" # TODO: parse URIs like 'sqlite://' also # TODO: integrate this function with detect_source parsed = urlparse(uri) if parsed.scheme: if parsed.scheme == "sqlite": return "sqlite" elif parsed.scheme == "postgres": return "postgresql" basename = os.path.basename(parsed.path) if not basename.strip(): raise RuntimeError("Could not identify file format.") extension = basename.split(".")[-1].lower() if extension in COMPRESSED_EXTENSIONS: extension = basename.split(".")[-2].lower() plugin_name = extension if extension in FILE_EXTENSIONS: plugin_name = MIME_TYPE_TO_PLUGIN_NAME[FILE_EXTENSIONS[plugin_name]] return plugin_name def extension_by_source(source, mime_type): "Return the file extension used by this plugin" # TODO: should get this information from the plugin extension = source.plugin_name if extension: return extension if mime_type: return mime_type.split("/")[-1] def normalize_mime_type(mime_type, mime_name, file_extension): file_extension = file_extension.lower() if file_extension else "" mime_name = mime_name.lower() if mime_name else "" mime_type = mime_type.lower() if mime_type else "" if mime_type == "text/plain" and file_extension in TEXT_PLAIN: return TEXT_PLAIN[file_extension] elif mime_type == "application/octet-stream" and mime_name in OCTET_STREAM: return OCTET_STREAM[mime_name] elif file_extension in FILE_EXTENSIONS: return FILE_EXTENSIONS[file_extension] else: return mime_type def plugin_name_by_mime_type(mime_type, mime_name, file_extension): "Return the plugin name based on the MIME type" return MIME_TYPE_TO_PLUGIN_NAME.get( normalize_mime_type(mime_type, mime_name, file_extension), None ) def detect_local_source(path, content, mime_type=None, encoding=None): # TODO: may add sample_size filename = os.path.basename(path) parts = filename.split(".") extension = parts[-1].lower() if len(parts) > 1 else None if extension in COMPRESSED_EXTENSIONS: extension = parts[-2].lower() if len(parts) > 2 else None if magic is not None: detected = magic.detect_from_content(content) encoding = detected.encoding or encoding mime_name = detected.name mime_type = detected.mime_type or mime_type else: if chardet and not encoding: encoding = chardet.detect(content)["encoding"] or encoding mime_name = None mime_type = mime_type or mimetypes.guess_type(filename)[0] plugin_name = plugin_name_by_mime_type(mime_type, mime_name, extension) if encoding == "binary": encoding = None return Source(uri=path, plugin_name=plugin_name, encoding=encoding) def local_file(path, sample_size=1048576): # TODO: may change sample_size if path.split(".")[-1].lower() in COMPRESSED_EXTENSIONS: compressed = True fobj = open_compressed(path, mode="rb") content = fobj.read(sample_size) fobj.close() else: compressed = False with open(path, "rb") as fobj: content = fobj.read(sample_size) source = detect_local_source(path, content, mime_type=None, encoding=None) return Source( uri=path, plugin_name=source.plugin_name, encoding=source.encoding, compressed=compressed, should_delete=False, is_file=True, local=True, ) def download_file( uri, filename=None, verify_ssl=True, timeout=5, progress=False, detect=False, chunk_size=8192, sample_size=1048576, retries=3, progress_pattern="Downloading file", ): # TODO: add ability to continue download session = requests.Session() retry_adapter = HTTPAdapter(max_retries=Retry(total=retries, backoff_factor=1)) session.mount("http://", retry_adapter) session.mount("https://", retry_adapter) response = session.get( uri, verify=verify_ssl, timeout=timeout, stream=True, headers={"user-agent": "rows-{}".format(rows.__version__)}, ) if not response.ok: raise RuntimeError("HTTP response: {}".format(response.status_code)) # Get data from headers (if available) to help plugin + encoding detection real_filename, encoding, mime_type = uri, None, None headers = response.headers if "content-type" in headers: mime_type, options = cgi.parse_header(headers["content-type"]) encoding = options.get("charset", encoding) if "content-disposition" in headers: _, options = cgi.parse_header(headers["content-disposition"]) real_filename = options.get("filename", real_filename) if filename is None: tmp = tempfile.NamedTemporaryFile(delete=False) fobj = open_compressed(tmp.name, mode="wb") else: fobj = open_compressed(filename, mode="wb") if progress: total = response.headers.get("content-length", None) total = int(total) if total else None progress_bar = ProgressBar( prefix=progress_pattern.format( uri=uri, filename=Path(fobj.name), mime_type=mime_type, encoding=encoding, ), total=total, unit="bytes", ) sample_data = b"" for data in response.iter_content(chunk_size=chunk_size): fobj.write(data) if detect and len(sample_data) <= sample_size: sample_data += data if progress: progress_bar.update(len(data)) fobj.close() if progress: progress_bar.close() # Detect file type and rename temporary file to have the correct extension if detect: # TODO: check if will work for compressed files source = detect_local_source(real_filename, sample_data, mime_type, encoding) extension = extension_by_source(source, mime_type) plugin_name = source.plugin_name encoding = source.encoding else: extension, plugin_name, encoding = None, None, None if mime_type: extension = mime_type.split("/")[-1] if filename is None: filename = tmp.name if extension: filename += "." + extension os.rename(tmp.name, filename) return Source( uri=filename, plugin_name=plugin_name, encoding=encoding, should_delete=True, is_file=True, local=False, ) def detect_source(uri, verify_ssl, progress, timeout=5): """Return a `rows.Source` with information for a given URI If URI starts with "http" or "https" the file will be downloaded. This function should only be used if the URI already exists because it's going to download/open the file to detect its encoding and MIME type. """ # TODO: should also supporte other schemes, like file://, sqlite:// etc. if uri.lower().startswith("http://") or uri.lower().startswith("https://"): return download_file( uri, verify_ssl=verify_ssl, timeout=timeout, progress=progress, detect=True ) elif uri.startswith("postgres://"): return Source( should_delete=False, encoding=None, plugin_name="postgresql", uri=uri, is_file=False, local=None, ) else: return local_file(uri) def import_from_source(source, default_encoding, *args, **kwargs): "Import data described in a `rows.Source` into a `rows.Table`" # TODO: test open_compressed plugin_name = source.plugin_name kwargs["encoding"] = ( kwargs.get("encoding", None) or source.encoding or default_encoding ) try: import_function = getattr(rows, "import_from_{}".format(plugin_name)) except AttributeError: raise ValueError('Plugin (import) "{}" not found'.format(plugin_name)) table = import_function(source.uri, *args, **kwargs) return table def import_from_uri( uri, default_encoding="utf-8", verify_ssl=True, progress=False, *args, **kwargs ): "Given an URI, detects plugin and encoding and imports into a `rows.Table`" # TODO: support '-' also # TODO: (optimization) if `kwargs.get('encoding', None) is not None` we can # skip encoding detection. source = detect_source(uri, verify_ssl=verify_ssl, progress=progress) return import_from_source(source, default_encoding, *args, **kwargs) def export_to_uri(table, uri, *args, **kwargs): "Given a `rows.Table` and an URI, detects plugin (from URI) and exports" # TODO: support '-' also plugin_name = plugin_name_by_uri(uri) try: export_function = getattr(rows, "export_to_{}".format(plugin_name)) except AttributeError: raise ValueError('Plugin (export) "{}" not found'.format(plugin_name)) return export_function(table, uri, *args, **kwargs) # TODO: check https://docs.python.org/3.7/library/fileinput.html def open_compressed( filename, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, ): """Return a text-based file object from a filename, even if compressed NOTE: if the file is compressed, options like `buffering` are valid to the compressed file-object (not the uncompressed file-object returned). """ binary_mode = "b" in mode if not binary_mode and "t" not in mode: # For some reason, passing only mode='r' to bzip2 is equivalent # to 'rb', not 'rt', so we force it here. mode += "t" if binary_mode and encoding: raise ValueError("encoding should not be specified in binary mode") extension = str(filename).split(".")[-1].lower() mode_binary = mode.replace("t", "b") get_fobj_binary = lambda: open( filename, mode=mode_binary, buffering=buffering, errors=errors, newline=newline, closefd=closefd, opener=opener, ) get_fobj_text = lambda: open( filename, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener, ) known_extensions = ("xz", "gz", "bz2") if extension not in known_extensions: # No compression if binary_mode: return get_fobj_binary() else: return get_fobj_text() elif extension == "xz": if lzma is None: raise ModuleNotFoundError("lzma support is not installed") fobj_binary = lzma.LZMAFile(get_fobj_binary(), mode=mode_binary) elif extension == "gz": fobj_binary = gzip.GzipFile(fileobj=get_fobj_binary(), mode=mode_binary) elif extension == "bz2": if bz2 is None: raise ModuleNotFoundError("bzip2 support is not installed") fobj_binary = bz2.BZ2File(get_fobj_binary(), mode=mode_binary) if binary_mode: return fobj_binary else: return io.TextIOWrapper(fobj_binary, encoding=encoding) def csv_to_sqlite( input_filename, output_filename, samples=None, dialect=None, batch_size=10000, encoding="utf-8", callback=None, force_types=None, chunk_size=8388608, table_name="table1", schema=None, ): "Export a CSV file to SQLite, based on field type detection from samples" # TODO: automatically detect encoding if encoding == `None` # TODO: should be able to specify fields # TODO: if schema is provided and the names are in uppercase, this function # will fail if dialect is None: # Get a sample to detect dialect fobj = open_compressed(input_filename, mode="rb") sample = fobj.read(chunk_size) fobj.close() dialect = rows.plugins.csv.discover_dialect(sample, encoding=encoding) elif isinstance(dialect, six.text_type): dialect = csv.get_dialect(dialect) if schema is None: # Identify data types fobj = open_compressed(input_filename, encoding=encoding) data = list(islice(csv.DictReader(fobj, dialect=dialect), samples)) fobj.close() schema = rows.import_from_dicts(data).fields if force_types is not None: schema.update(force_types) # Create lazy table object to be converted # TODO: this lazyness feature will be incorported into the library soon so # we can call here `rows.import_from_csv` instead of `csv.reader`. fobj = open_compressed(input_filename, encoding=encoding) csv_reader = csv.reader(fobj, dialect=dialect) header = make_header(next(csv_reader)) # skip header table = rows.Table(fields=OrderedDict([(field, schema[field]) for field in header])) table._rows = csv_reader # Export to SQLite result = rows.export_to_sqlite( table, output_filename, table_name=table_name, batch_size=batch_size, callback=callback, ) fobj.close() return result def sqlite_to_csv( input_filename, table_name, output_filename, dialect=csv.excel, batch_size=10000, encoding="utf-8", callback=None, query=None, ): """Export a table inside a SQLite database to CSV""" # TODO: should be able to specify fields # TODO: should be able to specify custom query if isinstance(dialect, six.text_type): dialect = csv.get_dialect(dialect) if query is None: query = "SELECT * FROM {}".format(table_name) connection = sqlite3.Connection(input_filename) cursor = connection.cursor() result = cursor.execute(query) header = [item[0] for item in cursor.description] fobj = open_compressed(output_filename, mode="w", encoding=encoding) writer = csv.writer(fobj, dialect=dialect) writer.writerow(header) total_written = 0 for batch in rows.plugins.utils.ipartition(result, batch_size): writer.writerows(batch) written = len(batch) total_written += written if callback: callback(written, total_written) fobj.close() class CsvLazyDictWriter: """Lazy CSV dict writer, with compressed output option This class is almost the same as `csv.DictWriter` with the following differences: - You don't need to pass `fieldnames` (it's extracted on the first `.writerow` call); - You can pass either a filename or a fobj (like `sys.stdout`); - If passing a filename, it can end with `.gz`, `.xz` or `.bz2` and the output file will be automatically compressed. """ def __init__(self, filename_or_fobj, encoding="utf-8", *args, **kwargs): self.writer = None self.filename_or_fobj = filename_or_fobj self.encoding = encoding self._fobj = None self.writer_args = args self.writer_kwargs = kwargs self.writer_kwargs["lineterminator"] = kwargs.get("lineterminator", "\n") # TODO: check if it should be the same in other OSes def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() @property def fobj(self): if self._fobj is None: if getattr(self.filename_or_fobj, "read", None) is not None: self._fobj = self.filename_or_fobj else: self._fobj = open_compressed( self.filename_or_fobj, mode="w", encoding=self.encoding ) return self._fobj def writerow(self, row): if self.writer is None: self.writer = csv.DictWriter( self.fobj, fieldnames=list(row.keys()), *self.writer_args, **self.writer_kwargs ) self.writer.writeheader() self.writerow = self.writer.writerow return self.writerow(row) def __del__(self): self.close() def close(self): if self._fobj and not self._fobj.closed: self._fobj.close() def execute_command(command): """Execute a command and return its output""" command = shlex.split(command) try: process = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) except FileNotFoundError: raise RuntimeError("Command not found: {}".format(repr(command))) process.wait() # TODO: may use another codec to decode if process.returncode > 0: stderr = process.stderr.read().decode("utf-8") raise ValueError("Error executing command: {}".format(repr(stderr))) data = process.stdout.read().decode("utf-8") process.stdin.close() process.stdout.close() process.stderr.close() process.wait() return data def uncompressed_size(filename): """Return the uncompressed size for a file by executing commands Note: due to a limitation in gzip format, uncompressed files greather than 4GiB will have a wrong value. """ quoted_filename = shlex.quote(filename) # TODO: get filetype from file-magic, if available if str(filename).lower().endswith(".xz"): output = execute_command('xz --list "{}"'.format(quoted_filename)) compressed, uncompressed = regexp_sizes.findall(output) value, unit = uncompressed.split() value = float(value.replace(",", "")) return int(value * MULTIPLIERS[unit]) elif str(filename).lower().endswith(".gz"): # XXX: gzip only uses 32 bits to store uncompressed size, so if the # uncompressed size is greater than 4GiB, the value returned will be # incorrect. output = execute_command('gzip --list "{}"'.format(quoted_filename)) lines = [line.split() for line in output.splitlines()] header, data = lines[0], lines[1] gzip_data = dict(zip(header, data)) return int(gzip_data["uncompressed"]) else: raise ValueError('Unrecognized file type for "{}".'.format(filename)) def generate_schema(table, export_fields, output_format): """Generate table schema for a specific output format and write Current supported output formats: 'txt', 'sql' and 'django'. The table name and all fields names pass for a slugifying process (table name is taken from file name). """ if output_format in ("csv", "txt"): from rows import plugins data = [ { "field_name": fieldname, "field_type": fieldtype.__name__.replace("Field", "").lower(), } for fieldname, fieldtype in table.fields.items() if fieldname in export_fields ] table = plugins.dicts.import_from_dicts( data, import_fields=["field_name", "field_type"] ) if output_format == "txt": return plugins.txt.export_to_txt(table) elif output_format == "csv": return plugins.csv.export_to_csv(table).decode("utf-8") elif output_format == "sql": # TODO: may use dict from rows.plugins.sqlite or postgresql sql_fields = { rows.fields.BinaryField: "BLOB", rows.fields.BoolField: "BOOL", rows.fields.IntegerField: "INT", rows.fields.FloatField: "FLOAT", rows.fields.PercentField: "FLOAT", rows.fields.DateField: "DATE", rows.fields.DatetimeField: "DATETIME", rows.fields.TextField: "TEXT", rows.fields.DecimalField: "FLOAT", rows.fields.EmailField: "TEXT", rows.fields.JSONField: "TEXT", } fields = [ " {} {}".format(field_name, sql_fields[field_type]) for field_name, field_type in table.fields.items() if field_name in export_fields ] sql = ( dedent( """ CREATE TABLE IF NOT EXISTS {name} ( {fields} ); """ ) .strip() .format(name=table.name, fields=",\n".join(fields)) + "\n" ) return sql elif output_format == "django": django_fields = { rows.fields.BinaryField: "BinaryField", rows.fields.BoolField: "BooleanField", rows.fields.IntegerField: "IntegerField", rows.fields.FloatField: "FloatField", rows.fields.PercentField: "DecimalField", rows.fields.DateField: "DateField", rows.fields.DatetimeField: "DateTimeField", rows.fields.TextField: "TextField", rows.fields.DecimalField: "DecimalField", rows.fields.EmailField: "EmailField", rows.fields.JSONField: "JSONField", } table_name = "".join(word.capitalize() for word in table.name.split("_")) lines = ["from django.db import models"] if rows.fields.JSONField in [ table.fields[field_name] for field_name in export_fields ]: lines.append("from django.contrib.postgres.fields import JSONField") lines.append("") lines.append("class {}(models.Model):".format(table_name)) for field_name, field_type in table.fields.items(): if field_name not in export_fields: continue if field_type is not rows.fields.JSONField: django_type = "models.{}()".format(django_fields[field_type]) else: django_type = "JSONField()" lines.append(" {} = {}".format(field_name, django_type)) result = "\n".join(lines) + "\n" return result def load_schema(filename, context=None): """Load schema from file in any of the supported formats The table must have at least the fields `field_name` and `field_type`. `context` is a `dict` with field_type as key pointing to field class, like: {"text": rows.fields.TextField, "value": MyCustomField} """ # TODO: load_schema must support Path objects table = import_from_uri(filename) field_names = table.field_names assert "field_name" in field_names assert "field_type" in field_names context = context or { key.replace("Field", "").lower(): getattr(rows.fields, key) for key in dir(rows.fields) if "Field" in key and key != "Field" } return OrderedDict([(row.field_name, context[row.field_type]) for row in table]) def scale_number(n, divider=1000, suffix=None, multipliers="KMGTPEZ", decimal_places=2): suffix = suffix if suffix is not None else "" count = -1 while n >= divider: n /= divider count += 1 multiplier = multipliers[count] if count > -1 else "" if not multiplier: return str(n) + suffix else: fmt_str = "{{n:.{}f}}{{multiplier}}{{suffix}}".format(decimal_places) return fmt_str.format(n=n, multiplier=multiplier, suffix=suffix) class NotNullWrapper(io.BufferedReader): """BufferedReader which removes NUL (`\x00`) from source stream""" def read(self, n): return super().read(n).replace(b"\x00", b"") def readline(self): return super().readline().replace(b"\x00", b"") # Shortcuts and legacy functions csv2sqlite = csv_to_sqlite sqlite2csv = sqlite_to_csv def pgimport(filename, *args, **kwargs): # TODO: add warning (will remove this function from here in the future) from rows.plugins.postgresql import pgimport as original_function return original_function(filename_or_fobj=filename, *args, **kwargs) def pgexport(*args, **kwargs): # TODO: add warning (will remove this function from here in the future) from rows.plugins.postgresql import pgexport as original_function return original_function(*args, **kwargs) def get_psql_command(*args, **kwargs): # TODO: add warning (will remove this function from here in the future) from rows.plugins.postgresql import get_psql_command as original_function return original_function(*args, **kwargs) def get_psql_copy_command(*args, **kwargs): # TODO: add warning (will remove this function from here in the future) from rows.plugins.postgresql import get_psql_copy_command as original_function return original_function(*args, **kwargs) def pg_create_table_sql(*args, **kwargs): # TODO: add warning (will remove this function from here in the future) from rows.plugins.postgresql import pg_create_table_sql as original_function return original_function(*args, **kwargs) def pg_execute_sql(*args, **kwargs): # TODO: add warning (will remove this function from here in the future) from rows.plugins.postgresql import pg_execute_sql as original_function return original_function(*args, **kwargs)
rows/utils/__init__.py
codereval_python_data_134
Convert a string to a number, using the given alphabet. The input is assumed to have the most significant digit first. def string_to_int(string: str, alphabet: List[str]) -> int: """ Convert a string to a number, using the given alphabet. The input is assumed to have the most significant digit first. """ number = 0 alpha_len = len(alphabet) for char in string: number = number * alpha_len + alphabet.index(char) return number """Concise UUID generation.""" import binascii import math import os import uuid as _uu from typing import List, Optional def int_to_string(number: int, alphabet: List[str], padding: Optional[int] = None) -> str: """ Convert a number to a string, using the given alphabet. The output has the most significant digit first. """ output = "" alpha_len = len(alphabet) while number: number, digit = divmod(number, alpha_len) output += alphabet[digit] if padding: remainder = max(padding - len(output), 0) output = output + alphabet[0] * remainder return output[::-1] def string_to_int(string: str, alphabet: List[str]) -> int: """ Convert a string to a number, using the given alphabet. The input is assumed to have the most significant digit first. """ number = 0 alpha_len = len(alphabet) for char in string: number = number * alpha_len + alphabet.index(char) return number class ShortUUID(object): def __init__(self, alphabet: Optional[List[str]] = None) -> None: if alphabet is None: alphabet = list( "23456789ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz" ) self.set_alphabet(alphabet) @property def _length(self) -> int: """Return the necessary length to fit the entire UUID given the current alphabet.""" return int(math.ceil(math.log(2 ** 128, self._alpha_len))) def encode(self, uuid: _uu.UUID, pad_length: Optional[int] = None) -> str: """ Encode a UUID into a string (LSB first) according to the alphabet. If leftmost (MSB) bits are 0, the string might be shorter. """ if not isinstance(uuid, _uu.UUID): raise ValueError("Input `uuid` must be a UUID object.") if pad_length is None: pad_length = self._length return int_to_string(uuid.int, self._alphabet, padding=pad_length) def decode(self, string: str, legacy: bool = False) -> _uu.UUID: """ Decode a string according to the current alphabet into a UUID. Raises ValueError when encountering illegal characters or a too-long string. If string too short, fills leftmost (MSB) bits with 0. Pass `legacy=True` if your UUID was encoded with a ShortUUID version prior to 1.0.0. """ if not isinstance(string, str): raise ValueError("Input `string` must be a str.") if legacy: string = string[::-1] return _uu.UUID(int=string_to_int(string, self._alphabet)) def uuid(self, name: Optional[str] = None, pad_length: Optional[int] = None) -> str: """ Generate and return a UUID. If the name parameter is provided, set the namespace to the provided name and generate a UUID. """ if pad_length is None: pad_length = self._length # If no name is given, generate a random UUID. if name is None: u = _uu.uuid4() elif name.lower().startswith(("http://", "https://")): u = _uu.uuid5(_uu.NAMESPACE_URL, name) else: u = _uu.uuid5(_uu.NAMESPACE_DNS, name) return self.encode(u, pad_length) def random(self, length: Optional[int] = None) -> str: """Generate and return a cryptographically secure short random string of `length`.""" if length is None: length = self._length random_num = int(binascii.b2a_hex(os.urandom(length)), 16) return int_to_string(random_num, self._alphabet, padding=length)[:length] def get_alphabet(self) -> str: """Return the current alphabet used for new UUIDs.""" return "".join(self._alphabet) def set_alphabet(self, alphabet: str) -> None: """Set the alphabet to be used for new UUIDs.""" # Turn the alphabet into a set and sort it to prevent duplicates # and ensure reproducibility. new_alphabet = list(sorted(set(alphabet))) if len(new_alphabet) > 1: self._alphabet = new_alphabet self._alpha_len = len(self._alphabet) else: raise ValueError("Alphabet with more than " "one unique symbols required.") def encoded_length(self, num_bytes: int = 16) -> int: """Return the string length of the shortened UUID.""" factor = math.log(256) / math.log(self._alpha_len) return int(math.ceil(factor * num_bytes)) # For backwards compatibility _global_instance = ShortUUID() encode = _global_instance.encode decode = _global_instance.decode uuid = _global_instance.uuid random = _global_instance.random get_alphabet = _global_instance.get_alphabet set_alphabet = _global_instance.set_alphabet
shortuuid/main.py
codereval_python_data_135
Given an url and a destination path, retrieve and extract .tar.gz archive which contains 'desc' file for each package. Each .tar.gz archive corresponds to an Arch Linux repo ('core', 'extra', 'community'). Args: url: url of the .tar.gz archive to download destination_path: the path on disk where to extract archive Returns: a directory Path where the archive has been extracted to. import requests def get_repo_archive(url: str, destination_path: Path) -> Path: """ Given an url and a destination path, retrieve and extract .tar.gz archive which contains 'desc' file for each package. Each .tar.gz archive corresponds to an Arch Linux repo ('core', 'extra', 'community'). Args: url: url of the .tar.gz archive to download destination_path: the path on disk where to extract archive Returns: a directory Path where the archive has been extracted to. """ res = requests.get(url) destination_path.parent.mkdir(parents=True, exist_ok=True) destination_path.write_bytes(res.content) extract_to = Path(str(destination_path).split(".tar.gz")[0]) tar = tarfile.open(destination_path) tar.extractall(path=extract_to) tar.close() return extract_to # Copyright (C) 2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import datetime import logging from pathlib import Path import re import tarfile from typing import Any, Dict, Iterator, List, Optional from urllib.parse import unquote, urljoin from bs4 import BeautifulSoup import requests from swh.model.hashutil import hash_to_hex from swh.scheduler.interface import SchedulerInterface from swh.scheduler.model import ListedOrigin from ..pattern import CredentialsType, StatelessLister logger = logging.getLogger(__name__) # Aliasing the page results returned by `get_pages` method from the lister. ArchListerPage = List[Dict[str, Any]] def size_to_bytes(size: str) -> int: """Convert human readable file size to bytes. Resulting value is an approximation as input value is in most case rounded. Args: size: A string representing a human readable file size (eg: '500K') Returns: A decimal representation of file size Examples:: >>> size_to_bytes("500") 500 >>> size_to_bytes("1K") 1000 """ units = { "K": 1000, "M": 1000**2, "G": 1000**3, "T": 1000**4, "P": 1000**5, "E": 1000**6, "Z": 1000**7, "Y": 1000**8, } if size.endswith(tuple(units)): v, u = (size[:-1], size[-1]) return int(v) * units[u] else: return int(size) class ArchLister(StatelessLister[ArchListerPage]): """List Arch linux origins from 'core', 'extra', and 'community' repositories For 'official' Arch Linux it downloads core.tar.gz, extra.tar.gz and community.tar.gz from https://archive.archlinux.org/repos/last/ extract to a temp directory and then walks through each 'desc' files. Each 'desc' file describe the latest released version of a package and helps to build an origin url from where scrapping artifacts metadata. For 'arm' Arch Linux it follow the same discovery process parsing 'desc' files. The main difference is that we can't get existing versions of an arm package because https://archlinuxarm.org does not have an 'archive' website or api. """ LISTER_NAME = "arch" VISIT_TYPE = "arch" INSTANCE = "arch" DESTINATION_PATH = Path("/tmp/archlinux_archive") ARCH_PACKAGE_URL_PATTERN = "{base_url}/packages/{repo}/{arch}/{pkgname}" ARCH_PACKAGE_VERSIONS_URL_PATTERN = "{base_url}/packages/{pkgname[0]}/{pkgname}" ARCH_PACKAGE_DOWNLOAD_URL_PATTERN = ( "{base_url}/packages/{pkgname[0]}/{pkgname}/{filename}" ) ARCH_API_URL_PATTERN = "{base_url}/packages/{repo}/{arch}/{pkgname}/json" ARM_PACKAGE_URL_PATTERN = "{base_url}/packages/{arch}/{pkgname}" ARM_PACKAGE_DOWNLOAD_URL_PATTERN = "{base_url}/{arch}/{repo}/{filename}" def __init__( self, scheduler: SchedulerInterface, credentials: Optional[CredentialsType] = None, flavours: Dict[str, Any] = { "official": { "archs": ["x86_64"], "repos": ["core", "extra", "community"], "base_info_url": "https://archlinux.org", "base_archive_url": "https://archive.archlinux.org", "base_mirror_url": "", "base_api_url": "https://archlinux.org", }, "arm": { "archs": ["armv7h", "aarch64"], "repos": ["core", "extra", "community"], "base_info_url": "https://archlinuxarm.org", "base_archive_url": "", "base_mirror_url": "https://uk.mirror.archlinuxarm.org", "base_api_url": "", }, }, ): super().__init__( scheduler=scheduler, credentials=credentials, url=flavours["official"]["base_info_url"], instance=self.INSTANCE, ) self.flavours = flavours def scrap_package_versions( self, name: str, repo: str, base_url: str ) -> List[Dict[str, Any]]: """Given a package 'name' and 'repo', make an http call to origin url and parse its content to get package versions artifacts data. That method is suitable only for 'official' Arch Linux, not 'arm'. Args: name: Package name repo: The repository the package belongs to (one of self.repos) Returns: A list of dict of version Example:: [ {"url": "https://archive.archlinux.org/packages/d/dialog/dialog-1:1.3_20190211-1-x86_64.pkg.tar.xz", # noqa: B950 "arch": "x86_64", "repo": "core", "name": "dialog", "version": "1:1.3_20190211-1", "length": 180000, "filename": "dialog-1:1.3_20190211-1-x86_64.pkg.tar.xz", "last_modified": "2019-02-13T08:36:00"}, ] """ url = self.ARCH_PACKAGE_VERSIONS_URL_PATTERN.format( pkgname=name, base_url=base_url ) soup = BeautifulSoup(requests.get(url).text, "html.parser") links = soup.find_all("a", href=True) # drop the first line (used to go to up directory) if links[0].attrs["href"] == "../": links.pop(0) versions = [] for link in links: # filename displayed can be cropped if name is too long, get it from href instead filename = unquote(link.attrs["href"]) if filename.endswith((".tar.xz", ".tar.zst")): # Extract arch from filename arch_rex = re.compile( rf"^{re.escape(name)}-(?P<version>.*)-(?P<arch>any|i686|x86_64)" rf"(.pkg.tar.(?:zst|xz))$" ) m = arch_rex.match(filename) if m is None: logger.error( "Can not find a match for architecture in %(filename)s" % dict(filename=filename) ) else: arch = m.group("arch") version = m.group("version") # Extract last_modified and an approximate file size raw_text = link.next_sibling raw_text_rex = re.compile( r"^(?P<last_modified>\d+-\w+-\d+ \d\d:\d\d)\s+(?P<size>\w+)$" ) s = raw_text_rex.search(raw_text.strip()) if s is None: logger.error( "Can not find a match for 'last_modified' and/or " "'size' in '%(raw_text)s'" % dict(raw_text=raw_text) ) else: assert s.groups() assert len(s.groups()) == 2 last_modified_str, size = s.groups() # format as expected last_modified = datetime.datetime.strptime( last_modified_str, "%d-%b-%Y %H:%M" ).isoformat() length = size_to_bytes(size) # we want bytes # link url is relative, format a canonical one url = self.ARCH_PACKAGE_DOWNLOAD_URL_PATTERN.format( base_url=base_url, pkgname=name, filename=filename ) versions.append( dict( name=name, version=version, repo=repo, arch=arch, filename=filename, url=url, last_modified=last_modified, length=length, ) ) return versions def get_repo_archive(self, url: str, destination_path: Path) -> Path: """Given an url and a destination path, retrieve and extract .tar.gz archive which contains 'desc' file for each package. Each .tar.gz archive corresponds to an Arch Linux repo ('core', 'extra', 'community'). Args: url: url of the .tar.gz archive to download destination_path: the path on disk where to extract archive Returns: a directory Path where the archive has been extracted to. """ res = requests.get(url) destination_path.parent.mkdir(parents=True, exist_ok=True) destination_path.write_bytes(res.content) extract_to = Path(str(destination_path).split(".tar.gz")[0]) tar = tarfile.open(destination_path) tar.extractall(path=extract_to) tar.close() return extract_to def parse_desc_file( self, path: Path, repo: str, base_url: str, dl_url_fmt: str, ) -> Dict[str, Any]: """Extract package information from a 'desc' file. There are subtle differences between parsing 'official' and 'arm' des files Args: path: A path to a 'desc' file on disk repo: The repo the package belongs to Returns: A dict of metadata Example:: {'api_url': 'https://archlinux.org/packages/core/x86_64/dialog/json', 'arch': 'x86_64', 'base': 'dialog', 'builddate': '1650081535', 'csize': '203028', 'desc': 'A tool to display dialog boxes from shell scripts', 'filename': 'dialog-1:1.3_20220414-1-x86_64.pkg.tar.zst', 'isize': '483988', 'license': 'LGPL2.1', 'md5sum': '06407c0cb11c50d7bf83d600f2e8107c', 'name': 'dialog', 'packager': 'Evangelos Foutras <foutrelis@archlinux.org>', 'pgpsig': 'pgpsig content xxx', 'project_url': 'https://invisible-island.net/dialog/', 'provides': 'libdialog.so=15-64', 'repo': 'core', 'sha256sum': 'ef8c8971f591de7db0f455970ef5d81d5aced1ddf139f963f16f6730b1851fa7', 'url': 'https://archive.archlinux.org/packages/.all/dialog-1:1.3_20220414-1-x86_64.pkg.tar.zst', # noqa: B950 'version': '1:1.3_20220414-1'} """ rex = re.compile(r"^\%(?P<k>\w+)\%\n(?P<v>.*)\n$", re.M) with path.open("rb") as content: parsed = rex.findall(content.read().decode()) data = {entry[0].lower(): entry[1] for entry in parsed} if "url" in data.keys(): data["project_url"] = data["url"] assert data["name"] assert data["filename"] assert data["arch"] data["repo"] = repo data["url"] = urljoin( base_url, dl_url_fmt.format( base_url=base_url, pkgname=data["name"], filename=data["filename"], arch=data["arch"], repo=repo, ), ) assert data["md5sum"] assert data["sha256sum"] data["checksums"] = { "md5sum": hash_to_hex(data["md5sum"]), "sha256sum": hash_to_hex(data["sha256sum"]), } return data def get_pages(self) -> Iterator[ArchListerPage]: """Yield an iterator sorted by name in ascending order of pages. Each page is a list of package belonging to a flavour ('official', 'arm'), and a repo ('core', 'extra', 'community') """ for name, flavour in self.flavours.items(): for arch in flavour["archs"]: for repo in flavour["repos"]: page = [] if name == "official": prefix = urljoin(flavour["base_archive_url"], "/repos/last/") filename = f"{repo}.files.tar.gz" archive_url = urljoin(prefix, f"{repo}/os/{arch}/{filename}") destination_path = Path(self.DESTINATION_PATH, arch, filename) base_url = flavour["base_archive_url"] dl_url_fmt = self.ARCH_PACKAGE_DOWNLOAD_URL_PATTERN base_info_url = flavour["base_info_url"] info_url_fmt = self.ARCH_PACKAGE_URL_PATTERN elif name == "arm": filename = f"{repo}.files.tar.gz" archive_url = urljoin( flavour["base_mirror_url"], f"{arch}/{repo}/{filename}" ) destination_path = Path(self.DESTINATION_PATH, arch, filename) base_url = flavour["base_mirror_url"] dl_url_fmt = self.ARM_PACKAGE_DOWNLOAD_URL_PATTERN base_info_url = flavour["base_info_url"] info_url_fmt = self.ARM_PACKAGE_URL_PATTERN archive = self.get_repo_archive( url=archive_url, destination_path=destination_path ) assert archive packages_desc = list(archive.glob("**/desc")) logger.debug( "Processing %(instance)s source packages info from " "%(flavour)s %(arch)s %(repo)s repository, " "(%(qty)s packages)." % dict( instance=self.instance, flavour=name, arch=arch, repo=repo, qty=len(packages_desc), ) ) for package_desc in packages_desc: data = self.parse_desc_file( path=package_desc, repo=repo, base_url=base_url, dl_url_fmt=dl_url_fmt, ) assert data["builddate"] last_modified = datetime.datetime.fromtimestamp( float(data["builddate"]), tz=datetime.timezone.utc ) assert data["name"] assert data["filename"] assert data["arch"] url = info_url_fmt.format( base_url=base_info_url, pkgname=data["name"], filename=data["filename"], repo=repo, arch=data["arch"], ) assert data["version"] if name == "official": # find all versions of a package scrapping archive versions = self.scrap_package_versions( name=data["name"], repo=repo, base_url=base_url, ) elif name == "arm": # There is no way to get related versions of a package, # but 'data' represents the latest released version, # use it in this case assert data["builddate"] assert data["csize"] assert data["url"] versions = [ dict( name=data["name"], version=data["version"], repo=repo, arch=data["arch"], filename=data["filename"], url=data["url"], last_modified=last_modified.replace( tzinfo=None ).isoformat(timespec="seconds"), length=int(data["csize"]), ) ] package = { "name": data["name"], "version": data["version"], "last_modified": last_modified, "url": url, "versions": versions, "data": data, } page.append(package) yield page def get_origins_from_page(self, page: ArchListerPage) -> Iterator[ListedOrigin]: """Iterate on all arch pages and yield ListedOrigin instances.""" assert self.lister_obj.id is not None for origin in page: yield ListedOrigin( lister_id=self.lister_obj.id, visit_type=self.VISIT_TYPE, url=origin["url"], last_update=origin["last_modified"], extra_loader_arguments={ "artifacts": origin["versions"], }, )
swh/lister/arch/lister.py
codereval_python_data_136
Checks if the os is macOS :return: True is macOS :rtype: bool import os def os_is_mac(): """ Checks if the os is macOS :return: True is macOS :rtype: bool """ return platform.system() == "Darwin" import platform import sys import os from pathlib import Path from cloudmesh.common.util import readfile from collections import OrderedDict import pip import psutil import humanize import re import multiprocessing def os_is_windows(): """ Checks if the os is windows :return: True is windows :rtype: bool """ return platform.system() == "Windows" # noinspection PyBroadException def os_is_linux(): """ Checks if the os is linux :return: True is linux :rtype: bool """ try: content = readfile('/etc/os-release') return platform.system() == "Linux" and "raspbian" not in content except: # noqa: E722 return False def os_is_mac(): """ Checks if the os is macOS :return: True is macOS :rtype: bool """ return platform.system() == "Darwin" # noinspection PyBroadException def os_is_pi(): """ Checks if the os is Raspberry OS :return: True is Raspberry OS :rtype: bool """ try: content = readfile('/etc/os-release') return platform.system() == "Linux" and "raspbian" in content except: # noqa: E722 return False def sys_user(): if "COLAB_GPU" in os.environ: return "collab" try: if sys.platform == "win32": return os.environ["USERNAME"] except: pass try: return os.environ["USER"] except: pass try: if os.environ["HOME"] == "/root": return "root" except: pass return "None" def get_platform(): if sys.platform == "darwin": return "macos" elif sys.platform == "win32": return "windows" try: content = readfile('/etc/os-release') if sys.platform == 'linux' and "raspbian" in content: return "raspberry" else: return sys.platform except: return sys.platform def systeminfo(info=None, user=None, node=None): uname = platform.uname() mem = psutil.virtual_memory() # noinspection PyPep8 def add_binary(value): try: r = humanize.naturalsize(value, binary=True) except: r = "" return r try: frequency = psutil.cpu_freq() except: frequency = None try: cores = psutil.cpu_count(logical=False) except: cores = "unkown" operating_system = get_platform() description = "" try: if operating_system == "macos": description = os.popen("sysctl -n machdep.cpu.brand_string").read() elif operating_system == "win32": description = platform.processor() elif operating_system == "linux": lines = readfile("/proc/cpuinfo").strip().splitlines() for line in lines: if "model name" in line: description = re.sub(".*model name.*:", "", line, 1) except: pass data = OrderedDict({ 'cpu': description.strip(), 'cpu_count': multiprocessing.cpu_count(), 'cpu_threads': multiprocessing.cpu_count(), 'cpu_cores': cores, 'uname.system': uname.system, 'uname.node': uname.node, 'uname.release': uname.release, 'uname.version': uname.version, 'uname.machine': uname.machine, 'uname.processor': uname.processor, 'sys.platform': sys.platform, 'python': sys.version, 'python.version': sys.version.split(" ", 1)[0], 'python.pip': pip.__version__, 'user': sys_user(), 'mem.percent': str(mem.percent) + " %", 'frequency': frequency }) for attribute in ["total", "available", "used", "free", "active", "inactive", "wired" ]: try: data[f"mem.{attribute}"] = \ humanize.naturalsize(getattr(mem, attribute), binary=True) except: pass # svmem(total=17179869184, available=6552825856, percent=61.9, if data['sys.platform'] == 'darwin': data['platform.version'] = platform.mac_ver()[0] elif data['sys.platform'] == 'win32': data['platform.version'] = platform.win32_ver() else: data['platform.version'] = uname.version try: release_files = Path("/etc").glob("*release") for filename in release_files: content = readfile(filename.resolve()).splitlines() for line in content: if "=" in line: attribute, value = line.split("=", 1) attribute = attribute.replace(" ", "") data[attribute] = value except: pass if info is not None: data.update(info) if user is not None: data["user"] = user if node is not None: data["uname.node"] = node return dict(data)
cloudmesh/common/systeminfo.py
codereval_python_data_137
Convert *.cpp keys to regex keys Given a dict where the keys are all filenames with wildcards, convert only the keys into equivalent regexes and leave the values intact. Example: rules = { '*.cpp': {'a': 'arf', 'b': 'bark', 'c': 'coo'}, '*.h': {'h': 'help'} } regex_keys = regex_dict(rules) Args: item: dict to convert Returns: dict with keys converted to regexes import re def regex_dict(item): """ Convert *.cpp keys to regex keys Given a dict where the keys are all filenames with wildcards, convert only the keys into equivalent regexes and leave the values intact. Example: rules = { '*.cpp': {'a': 'arf', 'b': 'bark', 'c': 'coo'}, '*.h': {'h': 'help'} } regex_keys = regex_dict(rules) Args: item: dict to convert Returns: dict with keys converted to regexes """ output = {} for key in item: output[re.compile(fnmatch.translate(key)).match] = item[key] return output #!/usr/bin/env python # -*- coding: utf-8 -*- """ The util module contains subroutines used everywhere. @package makeprojects.util """ from __future__ import absolute_import, print_function, unicode_literals import os import re import fnmatch from burger import string_to_bool, is_string, import_py_script from .enums import FileTypes # pylint: disable=consider-using-f-string ######################################## def validate_enum_type(value, data_type): """ Verify a value is a specific data type. Check if the value is either None or an instance of a specfic data type. If so, return immediately. If the value is a string, call the lookup() function of the data type for conversion. Args: value: Value to check. data_type: Type instance of the class type to match. Returns: Value converted to data_type or None. Raises: TypeError """ if value is not None: # Perform the lookup new_value = data_type.lookup(value) if new_value is None: msg = '"{}" must be of type "{}".'.format( value, data_type.__name__) raise TypeError(msg) # Save the converted type value = new_value return value ######################################## def regex_dict(item): """ Convert *.cpp keys to regex keys Given a dict where the keys are all filenames with wildcards, convert only the keys into equivalent regexes and leave the values intact. Example: rules = { '*.cpp': {'a': 'arf', 'b': 'bark', 'c': 'coo'}, '*.h': {'h': 'help'} } regex_keys = regex_dict(rules) Args: item: dict to convert Returns: dict with keys converted to regexes """ output = {} for key in item: output[re.compile(fnmatch.translate(key)).match] = item[key] return output ######################################## def validate_boolean(value): """ Verify a value is a boolean. Check if the value can be converted to a bool, if so, return the value as bool. None is converted to False. Args: value: Value to check. Returns: Value converted to data_type or None. Raises: ValueError """ if value is not None: # Convert to bool value = string_to_bool(value) return value ######################################## def validate_string(value): """ Verify a value is a string. Check if the value is a string, if so, return the value as is or None. Args: value: Value to check. Returns: Value is string or None. Raises: ValueError """ if value is not None: # Convert to bool if not is_string(value): raise ValueError('"{}" must be a string.'.format(value)) return value ######################################## def source_file_filter(file_list, file_type_list): """ Prune the file list for a specific type. Note: file_type_list can either be a single enums.FileTypes enum or an iterable list of enums.FileTypes Args: file_list: list of core.SourceFile entries. file_type_list: enums.FileTypes to match. Returns: list of matching core.SourceFile entries. """ result_list = [] # If a single item was passed, use a simple loop if isinstance(file_type_list, FileTypes): for item in file_list: if item.type is file_type_list: result_list.append(item) else: # A list was passed, so test against the list for item in file_list: if item.type in file_type_list: result_list.append(item) return result_list ######################################## def add_build_rules(build_rules_list, file_name, verbose, is_root, basename): """ Load in the file ``build_rules.py`` Load the build_rules.py file. If the variable ``*_GENERIC`` is ``True`` or if ``is_root`` is ``True``, append the module to ``build_rules_list``. If the variable ``*_CONTINUE`` was found in the file, check if it is set to ``True``. If so, return ``True`` to allow processing to continue. If the file is not found, return ``True`` to allow processing the parent folder. Since this is called from ``buildme``, ``cleanme``, and ``makeprojects``, the prefix needed for the tool is passed in ``basename``. An example is "CLEANME". Args: build_rules_list: List to add ``build_rules.py`` instances. file_name: Full path name of the build_rules.py to load. verbose: True for verbose output. is_root: True if *_GENERIC is ignored. basename: Variable prefix to substitute * in *_GENERIC Returns: True if the parent folder should be checked, False if not. """ # Ensure the absolute path is used. file_name = os.path.abspath(file_name) build_rules = import_py_script(file_name) # Not found? Continue parsing folders. if not build_rules: return True if is_root or getattr(build_rules, basename + "_GENERIC", False): # Add to the list build_rules_list.append(build_rules) if verbose: print('Using configuration file {}'.format(file_name)) # Test if this is considered the last one in the chain. return getattr(build_rules, basename + "_CONTINUE", False)
makeprojects/util.py
codereval_python_data_138
Remove quote from the given name. import re def unquote(name): """Remove quote from the given name.""" assert isinstance(name, bytes) # This function just gives back the original text if it can decode it def unquoted_char(match): """For each ;000 return the corresponding byte.""" if len(match.group()) != 4: return match.group try: return bytes([int(match.group()[1:])]) except ValueError: return match.group # Remove quote using regex return re.sub(b";[0-9]{3}", unquoted_char, name, re.S) # -*- coding: utf-8 -*- # rdiffweb, A web interface to rdiff-backup repositories # Copyright (C) 2012-2021 rdiffweb contributors # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import bisect import calendar import encodings import logging import os import re import shutil import subprocess import sys import threading import time from datetime import timedelta from distutils import spawn from subprocess import CalledProcessError import psutil from cached_property import cached_property from rdiffweb.tools.i18n import ugettext as _ # Define the logger logger = logging.getLogger(__name__) # Constant for the rdiff-backup-data folder name. RDIFF_BACKUP_DATA = b"rdiff-backup-data" # Increment folder name. INCREMENTS = b"increments" # Define the default LANG environment variable to be passed to rdiff-backup # restore command line to make sure the binary output stdout as utf8 otherwise # we end up with \x encoded characters. STDOUT_ENCODING = 'utf-8' LANG = "en_US." + STDOUT_ENCODING # PATH for executable lookup PATH = path = os.path.dirname(sys.executable) + os.pathsep + os.environ['PATH'] def rdiff_backup_version(): """ Get rdiff-backup version """ try: output = subprocess.check_output([find_rdiff_backup(), '--version']) m = re.search(b'([0-9]+).([0-9]+).([0-9]+)', output) return (int(m.group(1)), int(m.group(2)), int(m.group(3))) except Exception: return (0, 0, 0) def find_rdiff_backup(): """ Lookup for `rdiff-backup` executable. Raise an exception if not found. """ cmd = spawn.find_executable('rdiff-backup', PATH) if not cmd: raise FileNotFoundError("can't find `rdiff-backup` executable in PATH: %s" % PATH) return os.fsencode(cmd) def find_rdiff_backup_delete(): """ Lookup for `rdiff-backup-delete` executable. Raise an exception if not found. """ cmd = spawn.find_executable('rdiff-backup-delete', PATH) if not cmd: raise FileNotFoundError( "can't find `rdiff-backup-delete` executable in PATH: %s, make sure you have rdiff-backup >= 2.0.1 installed" % PATH ) return os.fsencode(cmd) def unquote(name): """Remove quote from the given name.""" assert isinstance(name, bytes) # This function just gives back the original text if it can decode it def unquoted_char(match): """For each ;000 return the corresponding byte.""" if len(match.group()) != 4: return match.group try: return bytes([int(match.group()[1:])]) except ValueError: return match.group # Remove quote using regex return re.sub(b";[0-9]{3}", unquoted_char, name, re.S) def popen(cmd, stderr=None, env=None): """ Alternative to os.popen() to support a `cmd` with a list of arguments and return a file object that return bytes instead of string. `stderr` could be subprocess.STDOUT or subprocess.DEVNULL or a function. Otherwise, the error is redirect to logger. """ # Check if stderr should be pipe. pipe_stderr = stderr == subprocess.PIPE or hasattr(stderr, '__call__') or stderr is None proc = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE if pipe_stderr else stderr, env=env, ) if pipe_stderr: t = threading.Thread(target=_readerthread, args=(proc.stderr, stderr)) t.daemon = True t.start() return _wrap_close(proc.stdout, proc) # Helper for popen() to redirect stderr to a logger. def _readerthread(stream, func): """ Read stderr and pipe each line to logger. """ func = func or logger.debug for line in stream: func(line.decode(STDOUT_ENCODING, 'replace').strip('\n')) stream.close() # Helper for popen() to close process when the pipe is closed. class _wrap_close: def __init__(self, stream, proc): self._stream = stream self._proc = proc def close(self): self._stream.close() returncode = self._proc.wait() if returncode == 0: return None return returncode def __enter__(self): return self def __exit__(self, *args): self.close() def __getattr__(self, name): return getattr(self._stream, name) def __iter__(self): return iter(self._stream) class AccessDeniedError(Exception): pass class DoesNotExistError(Exception): pass class RdiffTime(object): """Time information has two components: the local time, stored in GMT as seconds since Epoch, and the timezone, stored as a seconds offset. Since the server may not be in the same timezone as the user, we cannot rely on the built-in localtime() functions, but look at the rdiff-backup string for timezone information. As a general rule, we always display the "local" time, but pass the timezone information on to rdiff-backup, so it can restore to the correct state""" def __init__(self, value=None, tz_offset=None): assert value is None or isinstance(value, int) or isinstance(value, str) if value is None: # Get GMT time. self._time_seconds = int(time.time()) self._tz_offset = 0 elif isinstance(value, int): self._time_seconds = value self._tz_offset = tz_offset or 0 else: self._from_str(value) def _from_str(self, time_string): try: date, daytime = time_string[:19].split("T") year, month, day = list(map(int, date.split("-"))) hour, minute, second = list(map(int, daytime.split(":"))) assert 1900 < year < 2100, year assert 1 <= month <= 12 assert 1 <= day <= 31 assert 0 <= hour <= 23 assert 0 <= minute <= 59 assert 0 <= second <= 61 # leap seconds timetuple = (year, month, day, hour, minute, second, -1, -1, 0) self._time_seconds = calendar.timegm(timetuple) self._tz_offset = self._tzdtoseconds(time_string[19:]) self._tz_str() # to get assertions there except (TypeError, ValueError, AssertionError): raise ValueError(time_string) def epoch(self): return self._time_seconds - self._tz_offset def _tz_str(self): if self._tz_offset: hours, minutes = divmod(abs(self._tz_offset) // 60, 60) assert 0 <= hours <= 23 assert 0 <= minutes <= 59 if self._tz_offset > 0: plus_minus = "+" else: plus_minus = "-" return "%s%s:%s" % (plus_minus, "%02d" % hours, "%02d" % minutes) else: return "Z" def set_time(self, hour, minute, second): year = time.gmtime(self._time_seconds)[0] month = time.gmtime(self._time_seconds)[1] day = time.gmtime(self._time_seconds)[2] _time_seconds = calendar.timegm((year, month, day, hour, minute, second, -1, -1, 0)) return RdiffTime(_time_seconds, self._tz_offset) def _tzdtoseconds(self, tzd): """Given w3 compliant TZD, converts it to number of seconds from UTC""" if tzd == "Z": return 0 assert len(tzd) == 6 # only accept forms like +08:00 for now assert (tzd[0] == "-" or tzd[0] == "+") and tzd[3] == ":" if tzd[0] == "+": plus_minus = 1 else: plus_minus = -1 return plus_minus * 60 * (60 * int(tzd[1:3]) + int(tzd[4:])) def __add__(self, other): """Support plus (+) timedelta""" assert isinstance(other, timedelta) return RdiffTime(self._time_seconds + int(other.total_seconds()), self._tz_offset) def __sub__(self, other): """Support minus (-) timedelta""" assert isinstance(other, timedelta) or isinstance(other, RdiffTime) # Sub with timedelta, return RdiffTime if isinstance(other, timedelta): return RdiffTime(self._time_seconds - int(other.total_seconds()), self._tz_offset) # Sub with RdiffTime, return timedelta if isinstance(other, RdiffTime): return timedelta(seconds=self._time_seconds - other._time_seconds) def __int__(self): """Return this date as seconds since epoch.""" return self.epoch() def __lt__(self, other): assert isinstance(other, RdiffTime) return self.epoch() < other.epoch() def __le__(self, other): assert isinstance(other, RdiffTime) return self.epoch() <= other.epoch() def __gt__(self, other): assert isinstance(other, RdiffTime) return self.epoch() > other.epoch() def __ge__(self, other): assert isinstance(other, RdiffTime) return self.epoch() >= other.epoch() def __eq__(self, other): return isinstance(other, RdiffTime) and self.epoch() == other.epoch() def __hash__(self): return hash(self.epoch()) def __str__(self): """return utf-8 string""" value = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(self._time_seconds)) return value + self._tz_str() def __repr__(self): """return second since epoch""" return "RdiffTime('" + str(self) + "')" class RdiffDirEntry(object): """ Includes name, isdir, file_size, exists, and dict (change_dates) of sorted local dates when backed up. """ def __init__(self, repo, path, exists, increments): assert isinstance(repo, RdiffRepo) assert isinstance(path, bytes) # Keep reference to the path and repo object. self._repo = repo self.path = path # Absolute path to the directory if self.isroot: self.full_path = self._repo.full_path else: self.full_path = os.path.join(self._repo.full_path, self.path) # May need to compute our own state if not provided. self.exists = exists # Store the increments sorted by date. # See self.last_change_date() self._increments = sorted(increments, key=lambda x: x.date) @property def display_name(self): """Return the most human readable filename. Without quote.""" return self._repo.get_display_name(self.path) @property def isroot(self): """ Check if the directory entry represent the root of the repository. Return True when path is empty. """ return self.path == b'' @cached_property def isdir(self): """Lazy check if entry is a directory""" if self.exists: # If the entry exists, check if it's a directory return os.path.isdir(self.full_path) # Check if increments is a directory for increment in self._increments: if increment.is_missing: # Ignore missing increment... continue return increment.isdir @cached_property def file_size(self): """Return the file size in bytes.""" if self.isdir: return 0 elif self.exists: try: return os.lstat(self.full_path).st_size except Exception: logger.warning("cannot lstat on file [%s]", self.full_path, exc_info=1) else: # The only viable place to get the filesize of a deleted entry # it to get it from file_statistics try: stats = self._repo.file_statistics[self.last_change_date] # File stats uses unquoted name. unquote_path = unquote(self.path) return stats.get_source_size(unquote_path) except Exception: logger.warning("cannot find file statistic [%s]", self.last_change_date, exc_info=1) return 0 @cached_property def change_dates(self): """ Return a list of dates when this item has changes. Represent the previous revision. From old to new. """ # Exception for root path, use backups dates. if self.isroot: return self._repo.backup_dates # Compute the dates change_dates = set() for increment in self._increments: # Get date of the increment as reference change_date = increment.date # If the increment is a "missing" increment, need to get the date # before the folder was removed. if increment.is_missing: change_date = self._get_previous_backup_date(change_date) if change_date: change_dates.add(change_date) # If the directory exists, add the last known backup date. if self.exists and self._repo.last_backup_date: change_dates.add(self._repo.last_backup_date) # Return the list of dates. return sorted(change_dates) def _get_previous_backup_date(self, date): """Return the previous backup date.""" index = bisect.bisect_left(self._repo.backup_dates, date) if index == 0: return None return self._repo.backup_dates[index - 1] @cached_property def last_change_date(self): """Return last change date or False.""" return self.change_dates and self.change_dates[-1] class AbstractEntry: SUFFIXES = None @classmethod def _extract_date(cls, filename, onerror=None): """ Extract date from rdiff-backup filenames. """ # Extract suffix suffix = None for s in cls.SUFFIXES: if filename.endswith(s): suffix = s break if not suffix: raise ValueError(filename) # Parse date filename_without_suffix = filename[: -len(suffix)] parts = filename_without_suffix.rsplit(b'.', 1) if len(parts) != 2: return onerror(ValueError('')) date_string = unquote(parts[1]).decode('ascii') try: return RdiffTime(date_string) except Exception as e: if onerror is None: raise return onerror(e) class MetadataEntry(AbstractEntry): PREFIX = None SUFFIXES = None on_date_error = None def __init__(self, repo, name): assert isinstance(repo, RdiffRepo) assert isinstance(name, bytes) assert name.startswith(self.PREFIX) assert any(name.endswith(s) for s in self.SUFFIXES), 'name %s should ends with: %s' % (name, self.SUFFIXES) self.repo = repo self.name = name self.path = os.path.join(self.repo._data_path, self.name) self.date = self._extract_date(name, onerror=self.on_date_error) def _open(self): """ Should be used to open the increment file. This method handle compressed vs not-compressed file. """ if self._is_compressed: return popen(['zcat', self.path]) return open(self.path, 'rb') @property def _is_compressed(self): return self.name.endswith(b".gz") class MirrorMetadataEntry(MetadataEntry): PREFIX = b'mirror_metadata.' SUFFIXES = [ b'.diff', b'.diff.gz', b".snapshot.gz", b".snapshot", ] class IncrementEntry(AbstractEntry): """Instance of the class represent one increment at a specific date for one repository. The base repository is provided in the default constructor and the date is provided using an error_log.* file""" SUFFIXES = [ b".missing", b".snapshot.gz", b".snapshot", b".diff", b".diff.gz", b".dir", ] def __init__(self, name): """Default constructor for an increment entry. User must provide the repository directory and an entry name. The entry name correspond to an error_log.* filename.""" self.name, self.date, self.suffix = IncrementEntry._split(name) @property def isdir(self): return self.suffix == b".dir" @property def is_missing(self): """Check if the curent entry is a missing increment.""" return self.suffix == b".missing" @property def is_snapshot(self): """Check if the current entry is a snapshot increment.""" return self.suffix in [b".snapshot.gz", b".snapshot"] @classmethod def _split(cls, filename): """Return tuple with filename, date, suffix""" assert isinstance(filename, bytes) # Extract suffix suffix = None for s in cls.SUFFIXES: if filename.endswith(s): suffix = s break if not suffix: raise ValueError(filename) # Parse date and raise error on failure filename_without_suffix = filename[: -len(suffix)] name, date_string = filename_without_suffix.rsplit(b'.', 1) date_string = unquote(date_string).decode('ascii') date = RdiffTime(date_string) return (name, date, suffix) def __gt__(self, other): return self.date.__gt__(other.date) def __lt__(self, other): return self.date.__lt__(other.date) class FileStatisticsEntry(MetadataEntry): """ Represent a single file_statistics. File Statistics contains different information related to each file of the backup. This class provide a simple and easy way to access this data. """ PREFIX = b'file_statistics.' SUFFIXES = [b'.data', b'.data.gz'] def get_mirror_size(self, path): """Return the value of MirrorSize for the given file. path is the relative path from repo root.""" try: return int(self._search(path)["mirror_size"]) except ValueError: logger.warning("mirror size not found for [%r]", path, exc_info=1) return 0 def get_source_size(self, path): """Return the value of SourceSize for the given file. path is the relative path from repo root.""" try: return int(self._search(path)["source_size"]) except ValueError: logger.warning("source size not found for [%r]", path, exc_info=1) return 0 def _search(self, path): """ This function search for a file entry in the file_statistics compress file. Since python gzip.open() seams to be 2 time slower, we directly use zlib library on python2. """ logger.debug("read file_statistics [%r]", self.name) path += b' ' with self._open() as f: for line in f: if not line.startswith(path): continue break # Split the line into array data = line.rstrip(b'\r\n').rsplit(b' ', 4) # From array create an entry return {'changed': data[1], 'source_size': data[2], 'mirror_size': data[3], 'increment_size': data[4]} class SessionStatisticsEntry(MetadataEntry): """Represent a single session_statistics.""" PREFIX = b'session_statistics.' SUFFIXES = [b'.data', b'.data.gz'] ATTRS = [ 'starttime', 'endtime', 'elapsedtime', 'sourcefiles', 'sourcefilesize', 'mirrorfiles', 'mirrorfilesize', 'newfiles', 'newfilesize', 'deletedfiles', 'deletedfilesize', 'changedfiles', 'changedsourcesize', 'changedmirrorsize', 'incrementfiles', 'incrementfilesize', 'totaldestinationsizechange', 'errors', ] def _load(self): """This method is used to read the session_statistics and create the appropriate structure to quickly get the data. File Statistics contains different information related to each file of the backup. This class provide a simple and easy way to access this data.""" with self._open() as f: for line in f.readlines(): # Read the line into array line = line.rstrip(b'\r\n') data_line = line.split(b" ", 2) # Read line into tuple (key, value) = tuple(data_line)[0:2] if b'.' in value: value = float(value) else: value = int(value) setattr(self, key.lower().decode('ascii'), value) def __getattr__(self, name): """ Intercept attribute getter to load the file. """ if name in self.ATTRS: self._load() return self.__dict__[name] class CurrentMirrorEntry(MetadataEntry): PID_RE = re.compile(b"^PID\\s*([0-9]+)", re.I | re.M) PREFIX = b'current_mirror.' SUFFIXES = [b'.data'] def extract_pid(self): """ Return process ID from a current mirror marker, if any """ with open(self.path, 'rb') as f: match = self.PID_RE.search(f.read()) if not match: return None return int(match.group(1)) class LogEntry(MetadataEntry): PREFIX = b'error_log.' SUFFIXES = [b'.data', b'.data.gz'] @cached_property def is_empty(self): """ Check if the increment entry is empty. """ return os.path.getsize(self.path) == 0 def read(self): """Read the error file and return it's content. Raise exception if the file can't be read.""" # To avoid opening empty file, check the file size first. if self.is_empty: return "" encoding = self.repo._encoding.name if self._is_compressed: return subprocess.check_output( ['zcat', self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=encoding, errors='replace', ) with open(self.path, 'r', encoding=encoding, errors='replace') as f: return f.read() def tail(self, num=2000): """ Tail content of the file. This is used for logs. """ # To avoid opening empty file, check the file size first. if self.is_empty: return b'' encoding = self.repo._encoding.name if self._is_compressed: zcat = subprocess.Popen([b'zcat', self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return subprocess.check_output( ['tail', '-n', str(num)], stdin=zcat.stdout, stderr=subprocess.STDOUT, encoding=encoding, errors='replace', ) return subprocess.check_output( ['tail', '-n', str(num), self.path], stderr=subprocess.STDOUT, encoding=encoding, errors='replace' ) class RestoreLogEntry(LogEntry): PREFIX = b'restore.' SUFFIXES = [b'.log'] @staticmethod def on_date_error(e): return None class BackupLogEntry(LogEntry): PREFIX = b'backup.' SUFFIXES = [b'.log'] @staticmethod def on_date_error(e): return None class MetadataKeys: """ Provide a view on metadata dict keys. See MetadataDict#keys() """ def __init__(self, function, sequence): self._f = function self._sequence = sequence def __iter__(self): return map(self._f, self._sequence) def __getitem__(self, i): if isinstance(i, slice): return list(map(self._f, self._sequence[i])) else: return self._f(self._sequence[i]) def __len__(self): return len(self._sequence) class MetadataDict(object): """ This is used to access repository metadata quickly in a pythonic way. It make an abstraction to access a range of increment entries using index and date while also supporting slice to get a range of entries. """ def __init__(self, repo, cls): assert isinstance(repo, RdiffRepo) assert hasattr(cls, '__call__') self._repo = repo assert cls.PREFIX self._prefix = cls.PREFIX self._cls = cls @cached_property def _entries(self): return [e for e in self._repo._entries if e.startswith(self._prefix)] def __getitem__(self, key): if isinstance(key, RdiffTime): idx = bisect.bisect_left(self.keys(), key) if idx < len(self._entries): item = self._cls(self._repo, self._entries[idx]) if item.date == key: return item raise KeyError(key) elif isinstance(key, slice): if isinstance(key.start, RdiffTime): idx = bisect.bisect_left(self.keys(), key.start) key = slice(idx, key.stop, key.step) if isinstance(key.stop, RdiffTime): idx = bisect.bisect_right(self.keys(), key.stop) key = slice(key.start, idx, key.step) return [self._cls(self._repo, e) for e in self._entries[key]] elif isinstance(key, int): try: return self._cls(self._repo, self._entries[key]) except IndexError: raise KeyError(key) else: raise KeyError(key) def __iter__(self): for e in self._entries: yield self._cls(self._repo, e) def __len__(self): return len(self._entries) def keys(self): return MetadataKeys(lambda e: self._cls._extract_date(e), self._entries) class RdiffRepo(object): """Represent one rdiff-backup repository.""" def __init__(self, user_root, path, encoding): if isinstance(user_root, str): user_root = os.fsencode(user_root) if isinstance(path, str): path = os.fsencode(path) assert isinstance(user_root, bytes) assert isinstance(path, bytes) assert encoding self._encoding = encodings.search_function(encoding) assert self._encoding self.path = path.strip(b"/") if self.path: self.full_path = os.path.normpath(os.path.join(user_root, self.path)) else: self.full_path = os.path.normpath(user_root) # The location of rdiff-backup-data directory. self._data_path = os.path.join(self.full_path, RDIFF_BACKUP_DATA) assert isinstance(self._data_path, bytes) self._increment_path = os.path.join(self._data_path, INCREMENTS) self.current_mirror = MetadataDict(self, CurrentMirrorEntry) self.error_log = MetadataDict(self, LogEntry) self.mirror_metadata = MetadataDict(self, MirrorMetadataEntry) self.file_statistics = MetadataDict(self, FileStatisticsEntry) self.session_statistics = MetadataDict(self, SessionStatisticsEntry) @property def backup_dates(self): """Return a list of dates when backup was executed. This list is sorted from old to new (ascending order). To identify dates, 'mirror_metadata' file located in rdiff-backup-data are used.""" return self.mirror_metadata.keys() @property def backup_log(self): """ Return the location of the backup log. """ return BackupLogEntry(self, b'backup.log') def delete(self, path): """ Delete this entry from the repository history using rdiff-backup-delete. """ path_obj = self.fstat(path) if path_obj.isroot: return self.delete_repo() rdiff_backup_delete = find_rdiff_backup_delete() cmdline = [rdiff_backup_delete, path_obj.full_path] logger.info('executing: %r' % cmdline) process = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env={'LANG': LANG}) for line in process.stdout: line = line.rstrip(b'\n').decode('utf-8', errors='replace') logger.info('rdiff-backup-delete: %s' % line) retcode = process.wait() if retcode: raise CalledProcessError(retcode, cmdline) def delete_repo(self): """Delete the repository permanently.""" # Try to change the permissions of the file or directory to delete # them. def handle_error(func, path, exc_info): if exc_info[0] == PermissionError: # Parent directory must allow rwx if not os.access(os.path.dirname(path), os.W_OK | os.R_OK | os.X_OK): os.chmod(os.path.dirname(path), 0o0700) if not os.access(path, os.W_OK | os.R_OK): os.chmod(path, 0o0600) if os.path.isdir(path): return shutil.rmtree(path, onerror=handle_error) else: return os.unlink(path) raise try: shutil.rmtree(self.full_path, onerror=handle_error) except Exception: logger.warning('fail to delete repo', exc_info=1) @property def display_name(self): """Return the most human representation of the repository name.""" return self.get_display_name(b'') def _decode(self, value, errors='replace'): """Used to decode a repository path into unicode.""" assert isinstance(value, bytes) return self._encoding.decode(value, errors)[0] @cached_property def _entries(self): return sorted(os.listdir(self._data_path)) def listdir(self, path): """ Return a list of RdiffDirEntry each representing a file or a folder in the given path. """ # Compute increment directory location. full_path = os.path.realpath(os.path.join(self.full_path, path.strip(b'/'))) relative_path = os.path.relpath(full_path, self.full_path) if relative_path.startswith(RDIFF_BACKUP_DATA): raise DoesNotExistError(path) increment_path = os.path.normpath(os.path.join(self._increment_path, relative_path)) if not full_path.startswith(self.full_path) or not increment_path.startswith(self.full_path): raise AccessDeniedError('%s make reference outside the repository') # Get list of all increments and existing file and folder try: existing_items = os.listdir(full_path) if relative_path == b'.': existing_items.remove(RDIFF_BACKUP_DATA) except (NotADirectoryError, FileNotFoundError): existing_items = [] except OSError: raise AccessDeniedError(path) try: increment_items = os.listdir(increment_path) except (NotADirectoryError, FileNotFoundError): increment_items = [] except OSError: raise AccessDeniedError(path) # Raise error if nothing is found if not existing_items and not increment_items: raise DoesNotExistError(path) # Merge information from both location # Regroup all information into RdiffDirEntry entries = {} for name in existing_items: entries[name] = RdiffDirEntry( self, os.path.normpath(os.path.join(relative_path, name)), exists=True, increments=[], ) for item in increment_items: try: increment = IncrementEntry(item) except ValueError: # Ignore any increment that cannot be parsed continue entry = entries.get(increment.name, None) if not entry: # Create a new Direntry entry = entries[increment.name] = RdiffDirEntry( self, os.path.normpath(os.path.join(relative_path, increment.name)), exists=False, increments=[increment] if increment else [], ) else: # Add increment to dir entry bisect.insort_left(entry._increments, increment) return sorted(list(entries.values()), key=lambda e: e.path) def fstat(self, path): """Return a new instance of DirEntry to represent the given path.""" # Compute increment directory location. assert isinstance(path, bytes) full_path = os.path.normpath(os.path.join(self.full_path, path.strip(b'/'))) increment_path = os.path.normpath(os.path.join(self._increment_path, path.strip(b'/'), b'..')) if not full_path.startswith(self.full_path) or not increment_path.startswith(self.full_path): raise AccessDeniedError('%s make reference outside the repository') relative_path = os.path.relpath(full_path, self.full_path) if relative_path.startswith(RDIFF_BACKUP_DATA): raise DoesNotExistError(path) # Get if the path request is the root path. if relative_path == b'.': return RdiffDirEntry(self, b'', True, []) # TODO Check symlink # p = os.path.realpath(os.path.join(self.full_path, path)) # if not p.startswith(self.full_path): # raise AccessDeniedError(path) # Check if path exists try: os.lstat(full_path) exists = True except (OSError, ValueError): exists = False # Get incrmement data increment_items = os.listdir(increment_path) # Create dir entry prefix = os.path.basename(full_path) entry = RdiffDirEntry(self, relative_path, exists, []) for item in increment_items: if not item.startswith(prefix): # Ignore increment not matching our path continue try: increment = IncrementEntry(item) except ValueError: # Ignore any increment that cannot be parsed continue if increment.name != prefix: # Ignore increment not matching our path continue # Add increment to dir entry bisect.insort_left(entry._increments, increment) # Check if path exists or has increment. If not raise an exception. if not exists and not entry._increments: logger.error("path [%r] doesn't exists", path) raise DoesNotExistError(path) # Create a directory entry. return entry @property def last_backup_date(self): """Return the last known backup dates.""" try: if len(self.current_mirror) > 0: return self.current_mirror[-1].date return None except (PermissionError, FileNotFoundError): return None def get_display_name(self, path): """ Return proper display name of the given path according to repository encoding and quoted characters. """ assert isinstance(path, bytes) path = path.strip(b'/') if path in [b'.', b'']: # For repository we use either path if defined or the directory base name if not self.path: return self._decode(unquote(os.path.basename(self.full_path))) return self._decode(unquote(self.path)) else: # For path, we use the dir name return self._decode(unquote(os.path.basename(path))) def remove_older(self, remove_older_than): logger.info("execute rdiff-backup --force --remove-older-than=%sD %r", remove_older_than, self.full_path) subprocess.call( [ b'rdiff-backup', b'--force', b'--remove-older-than=' + str(remove_older_than).encode(encoding='latin1') + b'D', self.full_path, ] ) def restore(self, path, restore_as_of, kind=None): """ Restore the current directory entry into a fileobj containing the file content of the directory compressed into an archive. `kind` must be one of the supported archive type or none to use `zip` for folder and `raw` for file. Return a filename and a fileobj. """ assert isinstance(path, bytes) assert restore_as_of, "restore_as_of must be defined" assert kind in ['tar', 'tar.bz2', 'tar.gz', 'tbz2', 'tgz', 'zip', 'raw', None] # Define proper kind according to path type. path_obj = self.fstat(path) if path_obj.isdir: if kind == 'raw': raise ValueError('raw type not supported for directory') kind = kind or 'zip' else: kind = kind or 'raw' # Define proper filename according to the path if kind == 'raw': filename = path_obj.display_name else: filename = "%s.%s" % (path_obj.display_name, kind) # Call external process to offload processing. # python -m rdiffweb.core.restore --restore-as-of 123456 --encoding utf-8 --kind zip - cmdline = [ os.fsencode(sys.executable), b'-m', b'rdiffweb.core.restore', b'--restore-as-of', str(restore_as_of).encode('latin'), b'--encoding', self._encoding.name.encode('latin'), b'--kind', kind.encode('latin'), os.path.join(self.full_path, unquote(path_obj.path)), b'-', ] proc = subprocess.Popen( cmdline, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=None, ) # Check if the processing is properly started # Read stderr output until "Starting restore of" output = b'' success = False line = proc.stderr.readline() while line: output += line if b'Starting restore of' in line: success = True break line = proc.stderr.readline() if not success: raise CalledProcessError(1, cmdline, output) # Start a Thread to pipe the rest of the stream to the log t = threading.Thread(target=_readerthread, args=(proc.stderr, logger.debug)) t.daemon = True t.start() return filename, _wrap_close(proc.stdout, proc) @property def restore_log(self): """ Return the location of the restore log. """ return RestoreLogEntry(self, b'restore.log') @cached_property def status(self): """Check if a backup is in progress for the current repo.""" # Read content of the file and check if pid still exists try: # Make sure repoRoot is a valid rdiff-backup repository for current_mirror in self.current_mirror: pid = current_mirror.extract_pid() try: p = psutil.Process(pid) if any('rdiff-backup' in c for c in p.cmdline()): return ('in_progress', _('A backup is currently in progress to this repository.')) except psutil.NoSuchProcess: logger.debug('pid [%s] does not exists', pid) # If multiple current_mirror file exists and none of them are associated to a PID, this mean the last backup was interrupted. # Also, if the last backup date is undefined, this mean the first # initial backup was interrupted. if len(self.current_mirror) > 1 or len(self.current_mirror) == 0: self._status = ('interrupted', _('The previous backup seams to have failed.')) return self._status except FileNotFoundError: self._entries = [] return ('failed', _('The repository cannot be found or is badly damaged.')) except PermissionError: self._entries = [] logger.warning('error reading current_mirror files', exc_info=1) return ('failed', _("Permissions denied. Contact administrator to check repository's permissions.")) return ('ok', '')
rdiffweb/core/librdiff.py
codereval_python_data_139
Multi-platform variant of shlex.split() for command-line splitting. For use with subprocess, for argv injection etc. Using fast REGEX. platform: 'this' = auto from current platform; 1 = POSIX; 0 = Windows/CMD (other values reserved) import re def split(s, platform='this'): """Multi-platform variant of shlex.split() for command-line splitting. For use with subprocess, for argv injection etc. Using fast REGEX. platform: 'this' = auto from current platform; 1 = POSIX; 0 = Windows/CMD (other values reserved) """ if platform == 'this': platform = (sys.platform != 'win32') if platform == 1: RE_CMD_LEX = r'''"((?:\\["\\]|[^"])*)"|'([^']*)'|(\\.)|(&&?|\|\|?|\d?\>|[<])|([^\s'"\\&|<>]+)|(\s+)|(.)''' elif platform == 0: RE_CMD_LEX = r'''"((?:""|\\["\\]|[^"])*)"?()|(\\\\(?=\\*")|\\")|(&&?|\|\|?|\d?>|[<])|([^\s"&|<>]+)|(\s+)|(.)''' else: raise AssertionError('unkown platform %r' % platform) args = [] accu = None # collects pieces of one arg for qs, qss, esc, pipe, word, white, fail in re.findall(RE_CMD_LEX, s): if word: pass # most frequent elif esc: word = esc[1] elif white or pipe: if accu is not None: args.append(accu) if pipe: args.append(pipe) accu = None continue elif fail: raise ValueError("invalid or incomplete shell string") elif qs: word = qs.replace('\\"', '"').replace('\\\\', '\\') if platform == 0: word = word.replace('""', '"') else: word = qss # may be even empty; must be last accu = (accu or '') + word if accu is not None: args.append(accu) return args # This file was copied from https://github.com/jdjebi/winshlex # import sys import re def split(s, platform='this'): """Multi-platform variant of shlex.split() for command-line splitting. For use with subprocess, for argv injection etc. Using fast REGEX. platform: 'this' = auto from current platform; 1 = POSIX; 0 = Windows/CMD (other values reserved) """ if platform == 'this': platform = (sys.platform != 'win32') if platform == 1: RE_CMD_LEX = r'''"((?:\\["\\]|[^"])*)"|'([^']*)'|(\\.)|(&&?|\|\|?|\d?\>|[<])|([^\s'"\\&|<>]+)|(\s+)|(.)''' elif platform == 0: RE_CMD_LEX = r'''"((?:""|\\["\\]|[^"])*)"?()|(\\\\(?=\\*")|\\")|(&&?|\|\|?|\d?>|[<])|([^\s"&|<>]+)|(\s+)|(.)''' else: raise AssertionError('unkown platform %r' % platform) args = [] accu = None # collects pieces of one arg for qs, qss, esc, pipe, word, white, fail in re.findall(RE_CMD_LEX, s): if word: pass # most frequent elif esc: word = esc[1] elif white or pipe: if accu is not None: args.append(accu) if pipe: args.append(pipe) accu = None continue elif fail: raise ValueError("invalid or incomplete shell string") elif qs: word = qs.replace('\\"', '"').replace('\\\\', '\\') if platform == 0: word = word.replace('""', '"') else: word = qss # may be even empty; must be last accu = (accu or '') + word if accu is not None: args.append(accu) return args
cloudmesh/common/shlex.py
codereval_python_data_140
Given an existing archive_path, uncompress it. Returns a file repo url which can be used as origin url. This does not deal with the case where the archive passed along does not exist. import subprocess def prepare_repository_from_archive( archive_path: str, filename: Optional[str] = None, tmp_path: Union[PosixPath, str] = "/tmp", ) -> str: """Given an existing archive_path, uncompress it. Returns a file repo url which can be used as origin url. This does not deal with the case where the archive passed along does not exist. """ if not isinstance(tmp_path, str): tmp_path = str(tmp_path) # uncompress folder/repositories/dump for the loader to ingest subprocess.check_output(["tar", "xf", archive_path, "-C", tmp_path]) # build the origin url (or some derivative form) _fname = filename if filename else os.path.basename(archive_path) repo_url = f"file://{tmp_path}/{_fname}" return repo_url # Copyright (C) 2022 the Software Heritage developers # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import os from pathlib import PosixPath import subprocess from typing import Optional, Union # TODO: prepare_repository_from_archive method is duplicated from crates lister tests, # centralize to tests utils? def prepare_repository_from_archive( archive_path: str, filename: Optional[str] = None, tmp_path: Union[PosixPath, str] = "/tmp", ) -> str: """Given an existing archive_path, uncompress it. Returns a file repo url which can be used as origin url. This does not deal with the case where the archive passed along does not exist. """ if not isinstance(tmp_path, str): tmp_path = str(tmp_path) # uncompress folder/repositories/dump for the loader to ingest subprocess.check_output(["tar", "xf", archive_path, "-C", tmp_path]) # build the origin url (or some derivative form) _fname = filename if filename else os.path.basename(archive_path) repo_url = f"file://{tmp_path}/{_fname}" return repo_url
swh/lister/arch/tests/__init__.py
codereval_python_data_141
Use the git command to obtain the file names, turn it into a list, sort the list for only ignored files, return those files as a single string with each filename separated by a comma. import subprocess def addignored(ignored): ''' Use the git command to obtain the file names, turn it into a list, sort the list for only ignored files, return those files as a single string with each filename separated by a comma.''' fldr=subprocess.run(["git", "-C", ignored, "status", "-s", "--ignored"], capture_output=True, text=True).stdout.strip("\n") x = fldr.splitlines() sub = "!" g = ([s for s in x if sub in s]) i = [elem.replace(sub, '') for elem in g] t = ", ".join(i) return t # Copyright 2022 Ian Paul # Copyright 2009 Thomas Gideon # # This file is part of flashbake. # # flashbake is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # flashbake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with flashbake. If not, see <http://www.gnu.org/licenses/>. ''' This plugin was inspired by a suggestion from @xtaran on GitHub. It adds information to the commit message about files in the specified directory that are present and being ignored by git. ''' from flashbake.plugins import AbstractMessagePlugin import subprocess class Ignored(AbstractMessagePlugin): def __init__(self, plugin_spec): AbstractMessagePlugin.__init__(self, plugin_spec, False) self.define_property('ignored', required=False) def addcontext(self, message_file, config): ''' Add a list of the git repository's ignored but present files. ''' if self.ignored == None: message_file.write('Please specify the git directory containing ignored files.') else: t = self.addignored(self.ignored) message_file.write(t) def addignored(self, ignored): ''' Use the git command to obtain the file names, turn it into a list, sort the list for only ignored files, return those files as a single string with each filename separated by a comma.''' fldr=subprocess.run(["git", "-C", ignored, "status", "-s", "--ignored"], capture_output=True, text=True).stdout.strip("\n") x = fldr.splitlines() sub = "!" g = ([s for s in x if sub in s]) i = [elem.replace(sub, '') for elem in g] t = ", ".join(i) return t
src/flashbake/plugins/ignored.py
codereval_python_data_142
Check if the filename is a type that this module supports Args: filename: Filename to match Returns: False if not a match, True if supported import os def match(filename): """ Check if the filename is a type that this module supports Args: filename: Filename to match Returns: False if not a match, True if supported """ base_name = os.path.basename(filename) base_name_lower = base_name.lower() return base_name_lower == 'doxyfile' """Docopt is a Pythonic command-line interface parser that will make you smile. Now: with spellcheck, flag extension (de-abbreviation), and capitalization fixes. (but only when unambiguous) * Licensed under terms of MIT license (see LICENSE-MIT) Contributors (roughly in chronological order): * Copyright (c) 2012 Andrew Kassen <atkassen@ucdavis.edu> * Copyright (c) 2012 jeffrimko <jeffrimko@gmail.com> * Copyright (c) 2012 Andrew Sutton <met48@met48.com> * Copyright (c) 2012 Andrew Sutton <met48@met48.com> * Copyright (c) 2012 Nima Johari <nimajohari@gmail.com> * Copyright (c) 2012-2013 Vladimir Keleshev, vladimir@keleshev.com * Copyright (c) 2014-2018 Matt Boersma <matt@sprout.org> * Copyright (c) 2016 amir <ladsgroup@gmail.com> * Copyright (c) 2015 Benjamin Bach <benjaoming@gmail.com> * Copyright (c) 2017 Oleg Bulkin <o.bulkin@gmail.com> * Copyright (c) 2018 Iain Barnett <iainspeed@gmail.com> * Copyright (c) 2019 itdaniher, itdaniher@gmail.com """ from __future__ import annotations import sys import re import inspect from typing import Any, Type, Union, Callable, cast __all__ = ["docopt", "magic_docopt", "magic", "DocoptExit"] __version__ = "0.7.2" def levenshtein_norm(source: str, target: str) -> float: """Calculates the normalized Levenshtein distance between two string arguments. The result will be a float in the range [0.0, 1.0], with 1.0 signifying the biggest possible distance between strings with these lengths """ # Compute Levenshtein distance using helper function. The max is always # just the length of the longer string, so this is used to normalize result # before returning it distance = levenshtein(source, target) return float(distance) / max(len(source), len(target)) def levenshtein(source: str, target: str) -> int: """Computes the Levenshtein (https://en.wikipedia.org/wiki/Levenshtein_distance) and restricted Damerau-Levenshtein (https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distances between two Unicode strings with given lengths using the Wagner-Fischer algorithm (https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm). These distances are defined recursively, since the distance between two strings is just the cost of adjusting the last one or two characters plus the distance between the prefixes that exclude these characters (e.g. the distance between "tester" and "tested" is 1 + the distance between "teste" and "teste"). The Wagner-Fischer algorithm retains this idea but eliminates redundant computations by storing the distances between various prefixes in a matrix that is filled in iteratively. """ # Create matrix of correct size (this is s_len + 1 * t_len + 1 so that the # empty prefixes "" can also be included). The leftmost column represents # transforming various source prefixes into an empty string, which can # always be done by deleting all characters in the respective prefix, and # the top row represents transforming the empty string into various target # prefixes, which can always be done by inserting every character in the # respective prefix. The ternary used to build the list should ensure that # this row and column are now filled correctly s_range = range(len(source) + 1) t_range = range(len(target) + 1) matrix = [[(i if j == 0 else j) for j in t_range] for i in s_range] # Iterate through rest of matrix, filling it in with Levenshtein # distances for the remaining prefix combinations for i in s_range[1:]: for j in t_range[1:]: # Applies the recursive logic outlined above using the values # stored in the matrix so far. The options for the last pair of # characters are deletion, insertion, and substitution, which # amount to dropping the source character, the target character, # or both and then calculating the distance for the resulting # prefix combo. If the characters at this point are the same, the # situation can be thought of as a free substitution del_dist = matrix[i - 1][j] + 1 ins_dist = matrix[i][j - 1] + 1 sub_trans_cost = 0 if source[i - 1] == target[j - 1] else 1 sub_dist = matrix[i - 1][j - 1] + sub_trans_cost # Choose option that produces smallest distance matrix[i][j] = min(del_dist, ins_dist, sub_dist) # At this point, the matrix is full, and the biggest prefixes are just the # strings themselves, so this is the desired distance return matrix[len(source)][len(target)] class DocoptLanguageError(Exception): """Error in construction of usage-message by developer.""" class DocoptExit(SystemExit): """Exit in case user invoked program with incorrect arguments.""" usage = "" def __init__( self, message: str = "", collected: list[Pattern] = None, left: list[Pattern] = None, ) -> None: self.collected = collected if collected is not None else [] self.left = left if left is not None else [] SystemExit.__init__(self, (message + "\n" + self.usage).strip()) class Pattern: def __init__( self, name: str | None, value: list[str] | str | int | None = None ) -> None: self._name, self.value = name, value @property def name(self) -> str | None: return self._name def __eq__(self, other) -> bool: return repr(self) == repr(other) def __hash__(self) -> int: return hash(repr(self)) def transform(pattern: BranchPattern) -> Either: """Expand pattern into an (almost) equivalent one, but with single Either. Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) Quirks: [-a] => (-a), (-a...) => (-a -a) """ result = [] groups = [[pattern]] while groups: children = groups.pop(0) parents = [Required, NotRequired, OptionsShortcut, Either, OneOrMore] if any(t in map(type, children) for t in parents): child = [c for c in children if type(c) in parents][0] children.remove(child) if type(child) is Either: for c in child.children: groups.append([c] + children) elif type(child) is OneOrMore: groups.append(child.children * 2 + children) else: groups.append(child.children + children) else: result.append(children) return Either(*[Required(*e) for e in result]) TSingleMatch = tuple[Union[int, None], Union["LeafPattern", None]] class LeafPattern(Pattern): """Leaf/terminal node of a pattern tree.""" def __repr__(self) -> str: return "%s(%r, %r)" % (self.__class__.__name__, self.name, self.value) def single_match(self, left: list[LeafPattern]) -> TSingleMatch: raise NotImplementedError # pragma: no cover def flat(self, *types) -> list[LeafPattern]: return [self] if not types or type(self) in types else [] def match( self, left: list[LeafPattern], collected: list[Pattern] = None ) -> tuple[bool, list[LeafPattern], list[Pattern]]: collected = [] if collected is None else collected increment: Any | None = None pos, match = self.single_match(left) if match is None or pos is None: return False, left, collected left_ = left[:pos] + left[(pos + 1) :] same_name = [a for a in collected if a.name == self.name] if type(self.value) == int and len(same_name) > 0: if isinstance(same_name[0].value, int): same_name[0].value += 1 return True, left_, collected if type(self.value) == int and not same_name: match.value = 1 return True, left_, collected + [match] if same_name and type(self.value) == list: if type(match.value) == str: increment = [match.value] if same_name[0].value is not None and increment is not None: if isinstance(same_name[0].value, type(increment)): same_name[0].value += increment return True, left_, collected elif not same_name and type(self.value) == list: if isinstance(match.value, str): match.value = [match.value] return True, left_, collected + [match] return True, left_, collected + [match] class BranchPattern(Pattern): """Branch/inner node of a pattern tree.""" def __init__(self, *children) -> None: self.children = list(children) def match(self, left: list[Pattern], collected: list[Pattern] = None) -> Any: raise NotImplementedError # pragma: no cover def fix(self) -> "BranchPattern": self.fix_identities() self.fix_repeating_arguments() return self def fix_identities(self, uniq: Any | None = None) -> None: """Make pattern-tree tips point to same object if they are equal.""" flattened = self.flat() uniq = list(set(flattened)) if uniq is None else uniq for i, child in enumerate(self.children): if not hasattr(child, "children"): assert child in uniq self.children[i] = uniq[uniq.index(child)] else: child.fix_identities(uniq) return None def fix_repeating_arguments(self) -> BranchPattern: """Fix elements that should accumulate/increment values.""" either = [list(child.children) for child in transform(self).children] for case in either: for e in [child for child in case if case.count(child) > 1]: if type(e) is Argument or type(e) is Option and e.argcount: if e.value is None: e.value = [] elif type(e.value) is not list: e.value = cast(str, e.value) e.value = e.value.split() if type(e) is Command or type(e) is Option and e.argcount == 0: e.value = 0 return self def __repr__(self) -> str: return "%s(%s)" % ( self.__class__.__name__, ", ".join(repr(a) for a in self.children), ) def flat(self, *types) -> Any: if type(self) in types: return [self] return sum([child.flat(*types) for child in self.children], []) class Argument(LeafPattern): def single_match(self, left: list[LeafPattern]) -> TSingleMatch: for n, pattern in enumerate(left): if type(pattern) is Argument: return n, Argument(self.name, pattern.value) return None, None class Command(Argument): def __init__(self, name: str | None, value: bool = False) -> None: self._name, self.value = name, value def single_match(self, left: list[LeafPattern]) -> TSingleMatch: for n, pattern in enumerate(left): if type(pattern) is Argument: if pattern.value == self.name: return n, Command(self.name, True) else: break return None, None class Option(LeafPattern): def __init__( self, short: str | None = None, longer: str | None = None, argcount: int = 0, value: list[str] | str | int | None = False, ) -> None: assert argcount in (0, 1) self.short, self.longer, self.argcount = short, longer, argcount self.value = None if value is False and argcount else value @classmethod def parse(class_, option_description: str) -> Option: short, longer, argcount, value = None, None, 0, False options, _, description = option_description.strip().partition(" ") options = options.replace(",", " ").replace("=", " ") for s in options.split(): if s.startswith("--"): longer = s elif s.startswith("-"): short = s else: argcount = 1 if argcount: matched = re.findall(r"\[default: (.*)\]", description, flags=re.I) value = matched[0] if matched else None return class_(short, longer, argcount, value) def single_match(self, left: list[LeafPattern]) -> TSingleMatch: for n, pattern in enumerate(left): if self.name == pattern.name: return n, pattern return None, None @property def name(self) -> str | None: return self.longer or self.short def __repr__(self) -> str: return "Option(%r, %r, %r, %r)" % ( self.short, self.longer, self.argcount, self.value, ) class Required(BranchPattern): def match(self, left: list[Pattern], collected: list[Pattern] | None = None) -> Any: collected = [] if collected is None else collected original_collected = collected original_left = left for pattern in self.children: matched, left, collected = pattern.match(left, collected) if not matched: return False, original_left, original_collected return True, left, collected class NotRequired(BranchPattern): def match(self, left: list[Pattern], collected: list[Pattern] = None) -> Any: collected = [] if collected is None else collected for pattern in self.children: _, left, collected = pattern.match(left, collected) return True, left, collected class OptionsShortcut(NotRequired): """Marker/placeholder for [options] shortcut.""" class OneOrMore(BranchPattern): def match(self, left: list[Pattern], collected: list[Pattern] = None) -> Any: assert len(self.children) == 1 collected = [] if collected is None else collected original_collected = collected original_left = left last_left = None matched = True times = 0 while matched: matched, left, collected = self.children[0].match(left, collected) times += 1 if matched else 0 if last_left == left: break last_left = left if times >= 1: return True, left, collected return False, original_left, original_collected class Either(BranchPattern): def match(self, left: list[Pattern], collected: list[Pattern] = None) -> Any: collected = [] if collected is None else collected outcomes = [] for pattern in self.children: matched, _, _ = outcome = pattern.match(left, collected) if matched: outcomes.append(outcome) if outcomes: return min(outcomes, key=lambda outcome: len(outcome[1])) return False, left, collected class Tokens(list): def __init__( self, source: list[str] | str, error: Type[DocoptExit] | Type[DocoptLanguageError] = DocoptExit, ) -> None: if isinstance(source, list): self += source else: self += source.split() self.error = error @staticmethod def from_pattern(source: str) -> Tokens: source = re.sub(r"([\[\]\(\)\|]|\.\.\.)", r" \1 ", source) fragments = [s for s in re.split(r"\s+|(\S*<.*?>)", source) if s] return Tokens(fragments, error=DocoptLanguageError) def move(self) -> str | None: return self.pop(0) if len(self) else None def current(self) -> str | None: return self[0] if len(self) else None def parse_longer( tokens: Tokens, options: list[Option], argv: bool = False, more_magic: bool = False ) -> list[Pattern]: """longer ::= '--' chars [ ( ' ' | '=' ) chars ] ;""" current_token = tokens.move() if current_token is None or not current_token.startswith("--"): raise tokens.error( f"parse_longer got what appears to be an invalid token: {current_token}" ) # pragma: no cover longer, maybe_eq, maybe_value = current_token.partition("=") if maybe_eq == maybe_value == "": value = None else: value = maybe_value similar = [o for o in options if o.longer and longer == o.longer] start_collision = ( len( [ o for o in options if o.longer and longer in o.longer and o.longer.startswith(longer) ] ) > 1 ) if argv and not len(similar) and not start_collision: similar = [ o for o in options if o.longer and longer in o.longer and o.longer.startswith(longer) ] # try advanced matching if more_magic and not similar: corrected = [ (longer, o) for o in options if o.longer and levenshtein_norm(longer, o.longer) < 0.25 ] if corrected: print(f"NB: Corrected {corrected[0][0]} to {corrected[0][1].longer}") similar = [correct for (original, correct) in corrected] if len(similar) > 1: raise tokens.error( f"{longer} is not a unique prefix: {similar}?" ) # pragma: no cover elif len(similar) < 1: argcount = 1 if maybe_eq == "=" else 0 o = Option(None, longer, argcount) options.append(o) if tokens.error is DocoptExit: o = Option(None, longer, argcount, value if argcount else True) else: o = Option( similar[0].short, similar[0].longer, similar[0].argcount, similar[0].value ) if o.argcount == 0: if value is not None: raise tokens.error("%s must not have an argument" % o.longer) else: if value is None: if tokens.current() in [None, "--"]: raise tokens.error("%s requires argument" % o.longer) value = tokens.move() if tokens.error is DocoptExit: o.value = value if value is not None else True return [o] def parse_shorts( tokens: Tokens, options: list[Option], more_magic: bool = False ) -> list[Pattern]: """shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;""" token = tokens.move() if token is None or not token.startswith("-") or token.startswith("--"): raise ValueError( f"parse_shorts got what appears to be an invalid token: {token}" ) # pragma: no cover left = token.lstrip("-") parsed: list[Pattern] = [] while left != "": short, left = "-" + left[0], left[1:] transformations: dict[str | None, Callable[[str], str]] = {None: lambda x: x} if more_magic: transformations["lowercase"] = lambda x: x.lower() transformations["uppercase"] = lambda x: x.upper() # try identity, lowercase, uppercase, iff such resolves uniquely # (ie if upper and lowercase are not both defined) similar: list[Option] = [] de_abbreviated = False for transform_name, transform in transformations.items(): transformed = list(set([transform(o.short) for o in options if o.short])) no_collisions = len( [ o for o in options if o.short and transformed.count(transform(o.short)) == 1 ] ) # == len(transformed) if no_collisions: similar = [ o for o in options if o.short and transform(o.short) == transform(short) ] if similar: if transform_name: print( f"NB: Corrected {short} to {similar[0].short} " f"via {transform_name}" ) break # if transformations do not resolve, try abbreviations of 'longer' forms # iff such resolves uniquely (ie if no two longer forms begin with the # same letter) if not similar and more_magic: abbreviated = [ transform(o.longer[1:3]) for o in options if o.longer and not o.short ] + [transform(o.short) for o in options if o.short and not o.longer] nonredundantly_abbreviated_options = [ o for o in options if o.longer and abbreviated.count(short) == 1 ] no_collisions = len(nonredundantly_abbreviated_options) == len( abbreviated ) if no_collisions: for o in options: if ( not o.short and o.longer and transform(short) == transform(o.longer[1:3]) ): similar = [o] print( f"NB: Corrected {short} to {similar[0].longer} " f"via abbreviation (case change: {transform_name})" ) break if len(similar): de_abbreviated = True break if len(similar) > 1: raise tokens.error( "%s is specified ambiguously %d times" % (short, len(similar)) ) elif len(similar) < 1: o = Option(short, None, 0) options.append(o) if tokens.error is DocoptExit: o = Option(short, None, 0, True) else: if de_abbreviated: option_short_value = None else: option_short_value = transform(short) o = Option( option_short_value, similar[0].longer, similar[0].argcount, similar[0].value, ) value = None current_token = tokens.current() if o.argcount != 0: if left == "": if current_token is None or current_token == "--": raise tokens.error("%s requires argument" % short) else: value = tokens.move() else: value = left left = "" if tokens.error is DocoptExit: o.value = value if value is not None else True parsed.append(o) return parsed def parse_pattern(source: str, options: list[Option]) -> Required: tokens = Tokens.from_pattern(source) result = parse_expr(tokens, options) if tokens.current() is not None: raise tokens.error("unexpected ending: %r" % " ".join(tokens)) return Required(*result) def parse_expr(tokens: Tokens, options: list[Option]) -> list[Pattern]: """expr ::= seq ( '|' seq )* ;""" result: list[Pattern] = [] seq_0: list[Pattern] = parse_seq(tokens, options) if tokens.current() != "|": return seq_0 if len(seq_0) > 1: result.append(Required(*seq_0)) else: result += seq_0 while tokens.current() == "|": tokens.move() seq_1 = parse_seq(tokens, options) if len(seq_1) > 1: result += [Required(*seq_1)] else: result += seq_1 return [Either(*result)] def parse_seq(tokens: Tokens, options: list[Option]) -> list[Pattern]: """seq ::= ( atom [ '...' ] )* ;""" result: list[Pattern] = [] while tokens.current() not in [None, "]", ")", "|"]: atom = parse_atom(tokens, options) if tokens.current() == "...": atom = [OneOrMore(*atom)] tokens.move() result += atom return result def parse_atom(tokens: Tokens, options: list[Option]) -> list[Pattern]: """atom ::= '(' expr ')' | '[' expr ']' | 'options' | longer | shorts | argument | command ; """ token = tokens.current() if not token: return [Command(tokens.move())] # pragma: no cover elif token in "([": tokens.move() matching = {"(": ")", "[": "]"}[token] pattern = {"(": Required, "[": NotRequired}[token] matched_pattern = pattern(*parse_expr(tokens, options)) if tokens.move() != matching: raise tokens.error("unmatched '%s'" % token) return [matched_pattern] elif token == "options": tokens.move() return [OptionsShortcut()] elif token.startswith("--") and token != "--": return parse_longer(tokens, options) elif token.startswith("-") and token not in ("-", "--"): return parse_shorts(tokens, options) elif token.startswith("<") and token.endswith(">") or token.isupper(): return [Argument(tokens.move())] else: return [Command(tokens.move())] def parse_argv( tokens: Tokens, options: list[Option], options_first: bool = False, more_magic: bool = False, ) -> list[Pattern]: """Parse command-line argument vector. If options_first: argv ::= [ longer | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ longer | shorts | argument ]* [ '--' [ argument ]* ] ; """ def isanumber(x): try: float(x) return True except ValueError: return False parsed: list[Pattern] = [] current_token = tokens.current() while current_token is not None: if current_token == "--": return parsed + [Argument(None, v) for v in tokens] elif current_token.startswith("--"): parsed += parse_longer(tokens, options, argv=True, more_magic=more_magic) elif ( current_token.startswith("-") and current_token != "-" and not isanumber(current_token) ): parsed += parse_shorts(tokens, options, more_magic=more_magic) elif options_first: return parsed + [Argument(None, v) for v in tokens] else: parsed.append(Argument(None, tokens.move())) current_token = tokens.current() return parsed def parse_defaults(docstring: str) -> list[Option]: defaults = [] for s in parse_section("options:", docstring): options_literal, _, s = s.partition(":") if " " in options_literal: _, _, options_literal = options_literal.partition(" ") assert options_literal.lower().strip() == "options" split = re.split(r"\n[ \t]*(-\S+?)", "\n" + s)[1:] split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])] for s in split: if s.startswith("-"): arg, _, description = s.partition(" ") flag, _, var = arg.replace("=", " ").partition(" ") option = Option.parse(s) defaults.append(option) return defaults def parse_section(name: str, source: str) -> list[str]: pattern = re.compile( "^([^\n]*" + name + "[^\n]*\n?(?:[ \t].*?(?:\n|$))*)", re.IGNORECASE | re.MULTILINE, ) r = [ s.strip() for s in pattern.findall(source) if s.strip().lower() != name.lower() ] return r def formal_usage(section: str) -> str: _, _, section = section.partition(":") # drop "usage:" pu = section.split() return "( " + " ".join(") | (" if s == pu[0] else s for s in pu[1:]) + " )" def extras( default_help: bool, version: None, options: list[Pattern], docstring: str ) -> None: if default_help and any( (o.name in ("-h", "--help")) and o.value for o in options if isinstance(o, Option) ): print(docstring.strip("\n")) sys.exit() if version and any( o.name == "--version" and o.value for o in options if isinstance(o, Option) ): print(version) sys.exit() class ParsedOptions(dict): def __repr__(self): return "{%s}" % ",\n ".join("%r: %r" % i for i in sorted(self.items())) def __getattr__(self, name: str) -> str | bool | None: return self.get(name) or { name: self.get(k) for k in self.keys() if name in [k.lstrip("-").replace("-", "_"), k.lstrip("<").rstrip(">")] }.get(name) def docopt( docstring: str | None = None, argv: list[str] | str | None = None, default_help: bool = True, version: Any = None, options_first: bool = False, more_magic: bool = False, ) -> ParsedOptions: """Parse `argv` based on command-line interface described in `doc`. `docopt` creates your command-line interface based on its description that you pass as `docstring`. Such description can contain --options, <positional-argument>, commands, which could be [optional], (required), (mutually | exclusive) or repeated... Parameters ---------- docstring : str (default: first __doc__ in parent scope) Description of your command-line interface. argv : list of str, optional Argument vector to be parsed. sys.argv[1:] is used if not provided. default_help : bool (default: True) Set to False to disable automatic help on -h or --help options. version : any object If passed, the object will be printed if --version is in `argv`. options_first : bool (default: False) Set to True to require options precede positional arguments, i.e. to forbid options and positional arguments intermix. more_magic : bool (default: False) Try to be extra-helpful; pull results into globals() of caller as 'arguments', offer advanced pattern-matching and spellcheck. Also activates if `docopt` aliased to a name containing 'magic'. Returns ------- arguments: dict-like A dictionary, where keys are names of command-line elements such as e.g. "--verbose" and "<path>", and values are the parsed values of those elements. Also supports dot acccess. Example ------- >>> from docopt import docopt >>> doc = ''' ... Usage: ... my_program tcp <host> <port> [--timeout=<seconds>] ... my_program serial <port> [--baud=<n>] [--timeout=<seconds>] ... my_program (-h | --help | --version) ... ... Options: ... -h, --help Show this screen and exit. ... --baud=<n> Baudrate [default: 9600] ... ''' >>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30'] >>> docopt(doc, argv) {'--baud': '9600', '--help': False, '--timeout': '30', '--version': False, '<host>': '127.0.0.1', '<port>': '80', 'serial': False, 'tcp': True} """ argv = sys.argv[1:] if argv is None else argv maybe_frame = inspect.currentframe() if maybe_frame: parent_frame = doc_parent_frame = magic_parent_frame = maybe_frame.f_back if not more_magic: # make sure 'magic' isn't in the calling name while not more_magic and magic_parent_frame: imported_as = { v: k for k, v in magic_parent_frame.f_globals.items() if hasattr(v, "__name__") and v.__name__ == docopt.__name__ }.get(docopt) if imported_as and "magic" in imported_as: more_magic = True else: magic_parent_frame = magic_parent_frame.f_back if not docstring: # go look for one, if none exists, raise Exception while not docstring and doc_parent_frame: docstring = doc_parent_frame.f_locals.get("__doc__") if not docstring: doc_parent_frame = doc_parent_frame.f_back if not docstring: raise DocoptLanguageError( "Either __doc__ must be defined in the scope of a parent " "or passed as the first argument." ) output_value_assigned = False if more_magic and parent_frame: import dis instrs = dis.get_instructions(parent_frame.f_code) for instr in instrs: if instr.offset == parent_frame.f_lasti: break assert instr.opname.startswith("CALL_") MAYBE_STORE = next(instrs) if MAYBE_STORE and ( MAYBE_STORE.opname.startswith("STORE") or MAYBE_STORE.opname.startswith("RETURN") ): output_value_assigned = True usage_sections = parse_section("usage:", docstring) if len(usage_sections) == 0: raise DocoptLanguageError( '"usage:" section (case-insensitive) not found. ' "Perhaps missing indentation?" ) if len(usage_sections) > 1: raise DocoptLanguageError('More than one "usage:" (case-insensitive).') options_pattern = re.compile(r"\n\s*?options:", re.IGNORECASE) if options_pattern.search(usage_sections[0]): raise DocoptExit( "Warning: options (case-insensitive) was found in usage." "Use a blank line between each section.." ) DocoptExit.usage = usage_sections[0] options = parse_defaults(docstring) pattern = parse_pattern(formal_usage(DocoptExit.usage), options) pattern_options = set(pattern.flat(Option)) for options_shortcut in pattern.flat(OptionsShortcut): doc_options = parse_defaults(docstring) options_shortcut.children = [ opt for opt in doc_options if opt not in pattern_options ] parsed_arg_vector = parse_argv( Tokens(argv), list(options), options_first, more_magic ) extras(default_help, version, parsed_arg_vector, docstring) matched, left, collected = pattern.fix().match(parsed_arg_vector) if matched and left == []: output_obj = ParsedOptions( (a.name, a.value) for a in (pattern.flat() + collected) ) target_parent_frame = parent_frame or magic_parent_frame or doc_parent_frame if more_magic and target_parent_frame and not output_value_assigned: if not target_parent_frame.f_globals.get("arguments"): target_parent_frame.f_globals["arguments"] = output_obj return output_obj if left: raise DocoptExit(f"Warning: found unmatched (duplicate?) arguments {left}") raise DocoptExit(collected=collected, left=left) magic = magic_docopt = docopt
docopt/__init__.py
codereval_python_data_143
Given a frequency string with a number and a unit of time, return a corresponding datetime.timedelta instance or None if the frequency is None or "always". For instance, given "3 weeks", return datetime.timedelta(weeks=3) Raise ValueError if the given frequency cannot be parsed. import datetime def parse_frequency(frequency): ''' Given a frequency string with a number and a unit of time, return a corresponding datetime.timedelta instance or None if the frequency is None or "always". For instance, given "3 weeks", return datetime.timedelta(weeks=3) Raise ValueError if the given frequency cannot be parsed. ''' if not frequency: return None frequency = frequency.strip().lower() if frequency == 'always': return None try: number, time_unit = frequency.split(' ') number = int(number) except ValueError: raise ValueError(f"Could not parse consistency check frequency '{frequency}'") if not time_unit.endswith('s'): time_unit += 's' if time_unit == 'months': number *= 4 time_unit = 'weeks' elif time_unit == 'years': number *= 365 time_unit = 'days' try: return datetime.timedelta(**{time_unit: number}) except TypeError: raise ValueError(f"Could not parse consistency check frequency '{frequency}'") import argparse import datetime import json import logging import os import pathlib from borgmatic.borg import extract, info, state from borgmatic.execute import DO_NOT_CAPTURE, execute_command DEFAULT_CHECKS = ( {'name': 'repository', 'frequency': '2 weeks'}, {'name': 'archives', 'frequency': '2 weeks'}, ) DEFAULT_PREFIX = '{hostname}-' logger = logging.getLogger(__name__) def parse_checks(consistency_config, only_checks=None): ''' Given a consistency config with a "checks" sequence of dicts and an optional list of override checks, return a tuple of named checks to run. For example, given a retention config of: {'checks': ({'name': 'repository'}, {'name': 'archives'})} This will be returned as: ('repository', 'archives') If no "checks" option is present in the config, return the DEFAULT_CHECKS. If a checks value has a name of "disabled", return an empty tuple, meaning that no checks should be run. If the "data" check is present, then make sure the "archives" check is included as well. ''' checks = only_checks or tuple( check_config['name'] for check_config in (consistency_config.get('checks', None) or DEFAULT_CHECKS) ) checks = tuple(check.lower() for check in checks) if 'disabled' in checks: if len(checks) > 1: logger.warning( 'Multiple checks are configured, but one of them is "disabled"; not running any checks' ) return () if 'data' in checks and 'archives' not in checks: return checks + ('archives',) return checks def parse_frequency(frequency): ''' Given a frequency string with a number and a unit of time, return a corresponding datetime.timedelta instance or None if the frequency is None or "always". For instance, given "3 weeks", return datetime.timedelta(weeks=3) Raise ValueError if the given frequency cannot be parsed. ''' if not frequency: return None frequency = frequency.strip().lower() if frequency == 'always': return None try: number, time_unit = frequency.split(' ') number = int(number) except ValueError: raise ValueError(f"Could not parse consistency check frequency '{frequency}'") if not time_unit.endswith('s'): time_unit += 's' if time_unit == 'months': number *= 4 time_unit = 'weeks' elif time_unit == 'years': number *= 365 time_unit = 'days' try: return datetime.timedelta(**{time_unit: number}) except TypeError: raise ValueError(f"Could not parse consistency check frequency '{frequency}'") def filter_checks_on_frequency(location_config, consistency_config, borg_repository_id, checks): ''' Given a location config, a consistency config with a "checks" sequence of dicts, a Borg repository ID, and sequence of checks, filter down those checks based on the configured "frequency" for each check as compared to its check time file. In other words, a check whose check time file's timestamp is too new (based on the configured frequency) will get cut from the returned sequence of checks. Example: consistency_config = { 'checks': [ { 'name': 'archives', 'frequency': '2 weeks', }, ] } When this function is called with that consistency_config and "archives" in checks, "archives" will get filtered out of the returned result if its check time file is newer than 2 weeks old, indicating that it's not yet time to run that check again. Raise ValueError if a frequency cannot be parsed. ''' filtered_checks = list(checks) for check_config in consistency_config.get('checks', DEFAULT_CHECKS): check = check_config['name'] if checks and check not in checks: continue frequency_delta = parse_frequency(check_config.get('frequency')) if not frequency_delta: continue check_time = read_check_time( make_check_time_path(location_config, borg_repository_id, check) ) if not check_time: continue # If we've not yet reached the time when the frequency dictates we're ready for another # check, skip this check. if datetime.datetime.now() < check_time + frequency_delta: remaining = check_time + frequency_delta - datetime.datetime.now() logger.info( f"Skipping {check} check due to configured frequency; {remaining} until next check" ) filtered_checks.remove(check) return tuple(filtered_checks) def make_check_flags(checks, check_last=None, prefix=None): ''' Given a parsed sequence of checks, transform it into tuple of command-line flags. For example, given parsed checks of: ('repository',) This will be returned as: ('--repository-only',) However, if both "repository" and "archives" are in checks, then omit them from the returned flags because Borg does both checks by default. Additionally, if a check_last value is given and "archives" is in checks, then include a "--last" flag. And if a prefix value is given and "archives" is in checks, then include a "--prefix" flag. ''' if 'archives' in checks: last_flags = ('--last', str(check_last)) if check_last else () prefix_flags = ('--prefix', prefix) if prefix else () else: last_flags = () prefix_flags = () if check_last: logger.info('Ignoring check_last option, as "archives" is not in consistency checks') if prefix: logger.info( 'Ignoring consistency prefix option, as "archives" is not in consistency checks' ) common_flags = last_flags + prefix_flags + (('--verify-data',) if 'data' in checks else ()) if {'repository', 'archives'}.issubset(set(checks)): return common_flags return ( tuple('--{}-only'.format(check) for check in checks if check in ('repository', 'archives')) + common_flags ) def make_check_time_path(location_config, borg_repository_id, check_type): ''' Given a location configuration dict, a Borg repository ID, and the name of a check type ("repository", "archives", etc.), return a path for recording that check's time (the time of that check last occurring). ''' return os.path.join( os.path.expanduser( location_config.get( 'borgmatic_source_directory', state.DEFAULT_BORGMATIC_SOURCE_DIRECTORY ) ), 'checks', borg_repository_id, check_type, ) def write_check_time(path): # pragma: no cover ''' Record a check time of now as the modification time of the given path. ''' logger.debug(f'Writing check time at {path}') os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) pathlib.Path(path, mode=0o600).touch() def read_check_time(path): ''' Return the check time based on the modification time of the given path. Return None if the path doesn't exist. ''' logger.debug(f'Reading check time from {path}') try: return datetime.datetime.fromtimestamp(os.stat(path).st_mtime) except FileNotFoundError: return None def check_archives( repository, location_config, storage_config, consistency_config, local_path='borg', remote_path=None, progress=None, repair=None, only_checks=None, ): ''' Given a local or remote repository path, a storage config dict, a consistency config dict, local/remote commands to run, whether to include progress information, whether to attempt a repair, and an optional list of checks to use instead of configured checks, check the contained Borg archives for consistency. If there are no consistency checks to run, skip running them. Raises ValueError if the Borg repository ID cannot be determined. ''' try: borg_repository_id = json.loads( info.display_archives_info( repository, storage_config, argparse.Namespace(json=True, archive=None), local_path, remote_path, ) )['repository']['id'] except (json.JSONDecodeError, KeyError): raise ValueError(f'Cannot determine Borg repository ID for {repository}') checks = filter_checks_on_frequency( location_config, consistency_config, borg_repository_id, parse_checks(consistency_config, only_checks), ) check_last = consistency_config.get('check_last', None) lock_wait = None extra_borg_options = storage_config.get('extra_borg_options', {}).get('check', '') if set(checks).intersection({'repository', 'archives', 'data'}): lock_wait = storage_config.get('lock_wait', None) verbosity_flags = () if logger.isEnabledFor(logging.INFO): verbosity_flags = ('--info',) if logger.isEnabledFor(logging.DEBUG): verbosity_flags = ('--debug', '--show-rc') prefix = consistency_config.get('prefix', DEFAULT_PREFIX) full_command = ( (local_path, 'check') + (('--repair',) if repair else ()) + make_check_flags(checks, check_last, prefix) + (('--remote-path', remote_path) if remote_path else ()) + (('--lock-wait', str(lock_wait)) if lock_wait else ()) + verbosity_flags + (('--progress',) if progress else ()) + (tuple(extra_borg_options.split(' ')) if extra_borg_options else ()) + (repository,) ) # The Borg repair option triggers an interactive prompt, which won't work when output is # captured. And progress messes with the terminal directly. if repair or progress: execute_command(full_command, output_file=DO_NOT_CAPTURE) else: execute_command(full_command) for check in checks: write_check_time(make_check_time_path(location_config, borg_repository_id, check)) if 'extract' in checks: extract.extract_last_archive_dry_run(repository, lock_wait, local_path, remote_path) write_check_time(make_check_time_path(location_config, borg_repository_id, 'extract'))
borgmatic/borg/check.py
codereval_python_data_144
Checks if the host is the localhost :param host: The hostname or ip :return: True if the host is the localhost import socket def is_local(host): """ Checks if the host is the localhost :param host: The hostname or ip :return: True if the host is the localhost """ return host in ["127.0.0.1", "localhost", socket.gethostname(), # just in case socket.gethostname() does not work we also try the following: platform.node(), socket.gethostbyaddr(socket.gethostname())[0] ] import subprocess import collections import glob import inspect import os import random import re import shutil import tempfile import time from contextlib import contextmanager import sys import psutil import requests from pathlib import Path from cloudmesh.common.console import Console from cloudmesh.common.systeminfo import is_gitbash, is_cmd_exe import pyfiglet import socket import platform try: collectionsAbc = collections.abc except AttributeError: collectionsAbc = collections @contextmanager def tempdir(*args, **kwargs): """A contextmanager to work in an auto-removed temporary directory Arguments are passed through to tempfile.mkdtemp example: >>> with tempdir() as path: ... pass """ d = tempfile.mkdtemp(*args, **kwargs) try: yield d finally: shutil.rmtree(d) def check_root(dryrun=False, terminate=True): """ check if I am the root user. If not, simply exits the program. :param dryrun: if set to true, does not terminate if not root user :type dryrun: bool :param terminate: terminates if not root user and dryrun is False :type terminate: bool """ uid = os.getuid() if uid == 0: Console.ok("You are executing as a root user") else: Console.error("You do not run as root") if terminate and not dryrun: sys.exit() def exponential_backoff(fn, sleeptime_s_max=30 * 60): """ Calls `fn` until it returns True, with an exponentially increasing wait time between calls :param fn: the function to be called that returns Truw or False :type fn: object :param sleeptime_s_max: the sleep time in milliseconds :type sleeptime_s_max: int :return: None """ sleeptime_ms = 500 while True: if fn(): return True else: print('Sleeping {} ms'.format(sleeptime_ms)) time.sleep(sleeptime_ms / 1000.0) sleeptime_ms *= 2 if sleeptime_ms / 1000.0 > sleeptime_s_max: return False def download(source, destination, force=False): """ Downloads the file from source to destination For large files, see cloudmesh.common.Shell.download :param source: The http source :param destination: The destination in the file system :param force: If True the file will be downloaded even if it already exists """ if os.path.isfile(destination) and not force: Console.warning(f"File {destination} already exists. " "Skipping download ...") else: directory = os.path.dirname(destination) Path(directory).mkdir(parents=True, exist_ok=True) r = requests.get(source, allow_redirects=True) open(destination, 'wb').write(r.content) def search(lines, pattern): """ return all lines that match the pattern #TODO: we need an example :param lines: :param pattern: :return: """ p = pattern.replace("*", ".*") test = re.compile(p) result = [] for l in lines: # noqa: E741 if test.search(l): result.append(l) return result def grep(pattern, filename): """Very simple grep that returns the first matching line in a file. String matching only, does not do REs as currently implemented. """ try: # for line in file # if line matches pattern: # return line return next((L for L in open(filename) if L.find(pattern) >= 0)) except StopIteration: return '' def is_local(host): """ Checks if the host is the localhost :param host: The hostname or ip :return: True if the host is the localhost """ return host in ["127.0.0.1", "localhost", socket.gethostname(), # just in case socket.gethostname() does not work we also try the following: platform.node(), socket.gethostbyaddr(socket.gethostname())[0] ] # noinspection PyPep8 def is_gitbash(): """ returns True if you run in a Windows gitbash :return: True if gitbash """ try: exepath = os.environ['EXEPATH'] return "Git" in exepath except: return False def is_powershell(): """ True if you run in powershell :return: True if you run in powershell """ # psutil.Process(parent_pid).name() returns - # cmd.exe for CMD # powershell.exe for powershell # bash.exe for git bash return (psutil.Process(os.getppid()).name() == "powershell.exe") def is_cmd_exe(): """ return True if you run in a Windows CMD :return: True if you run in CMD """ if is_gitbash(): return False else: try: return os.environ['OS'] == 'Windows_NT' except: return False def path_expand(text): """ returns a string with expanded variable. :param text: the path to be expanded, which can include ~ and environment variables :param text: string """ result = os.path.expandvars(os.path.expanduser(text)) if result.startswith("./"): result = result.replace(".", os.getcwd(), 1) if is_gitbash() or is_cmd_exe(): result = result.replace("/", "\\") return result def convert_from_unicode(data): """ converts unicode data to a string :param data: the data to convert :return: """ # if isinstance(data, basestring): if isinstance(data, str): return str(data) elif isinstance(data, collectionsAbc.Mapping): return dict(map(convert_from_unicode, data.items())) elif isinstance(data, collectionsAbc.Iterable): return type(data)(map(convert_from_unicode, data)) else: return data def yn_choice(message, default='y', tries=None): """asks for a yes/no question. :param tries: the number of tries :param message: the message containing the question :param default: the default answer """ # http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input""" choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N' if tries is None: choice = input(f"{message} ({choices}) ") values = ('y', 'yes', '') if default == 'y' else ('y', 'yes') return True if choice.strip().lower() in values else False else: while tries > 0: choice = input(f"{message} ({choices}) ('q' to discard)") choice = choice.strip().lower() if choice in ['y', 'yes']: return True elif choice in ['n', 'no', 'q']: return False else: print("Invalid input...") tries -= 1 def str_banner(txt=None, c="-", prefix="#", debug=True, label=None, color="BLUE", padding=False, figlet=False, font="big"): """ prints a banner of the form with a frame of # around the txt:: # -------------------------- # txt # -------------------------- :param color: prints in the given color :param label: adds a label :param debug: prints only if debug is true :param txt: a text message to be printed :type txt: string :param c: the character used instead of c :type c: character """ output = "" if debug: output = "\n" output += prefix + " " + 70 * c + "\n" if padding: output += prefix + "\n" if label is not None: output += prefix + " " + label + "\n" output += prefix + " " + 70 * c + "\n" if txt is not None: if figlet: txt = pyfiglet.figlet_format(txt, font=font) for line in txt.splitlines(): output += prefix + " " + line + "\n" if padding: output += prefix + "\n" output += prefix + " " + 70 * c + "\n" return output def banner(txt=None, c="-", prefix="#", debug=True, label=None, color="BLUE", padding=False, figlet=False, font="big"): """ prints a banner of the form with a frame of # around the txt:: # -------------------------- # txt # -------------------------- :param color: prints in the given color :param label: adds a label :param debug: prints only if debug is true :param txt: a text message to be printed :type txt: string :param c: the character used instead of c :type c: character :param padding: ads additional comment line around the text so the banner is larger :type padding: bool """ output = str_banner(txt=txt, c=c, prefix=prefix, debug=debug, label=label, color=color, padding=padding, figlet=figlet, font=font) Console.cprint(color, "", output) # noinspection PyPep8Naming def HEADING(txt=None, c="#", color="HEADER"): """ Prints a message to stdout with #### surrounding it. This is useful for pytests to better distinguish them. :param c: uses the given char to wrap the header :param txt: a text message to be printed :type txt: string """ frame = inspect.getouterframes(inspect.currentframe()) filename = frame[1][1].replace(os.getcwd(), "") line = frame[1][2] - 1 method = frame[1][3] if txt is None: msg = "{} {} {}".format(method, filename, line) else: msg = "{}\n {} {} {}".format(txt, method, filename, line) print() banner(msg, c=c, color=color) # noinspection PyPep8Naming def FUNCTIONNAME(): """ Returns the anme of a function. """ frame = inspect.getouterframes(inspect.currentframe()) filename = frame[1][1].replace(os.getcwd(), "") line = frame[1][2] - 1 method = frame[1][3] return method def backup_name(filename): """ :param filename: given a filename creates a backup name of the form filename.bak.1. If the filename already exists the number will be increased as much as needed so the file does not exist in the given location. The filename can consists a path and is expanded with ~ and environment variables. :type filename: string :rtype: string """ location = path_expand(filename) n = 0 found = True backup = None while found: n += 1 backup = "{0}.bak.{1}".format(location, n) found = os.path.isfile(backup) return backup def auto_create_version(class_name, version, filename="__init__.py"): """ creates a version number in the __init__.py file. it can be accessed with __version__ :param class_name: :param version: :param filename: :return: """ version_filename = Path( "{classname}/{filename}".format(classname=class_name, filename=filename)) with open(version_filename, "r") as f: content = f.read() if content != '__version__ = "{0}"'.format(version): banner("Updating version to {0}".format(version)) with open(version_filename, "w") as text_file: text_file.write('__version__ = "{0:s}"'.format(version)) def auto_create_requirements(requirements): """ creates a requirement.txt file form the requirements in the list. If the file exists, it get changed only if the requirements in the list are different from the existing file :param requirements: the requirements in a list """ banner("Creating requirements.txt file") try: with open("requirements.txt", "r") as f: file_content = f.read() except: file_content = "" setup_requirements = '\n'.join(requirements) if setup_requirements != file_content: with open("requirements.txt", "w") as text_file: text_file.write(setup_requirements) def copy_files(files_glob, source_dir, dest_dir): """ copies the files to the destination :param files_glob: `*.yaml` :param source_dir: source directory :param dest_dir: destination directory """ files = glob.iglob(os.path.join(source_dir, files_glob)) for filename in files: if os.path.isfile(filename): shutil.copy2(filename, dest_dir) def readfile(filename, mode='r'): """ returns the content of a file :param filename: the filename :return: """ if mode != 'r' and mode != 'rb': Console.error(f"incorrect mode : expected 'r' or 'rb' given {mode}") else: with open(path_expand(filename), mode) as f: content = f.read() f.close() return content def writefile(filename, content): """ writes the content into the file :param filename: the filename :param content: teh content :return: """ with open(path_expand(filename), 'w') as outfile: outfile.write(content) outfile.truncate() def writefd(filename, content, mode='w', flags=os.O_RDWR | os.O_CREAT, mask=0o600): """ writes the content into the file and control permissions :param filename: the full or relative path to the filename :param content: the content being written :param mode: the write mode ('w') or write bytes mode ('wb') :param flags: the os flags that determine the permissions for the file :param mask: the mask that the permissions will be applied to """ if mode != 'w' and mode != 'wb': Console.error(f"incorrect mode : expected 'w' or 'wb' given {mode}") with os.fdopen(os.open(filename, flags, mask), mode) as outfile: outfile.write(content) outfile.truncate() outfile.close() def sudo_readfile(filename, split=True, trim=False): """ Reads the content of the file as sudo and returns the result :param filename: the filename :type filename: str :param split: uf true returns a list of lines :type split: bool :param trim: trim trailing whitespace. This is useful to prevent empty string entries when splitting by '\n' :type trim: bool :return: the content :rtype: str or list """ result = subprocess.getoutput(f"sudo cat {filename}") if trim: result = result.rstrip() if split: result = result.split('\n') return result # Reference: http://interactivepython.org/runestone/static/everyday/2013/01/3_password.html def generate_password(length=8, lower=True, upper=True, number=True): """ generates a simple password. We should not really use this in production. :param length: the length of the password :param lower: True of lower case characters are allowed :param upper: True if upper case characters are allowed :param number: True if numbers are allowed :return: """ lletters = "abcdefghijklmnopqrstuvwxyz" uletters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # This doesn't guarantee both lower and upper cases will show up alphabet = lletters + uletters digit = "0123456789" mypw = "" def _random_character(texts): return texts[random.randrange(len(texts))] if not lower: alphabet = uletters elif not upper: alphabet = lletters for i in range(length): # last half length will be filled with numbers if number and i >= int(length / 2): mypw = mypw + _random_character(digit) else: mypw = mypw + _random_character(alphabet) return mypw def str_bool(value): return str(value).lower() in ['yes', '1', 'y', 'true', 't']
cloudmesh/common/util.py
codereval_python_data_145
Given a sequence of path fragments or patterns as passed to `--find`, transform all path fragments into glob patterns. Pass through existing patterns untouched. For example, given find_paths of: ['foo.txt', 'pp:root/somedir'] ... transform that into: ['sh:**/*foo.txt*/**', 'pp:root/somedir'] import re def make_find_paths(find_paths): ''' Given a sequence of path fragments or patterns as passed to `--find`, transform all path fragments into glob patterns. Pass through existing patterns untouched. For example, given find_paths of: ['foo.txt', 'pp:root/somedir'] ... transform that into: ['sh:**/*foo.txt*/**', 'pp:root/somedir'] ''' return tuple( find_path if re.compile(r'([-!+RrPp] )|(\w\w:)').match(find_path) else f'sh:**/*{find_path}*/**' for find_path in find_paths ) import copy import logging import re from borgmatic.borg.flags import make_flags, make_flags_from_arguments from borgmatic.execute import execute_command logger = logging.getLogger(__name__) def resolve_archive_name(repository, archive, storage_config, local_path='borg', remote_path=None): ''' Given a local or remote repository path, an archive name, a storage config dict, a local Borg path, and a remote Borg path, simply return the archive name. But if the archive name is "latest", then instead introspect the repository for the latest archive and return its name. Raise ValueError if "latest" is given but there are no archives in the repository. ''' if archive != "latest": return archive lock_wait = storage_config.get('lock_wait', None) full_command = ( (local_path, 'list') + (('--info',) if logger.getEffectiveLevel() == logging.INFO else ()) + (('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) else ()) + make_flags('remote-path', remote_path) + make_flags('lock-wait', lock_wait) + make_flags('last', 1) + ('--short', repository) ) output = execute_command(full_command, output_log_level=None, borg_local_path=local_path) try: latest_archive = output.strip().splitlines()[-1] except IndexError: raise ValueError('No archives found in the repository') logger.debug('{}: Latest archive is {}'.format(repository, latest_archive)) return latest_archive MAKE_FLAGS_EXCLUDES = ('repository', 'archive', 'successful', 'paths', 'find_paths') def make_list_command( repository, storage_config, list_arguments, local_path='borg', remote_path=None ): ''' Given a local or remote repository path, a storage config dict, the arguments to the list action, and local and remote Borg paths, return a command as a tuple to list archives or paths within an archive. ''' lock_wait = storage_config.get('lock_wait', None) return ( (local_path, 'list') + ( ('--info',) if logger.getEffectiveLevel() == logging.INFO and not list_arguments.json else () ) + ( ('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) and not list_arguments.json else () ) + make_flags('remote-path', remote_path) + make_flags('lock-wait', lock_wait) + make_flags_from_arguments(list_arguments, excludes=MAKE_FLAGS_EXCLUDES,) + ( ('::'.join((repository, list_arguments.archive)),) if list_arguments.archive else (repository,) ) + (tuple(list_arguments.paths) if list_arguments.paths else ()) ) def make_find_paths(find_paths): ''' Given a sequence of path fragments or patterns as passed to `--find`, transform all path fragments into glob patterns. Pass through existing patterns untouched. For example, given find_paths of: ['foo.txt', 'pp:root/somedir'] ... transform that into: ['sh:**/*foo.txt*/**', 'pp:root/somedir'] ''' return tuple( find_path if re.compile(r'([-!+RrPp] )|(\w\w:)').match(find_path) else f'sh:**/*{find_path}*/**' for find_path in find_paths ) def list_archives(repository, storage_config, list_arguments, local_path='borg', remote_path=None): ''' Given a local or remote repository path, a storage config dict, the arguments to the list action, and local and remote Borg paths, display the output of listing Borg archives in the repository or return JSON output. Or, if an archive name is given, list the files in that archive. Or, if list_arguments.find_paths are given, list the files by searching across multiple archives. ''' # If there are any paths to find (and there's not a single archive already selected), start by # getting a list of archives to search. if list_arguments.find_paths and not list_arguments.archive: repository_arguments = copy.copy(list_arguments) repository_arguments.archive = None repository_arguments.json = False repository_arguments.format = None # Ask Borg to list archives. Capture its output for use below. archive_lines = tuple( execute_command( make_list_command( repository, storage_config, repository_arguments, local_path, remote_path ), output_log_level=None, borg_local_path=local_path, ) .strip('\n') .split('\n') ) else: archive_lines = (list_arguments.archive,) # For each archive listed by Borg, run list on the contents of that archive. for archive_line in archive_lines: try: archive = archive_line.split()[0] except (AttributeError, IndexError): archive = None if archive: logger.warning(archive_line) archive_arguments = copy.copy(list_arguments) archive_arguments.archive = archive main_command = make_list_command( repository, storage_config, archive_arguments, local_path, remote_path ) + make_find_paths(list_arguments.find_paths) output = execute_command( main_command, output_log_level=None if list_arguments.json else logging.WARNING, borg_local_path=local_path, ) if list_arguments.json: return output
borgmatic/borg/list.py
codereval_python_data_146
returns True if you run in a Windows gitbash :return: True if gitbash import os def is_gitbash(): """ returns True if you run in a Windows gitbash :return: True if gitbash """ try: exepath = os.environ['EXEPATH'] return "Git" in exepath except: return False import subprocess import collections import glob import inspect import os import random import re import shutil import tempfile import time from contextlib import contextmanager import sys import psutil import requests from pathlib import Path from cloudmesh.common.console import Console from cloudmesh.common.systeminfo import is_gitbash, is_cmd_exe import pyfiglet import socket import platform try: collectionsAbc = collections.abc except AttributeError: collectionsAbc = collections @contextmanager def tempdir(*args, **kwargs): """A contextmanager to work in an auto-removed temporary directory Arguments are passed through to tempfile.mkdtemp example: >>> with tempdir() as path: ... pass """ d = tempfile.mkdtemp(*args, **kwargs) try: yield d finally: shutil.rmtree(d) def check_root(dryrun=False, terminate=True): """ check if I am the root user. If not, simply exits the program. :param dryrun: if set to true, does not terminate if not root user :type dryrun: bool :param terminate: terminates if not root user and dryrun is False :type terminate: bool """ uid = os.getuid() if uid == 0: Console.ok("You are executing as a root user") else: Console.error("You do not run as root") if terminate and not dryrun: sys.exit() def exponential_backoff(fn, sleeptime_s_max=30 * 60): """ Calls `fn` until it returns True, with an exponentially increasing wait time between calls :param fn: the function to be called that returns Truw or False :type fn: object :param sleeptime_s_max: the sleep time in milliseconds :type sleeptime_s_max: int :return: None """ sleeptime_ms = 500 while True: if fn(): return True else: print('Sleeping {} ms'.format(sleeptime_ms)) time.sleep(sleeptime_ms / 1000.0) sleeptime_ms *= 2 if sleeptime_ms / 1000.0 > sleeptime_s_max: return False def download(source, destination, force=False): """ Downloads the file from source to destination For large files, see cloudmesh.common.Shell.download :param source: The http source :param destination: The destination in the file system :param force: If True the file will be downloaded even if it already exists """ if os.path.isfile(destination) and not force: Console.warning(f"File {destination} already exists. " "Skipping download ...") else: directory = os.path.dirname(destination) Path(directory).mkdir(parents=True, exist_ok=True) r = requests.get(source, allow_redirects=True) open(destination, 'wb').write(r.content) def search(lines, pattern): """ return all lines that match the pattern #TODO: we need an example :param lines: :param pattern: :return: """ p = pattern.replace("*", ".*") test = re.compile(p) result = [] for l in lines: # noqa: E741 if test.search(l): result.append(l) return result def grep(pattern, filename): """Very simple grep that returns the first matching line in a file. String matching only, does not do REs as currently implemented. """ try: # for line in file # if line matches pattern: # return line return next((L for L in open(filename) if L.find(pattern) >= 0)) except StopIteration: return '' def is_local(host): """ Checks if the host is the localhost :param host: The hostname or ip :return: True if the host is the localhost """ return host in ["127.0.0.1", "localhost", socket.gethostname(), # just in case socket.gethostname() does not work we also try the following: platform.node(), socket.gethostbyaddr(socket.gethostname())[0] ] # noinspection PyPep8 def is_gitbash(): """ returns True if you run in a Windows gitbash :return: True if gitbash """ try: exepath = os.environ['EXEPATH'] return "Git" in exepath except: return False def is_powershell(): """ True if you run in powershell :return: True if you run in powershell """ # psutil.Process(parent_pid).name() returns - # cmd.exe for CMD # powershell.exe for powershell # bash.exe for git bash return (psutil.Process(os.getppid()).name() == "powershell.exe") def is_cmd_exe(): """ return True if you run in a Windows CMD :return: True if you run in CMD """ if is_gitbash(): return False else: try: return os.environ['OS'] == 'Windows_NT' except: return False def path_expand(text): """ returns a string with expanded variable. :param text: the path to be expanded, which can include ~ and environment variables :param text: string """ result = os.path.expandvars(os.path.expanduser(text)) if result.startswith("./"): result = result.replace(".", os.getcwd(), 1) if is_gitbash() or is_cmd_exe(): result = result.replace("/", "\\") return result def convert_from_unicode(data): """ converts unicode data to a string :param data: the data to convert :return: """ # if isinstance(data, basestring): if isinstance(data, str): return str(data) elif isinstance(data, collectionsAbc.Mapping): return dict(map(convert_from_unicode, data.items())) elif isinstance(data, collectionsAbc.Iterable): return type(data)(map(convert_from_unicode, data)) else: return data def yn_choice(message, default='y', tries=None): """asks for a yes/no question. :param tries: the number of tries :param message: the message containing the question :param default: the default answer """ # http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input""" choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N' if tries is None: choice = input(f"{message} ({choices}) ") values = ('y', 'yes', '') if default == 'y' else ('y', 'yes') return True if choice.strip().lower() in values else False else: while tries > 0: choice = input(f"{message} ({choices}) ('q' to discard)") choice = choice.strip().lower() if choice in ['y', 'yes']: return True elif choice in ['n', 'no', 'q']: return False else: print("Invalid input...") tries -= 1 def str_banner(txt=None, c="-", prefix="#", debug=True, label=None, color="BLUE", padding=False, figlet=False, font="big"): """ prints a banner of the form with a frame of # around the txt:: # -------------------------- # txt # -------------------------- :param color: prints in the given color :param label: adds a label :param debug: prints only if debug is true :param txt: a text message to be printed :type txt: string :param c: the character used instead of c :type c: character """ output = "" if debug: output = "\n" output += prefix + " " + 70 * c + "\n" if padding: output += prefix + "\n" if label is not None: output += prefix + " " + label + "\n" output += prefix + " " + 70 * c + "\n" if txt is not None: if figlet: txt = pyfiglet.figlet_format(txt, font=font) for line in txt.splitlines(): output += prefix + " " + line + "\n" if padding: output += prefix + "\n" output += prefix + " " + 70 * c + "\n" return output def banner(txt=None, c="-", prefix="#", debug=True, label=None, color="BLUE", padding=False, figlet=False, font="big"): """ prints a banner of the form with a frame of # around the txt:: # -------------------------- # txt # -------------------------- :param color: prints in the given color :param label: adds a label :param debug: prints only if debug is true :param txt: a text message to be printed :type txt: string :param c: the character used instead of c :type c: character :param padding: ads additional comment line around the text so the banner is larger :type padding: bool """ output = str_banner(txt=txt, c=c, prefix=prefix, debug=debug, label=label, color=color, padding=padding, figlet=figlet, font=font) Console.cprint(color, "", output) # noinspection PyPep8Naming def HEADING(txt=None, c="#", color="HEADER"): """ Prints a message to stdout with #### surrounding it. This is useful for pytests to better distinguish them. :param c: uses the given char to wrap the header :param txt: a text message to be printed :type txt: string """ frame = inspect.getouterframes(inspect.currentframe()) filename = frame[1][1].replace(os.getcwd(), "") line = frame[1][2] - 1 method = frame[1][3] if txt is None: msg = "{} {} {}".format(method, filename, line) else: msg = "{}\n {} {} {}".format(txt, method, filename, line) print() banner(msg, c=c, color=color) # noinspection PyPep8Naming def FUNCTIONNAME(): """ Returns the anme of a function. """ frame = inspect.getouterframes(inspect.currentframe()) filename = frame[1][1].replace(os.getcwd(), "") line = frame[1][2] - 1 method = frame[1][3] return method def backup_name(filename): """ :param filename: given a filename creates a backup name of the form filename.bak.1. If the filename already exists the number will be increased as much as needed so the file does not exist in the given location. The filename can consists a path and is expanded with ~ and environment variables. :type filename: string :rtype: string """ location = path_expand(filename) n = 0 found = True backup = None while found: n += 1 backup = "{0}.bak.{1}".format(location, n) found = os.path.isfile(backup) return backup def auto_create_version(class_name, version, filename="__init__.py"): """ creates a version number in the __init__.py file. it can be accessed with __version__ :param class_name: :param version: :param filename: :return: """ version_filename = Path( "{classname}/{filename}".format(classname=class_name, filename=filename)) with open(version_filename, "r") as f: content = f.read() if content != '__version__ = "{0}"'.format(version): banner("Updating version to {0}".format(version)) with open(version_filename, "w") as text_file: text_file.write('__version__ = "{0:s}"'.format(version)) def auto_create_requirements(requirements): """ creates a requirement.txt file form the requirements in the list. If the file exists, it get changed only if the requirements in the list are different from the existing file :param requirements: the requirements in a list """ banner("Creating requirements.txt file") try: with open("requirements.txt", "r") as f: file_content = f.read() except: file_content = "" setup_requirements = '\n'.join(requirements) if setup_requirements != file_content: with open("requirements.txt", "w") as text_file: text_file.write(setup_requirements) def copy_files(files_glob, source_dir, dest_dir): """ copies the files to the destination :param files_glob: `*.yaml` :param source_dir: source directory :param dest_dir: destination directory """ files = glob.iglob(os.path.join(source_dir, files_glob)) for filename in files: if os.path.isfile(filename): shutil.copy2(filename, dest_dir) def readfile(filename, mode='r'): """ returns the content of a file :param filename: the filename :return: """ if mode != 'r' and mode != 'rb': Console.error(f"incorrect mode : expected 'r' or 'rb' given {mode}") else: with open(path_expand(filename), mode) as f: content = f.read() f.close() return content def writefile(filename, content): """ writes the content into the file :param filename: the filename :param content: teh content :return: """ with open(path_expand(filename), 'w') as outfile: outfile.write(content) outfile.truncate() def writefd(filename, content, mode='w', flags=os.O_RDWR | os.O_CREAT, mask=0o600): """ writes the content into the file and control permissions :param filename: the full or relative path to the filename :param content: the content being written :param mode: the write mode ('w') or write bytes mode ('wb') :param flags: the os flags that determine the permissions for the file :param mask: the mask that the permissions will be applied to """ if mode != 'w' and mode != 'wb': Console.error(f"incorrect mode : expected 'w' or 'wb' given {mode}") with os.fdopen(os.open(filename, flags, mask), mode) as outfile: outfile.write(content) outfile.truncate() outfile.close() def sudo_readfile(filename, split=True, trim=False): """ Reads the content of the file as sudo and returns the result :param filename: the filename :type filename: str :param split: uf true returns a list of lines :type split: bool :param trim: trim trailing whitespace. This is useful to prevent empty string entries when splitting by '\n' :type trim: bool :return: the content :rtype: str or list """ result = subprocess.getoutput(f"sudo cat {filename}") if trim: result = result.rstrip() if split: result = result.split('\n') return result # Reference: http://interactivepython.org/runestone/static/everyday/2013/01/3_password.html def generate_password(length=8, lower=True, upper=True, number=True): """ generates a simple password. We should not really use this in production. :param length: the length of the password :param lower: True of lower case characters are allowed :param upper: True if upper case characters are allowed :param number: True if numbers are allowed :return: """ lletters = "abcdefghijklmnopqrstuvwxyz" uletters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # This doesn't guarantee both lower and upper cases will show up alphabet = lletters + uletters digit = "0123456789" mypw = "" def _random_character(texts): return texts[random.randrange(len(texts))] if not lower: alphabet = uletters elif not upper: alphabet = lletters for i in range(length): # last half length will be filled with numbers if number and i >= int(length / 2): mypw = mypw + _random_character(digit) else: mypw = mypw + _random_character(alphabet) return mypw def str_bool(value): return str(value).lower() in ['yes', '1', 'y', 'true', 't']
cloudmesh/common/util.py
codereval_python_data_147
Given a target config filename and rendered config YAML, write it out to file. Create any containing directories as needed. But if the file already exists and overwrite is False, abort before writing anything. import os def write_configuration(config_filename, rendered_config, mode=0o600, overwrite=False): ''' Given a target config filename and rendered config YAML, write it out to file. Create any containing directories as needed. But if the file already exists and overwrite is False, abort before writing anything. ''' if not overwrite and os.path.exists(config_filename): return FileExistsError # raise FileExistsError( # '{} already exists. Aborting. Use --overwrite to replace the file.'.format( # config_filename # ) # ) try: os.makedirs(os.path.dirname(config_filename), mode=0o700) except (FileExistsError, FileNotFoundError): pass with open(config_filename, 'w') as config_file: config_file.write(rendered_config) os.chmod(config_filename, mode) return rendered_config import collections import io import os import re from ruamel import yaml from borgmatic.config import load, normalize INDENT = 4 SEQUENCE_INDENT = 2 def _insert_newline_before_comment(config, field_name): ''' Using some ruamel.yaml black magic, insert a blank line in the config right before the given field and its comments. ''' config.ca.items[field_name][1].insert( 0, yaml.tokens.CommentToken('\n', yaml.error.CommentMark(0), None) ) def _schema_to_sample_configuration(schema, level=0, parent_is_sequence=False): ''' Given a loaded configuration schema, generate and return sample config for it. Include comments for each section based on the schema "description". ''' schema_type = schema.get('type') example = schema.get('example') if example is not None: return example if schema_type == 'array': config = yaml.comments.CommentedSeq( [_schema_to_sample_configuration(schema['items'], level, parent_is_sequence=True)] ) add_comments_to_configuration_sequence(config, schema, indent=(level * INDENT)) elif schema_type == 'object': config = yaml.comments.CommentedMap( [ (field_name, _schema_to_sample_configuration(sub_schema, level + 1)) for field_name, sub_schema in schema['properties'].items() ] ) indent = (level * INDENT) + (SEQUENCE_INDENT if parent_is_sequence else 0) add_comments_to_configuration_object( config, schema, indent=indent, skip_first=parent_is_sequence ) else: raise ValueError('Schema at level {} is unsupported: {}'.format(level, schema)) return config def _comment_out_line(line): # If it's already is commented out (or empty), there's nothing further to do! stripped_line = line.lstrip() if not stripped_line or stripped_line.startswith('#'): return line # Comment out the names of optional sections, inserting the '#' after any indent for aesthetics. matches = re.match(r'(\s*)', line) indent_spaces = matches.group(0) if matches else '' count_indent_spaces = len(indent_spaces) return '# '.join((indent_spaces, line[count_indent_spaces:])) def _comment_out_optional_configuration(rendered_config): ''' Post-process a rendered configuration string to comment out optional key/values, as determined by a sentinel in the comment before each key. The idea is that the pre-commented configuration prevents the user from having to comment out a bunch of configuration they don't care about to get to a minimal viable configuration file. Ideally ruamel.yaml would support commenting out keys during configuration generation, but it's not terribly easy to accomplish that way. ''' lines = [] optional = False for line in rendered_config.split('\n'): # Upon encountering an optional configuration option, comment out lines until the next blank # line. if line.strip().startswith('# {}'.format(COMMENTED_OUT_SENTINEL)): optional = True continue # Hit a blank line, so reset commenting. if not line.strip(): optional = False lines.append(_comment_out_line(line) if optional else line) return '\n'.join(lines) def render_configuration(config): ''' Given a config data structure of nested OrderedDicts, render the config as YAML and return it. ''' dumper = yaml.YAML() dumper.indent(mapping=INDENT, sequence=INDENT + SEQUENCE_INDENT, offset=INDENT) rendered = io.StringIO() dumper.dump(config, rendered) return rendered.getvalue() def write_configuration(config_filename, rendered_config, mode=0o600, overwrite=False): ''' Given a target config filename and rendered config YAML, write it out to file. Create any containing directories as needed. But if the file already exists and overwrite is False, abort before writing anything. ''' if not overwrite and os.path.exists(config_filename): raise FileExistsError( '{} already exists. Aborting. Use --overwrite to replace the file.'.format( config_filename ) ) try: os.makedirs(os.path.dirname(config_filename), mode=0o700) except (FileExistsError, FileNotFoundError): pass with open(config_filename, 'w') as config_file: config_file.write(rendered_config) os.chmod(config_filename, mode) def add_comments_to_configuration_sequence(config, schema, indent=0): ''' If the given config sequence's items are object, then mine the schema for the description of the object's first item, and slap that atop the sequence. Indent the comment the given number of characters. Doing this for sequences of maps results in nice comments that look like: ``` things: # First key description. Added by this function. - key: foo # Second key description. Added by add_comments_to_configuration_object(). other: bar ``` ''' if schema['items'].get('type') != 'object': return for field_name in config[0].keys(): field_schema = schema['items']['properties'].get(field_name, {}) description = field_schema.get('description') # No description to use? Skip it. if not field_schema or not description: return config[0].yaml_set_start_comment(description, indent=indent) # We only want the first key's description here, as the rest of the keys get commented by # add_comments_to_configuration_object(). return REQUIRED_SECTION_NAMES = {'location', 'retention'} REQUIRED_KEYS = {'source_directories', 'repositories', 'keep_daily'} COMMENTED_OUT_SENTINEL = 'COMMENT_OUT' def add_comments_to_configuration_object(config, schema, indent=0, skip_first=False): ''' Using descriptions from a schema as a source, add those descriptions as comments to the given config mapping, before each field. Indent the comment the given number of characters. ''' for index, field_name in enumerate(config.keys()): if skip_first and index == 0: continue field_schema = schema['properties'].get(field_name, {}) description = field_schema.get('description', '').strip() # If this is an optional key, add an indicator to the comment flagging it to be commented # out from the sample configuration. This sentinel is consumed by downstream processing that # does the actual commenting out. if field_name not in REQUIRED_SECTION_NAMES and field_name not in REQUIRED_KEYS: description = ( '\n'.join((description, COMMENTED_OUT_SENTINEL)) if description else COMMENTED_OUT_SENTINEL ) # No description to use? Skip it. if not field_schema or not description: # pragma: no cover continue config.yaml_set_comment_before_after_key(key=field_name, before=description, indent=indent) if index > 0: _insert_newline_before_comment(config, field_name) RUAMEL_YAML_COMMENTS_INDEX = 1 def remove_commented_out_sentinel(config, field_name): ''' Given a configuration CommentedMap and a top-level field name in it, remove any "commented out" sentinel found at the end of its YAML comments. This prevents the given field name from getting commented out by downstream processing that consumes the sentinel. ''' try: last_comment_value = config.ca.items[field_name][RUAMEL_YAML_COMMENTS_INDEX][-1].value except KeyError: return if last_comment_value == '# {}\n'.format(COMMENTED_OUT_SENTINEL): config.ca.items[field_name][RUAMEL_YAML_COMMENTS_INDEX].pop() def merge_source_configuration_into_destination(destination_config, source_config): ''' Deep merge the given source configuration dict into the destination configuration CommentedMap, favoring values from the source when there are collisions. The purpose of this is to upgrade configuration files from old versions of borgmatic by adding new configuration keys and comments. ''' if not source_config: return destination_config if not destination_config or not isinstance(source_config, collections.abc.Mapping): return source_config for field_name, source_value in source_config.items(): # Since this key/value is from the source configuration, leave it uncommented and remove any # sentinel that would cause it to get commented out. remove_commented_out_sentinel(destination_config, field_name) # This is a mapping. Recurse for this key/value. if isinstance(source_value, collections.abc.Mapping): destination_config[field_name] = merge_source_configuration_into_destination( destination_config[field_name], source_value ) continue # This is a sequence. Recurse for each item in it. if isinstance(source_value, collections.abc.Sequence) and not isinstance(source_value, str): destination_value = destination_config[field_name] destination_config[field_name] = yaml.comments.CommentedSeq( [ merge_source_configuration_into_destination( destination_value[index] if index < len(destination_value) else None, source_item, ) for index, source_item in enumerate(source_value) ] ) continue # This is some sort of scalar. Simply set it into the destination. destination_config[field_name] = source_config[field_name] return destination_config def generate_sample_configuration( source_filename, destination_filename, schema_filename, overwrite=False ): ''' Given an optional source configuration filename, and a required destination configuration filename, the path to a schema filename in a YAML rendition of the JSON Schema format, and whether to overwrite a destination file, write out a sample configuration file based on that schema. If a source filename is provided, merge the parsed contents of that configuration into the generated configuration. ''' schema = yaml.round_trip_load(open(schema_filename)) source_config = None if source_filename: source_config = load.load_configuration(source_filename) normalize.normalize(source_config) destination_config = merge_source_configuration_into_destination( _schema_to_sample_configuration(schema), source_config ) write_configuration( destination_filename, _comment_out_optional_configuration(render_configuration(destination_config)), overwrite=overwrite, )
borgmatic/config/generate.py
codereval_python_data_148
converts a script to one line command. THis is useful to run a single ssh command and pass a one line script. :param script: :return: import textwrap def oneline(script, seperator=" && "): """ converts a script to one line command. THis is useful to run a single ssh command and pass a one line script. :param script: :return: """ return seperator.join(textwrap.dedent(script).strip().splitlines()) """ A convenient method to execute shell commands and return their output. Note: that this method requires that the command be completely execute before the output is returned. FOr many activities in cloudmesh this is sufficient. """ import errno import glob import os import platform as os_platform import requests import shlex import shutil import subprocess import sys import textwrap import zipfile from pathlib import Path from pipes import quote from sys import platform from tqdm import tqdm import psutil from cloudmesh.common.StopWatch import StopWatch from cloudmesh.common.console import Console from cloudmesh.common.dotdict import dotdict from cloudmesh.common.systeminfo import get_platform from cloudmesh.common.util import path_expand from cloudmesh.common.util import readfile # from functools import wraps # def timer(func): # @wraps(func) # def wrapper(*args,**kwargs): # print(f"{func.__name__!r} begins") # start_time = time.time() # result = func(*args,**kwargs) # print(f"{func.__name__!r} ends in {time.time()-start_time} secs") # return result # return wrapper # def NotImplementedInWindows(f): # def new_f(*args): # if sys.platform == "win32": # Console.error("The method {f.__name__} is not implemented in Windows," # " please implement, and/or submit an issue.") # sys.exit() # f(args) # return new_f def windows_not_supported(f): def wrapper(*args, **kwargs): host = get_platform() if host == "windows": Console.error("Not supported on windows") return "" else: return f(*args, **kwargs) return wrapper def NotImplementedInWindows(): if sys.platform == "win32": Console.error(f"The method {__name__} is not implemented in Windows.") sys.exit() class Brew(object): @classmethod def install(cls, name): r = Shell.brew("install", name) print(r) if "already satisfied: " + name in r: print(name, "... already installed") Console.ok(r) elif "Successfully installed esptool": print(name, "... installed") Console.ok(r) else: print(name, "... error") Console.error(r) @classmethod def version(cls, name): r = Shell.brew("ls", "--version", "name") print(r) class Pip(object): @classmethod def install(cls, name): r = Shell.pip("install", name) if f"already satisfied: {name}" in r: print(name, "... already installed") Console.ok(r) elif f"Successfully installed {name}": print(name, "... installed") Console.ok(r) else: print(name, "... error") Console.error(r) class SubprocessError(Exception): """ Manages the formatting of the error and stdout. This command should not be directly called. Instead use Shell """ def __init__(self, cmd, returncode, stderr, stdout): """ sets the error :param cmd: the command executed :param returncode: the return code :param stderr: the stderr :param stdout: the stdout """ self.cmd = cmd self.returncode = returncode self.stderr = stderr self.stdout = stdout def __str__(self): def indent(lines, amount, ch=' '): """ indent the lines by multiples of ch :param lines: :param amount: :param ch: :return: """ padding = amount * ch return padding + ('\n' + padding).join(lines.split('\n')) cmd = ' '.join(map(quote, self.cmd)) s = '' s += 'Command: %s\n' % cmd s += 'Exit code: %s\n' % self.returncode if self.stderr: s += 'Stderr:\n' + indent(self.stderr, 4) if self.stdout: s += 'Stdout:\n' + indent(self.stdout, 4) return s class Subprocess(object): """ Executes a command. This class should not be directly used, but instead you should use Shell. """ def __init__(self, cmd, cwd=None, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env=None): """ execute the given command :param cmd: the command :param cwd: the directory in which to execute the command :param stderr: the pipe for stderror :param stdout: the pipe for the stdoutput :param env: """ Console.debug_msg('Running cmd: {}'.format(' '.join(map(quote, cmd)))) proc = subprocess.Popen(cmd, stderr=stderr, stdout=stdout, cwd=cwd, env=env) stdout, stderr = proc.communicate() self.returncode = proc.returncode self.stderr = stderr self.stdout = stdout if self.returncode != 0: raise SubprocessError(cmd, self.returncode, self.stderr, self.stdout) class Shell(object): """ The shell class allowing us to conveniently access many operating system commands. TODO: This works well on Linux and OSX, but has not been tested much on Windows """ # TODO: we have not supported cygwin for a while # cygwin_path = 'bin' # i copied fom C:\cygwin\bin command = { 'windows': {}, 'linux': {}, 'darwin': {} } # TODO # # how do we now define dynamically functions based on a list that we want to support # # what we want is where args are multiple unlimited parameters to the function # # def f(args...): # name = get the name from f # a = list of args... # # cls.execute(cmd, arguments=a, capture=True, verbose=False) # # commands = ['ps', 'ls', ..... ] # for c in commands: # generate this command and add to this class dynamically # # or do something more simple # # ls = cls.execute('cmd', args...) @staticmethod def timezone(default="America/Indiana/Indianapolis"): # BUG we need to be able to pass the default from the cmdline host = get_platform() if host == "windows": return default else: # result = Shell.run("ls -l /etc/localtime").strip().split("/") try: result = Shell.run("ls -l /etc/localtime").strip().split("zoneinfo")[1][1:] return result except IndexError as e: return default @staticmethod @windows_not_supported def locale(): try: result = Shell.run('locale').split('\n')[0].split('_')[1].split('.')[0].lower() return result except IndexError as e: Console.warning('Could not determine locale. Defaulting to "us"') return 'us' @staticmethod def run_timed(label, command, encoding=None, service=None): """ runs the command and uses the StopWatch to time it :param label: name of the StopWatch :param command: the command to be executed :param encoding: the encoding :param service: a prefix to the stopwatch label :return: """ _label = str(label) print(_label, command) StopWatch.start(f"{service} {_label}") result = Shell.run(command, encoding) StopWatch.stop(f"{service} {_label}") return str(result) @staticmethod def run(command, exit="; exit 0", encoding='utf-8'): """ executes the command and returns the output as string :param command: :param encoding: :return: """ if sys.platform == "win32": command = f"{command}" else: command = f"{command} {exit}" r = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) if encoding is None or encoding == 'utf-8': return str(r, 'utf-8') else: return r @staticmethod def run2(command, encoding='utf-8'): """ executes the command and returns the output as string. This command also allows execution of 32 bit commands. :param command: the program or command to be executed :param encoding: encoding of the output :return: """ if platform.lower() == 'win32': import ctypes class disable_file_system_redirection: _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection def __enter__(self): self.old_value = ctypes.c_long() self.success = self._disable(ctypes.byref(self.old_value)) def __exit__(self, type, value, traceback): if self.success: self._revert(self.old_value) with disable_file_system_redirection(): command = f"{command}" r = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) if encoding is None or encoding == 'utf-8': return str(r, 'utf-8') else: return r elif platform.lower() == 'linux' or platform.lower() == 'darwin': command = f"{command}" r = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) if encoding is None or encoding == 'utf-8': return str(r, 'utf-8') else: return r @classmethod def execute(cls, cmd, arguments="", shell=False, cwd=None, traceflag=True, witherror=True): """Run Shell command :param witherror: if set to False the error will not be printed :param traceflag: if set to true the trace is printed in case of an error :param cwd: the current working directory in which the command is supposed to be executed. :param shell: if set to true the subprocess is called as part of a shell :param cmd: command to run :param arguments: we do not know yet :return: """ # print "--------------" result = None terminal = cls.terminal_type() # print cls.command os_command = [cmd] if terminal in ['linux', 'windows']: os_command = [cmd] elif 'cygwin' in terminal: if not cls.command_exists(cmd): print("ERROR: the command could not be found", cmd) return else: os_command = [cls.command[cls.operating_system()][cmd]] if isinstance(arguments, list): os_command = os_command + arguments elif isinstance(arguments, tuple): os_command = os_command + list(arguments) elif isinstance(arguments, str): os_command = os_command + arguments.split() else: print("ERROR: Wrong parameter type", type(arguments)) if cwd is None: cwd = os.getcwd() # noinspection PyPep8 try: if shell: if platform.lower() == 'win32': import ctypes class disable_file_system_redirection: _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection def __enter__(self): self.old_value = ctypes.c_long() self.success = self._disable( ctypes.byref(self.old_value)) def __exit__(self, type, value, traceback): if self.success: self._revert(self.old_value) if len(os_command) == 1: os_command = os_command[0].split(' ') with disable_file_system_redirection(): result = subprocess.check_output(os_command, stderr=subprocess.STDOUT, shell=True, cwd=cwd) else: result = subprocess.check_output( os_command, stderr=subprocess.STDOUT, shell=True, cwd=cwd) else: result = subprocess.check_output( os_command, # shell=True, stderr=subprocess.STDOUT, cwd=cwd) except: if witherror: Console.error("problem executing subprocess", traceflag=traceflag) if result is not None: result = result.strip().decode() return result @staticmethod def oneline(script, seperator=" && "): """ converts a script to one line command. THis is useful to run a single ssh command and pass a one line script. :param script: :return: """ return seperator.join(textwrap.dedent(script).strip().splitlines()) @staticmethod def is_root(): """ checks if the user is root :return: True if the user is root :rtype: boolean """ username = subprocess.getoutput("whoami") return username == "root" @staticmethod def rmdir(top, verbose=False): """ removes a directory :param top: removes the directory tree from the top :type top: str :param verbose: unused :type verbose: unused :return: void :rtype: void """ p = Path(top) if not p.exists(): return try: shutil.rmtree(path_expand(top)) except Exception as e: pass # print(e.strerror) # assert False, f"Directory {top} could not be deleted" @staticmethod def dot2svg(filename, engine='dot'): data = { 'engine': engine, 'file': filename.replace(".dot", "") } command = "{engine} -Tsvg {file}.dot > {file}.svg".format(**data) print(command) os.system(command) @staticmethod def browser(filename): data = { 'engine': 'python -m webbrowser', 'file': filename } if 'file:' not in filename and 'http' not in filename: os.system("python -m webbrowser -t file:///{file}".format(**data)) else: os.system("python -m webbrowser -t {file}".format(**data)) @staticmethod def terminal_title(name): """ sets the title of the terminal :param name: the title :type name: str :return: void :rtype: void """ return f'echo -n -e \"\033]0;{name}\007\"' @classmethod def terminal(cls, command='pwd', title=None, kind=None): """ starts a terminal and executes the command in that terminal :param command: the command to be executed :type command: str :param title: the title :type title: str :param kind: for windows you can set "cmd", "powershell", or "gitbash" :type kind: str :return: void :rtype: void """ # title nameing not implemented print(platform) if platform == 'darwin': label = Shell.terminal_title(title) os.system( f"osascript -e 'tell application \"Terminal\" to do script \"{command}\"'" ) elif platform == "linux": # for ubuntu running gnome dist = os_platform.linux_distribution()[0] linux_apps = {'ubuntu': 'gnome-terminal', 'debian':'lxterminal'} os.system(f"{linux_apps[dist]} -e \"bash -c \'{command}; exec $SHELL\'\"") elif platform == "win32": if kind is None: if Path.is_dir(Path(r"C:\Program Files\Git")): kind = "gitbash" kind = kind.lower() if kind == "gitbash": p = subprocess.Popen([r"C:\Program Files\Git\git-bash.exe", "-c", f"{command}"]) return p.pid elif kind == "cmd": Console.error(f"Command not implemented for {kind}") elif kind == "powershell": Console.error(f"Command not implemented for {kind}") else: Console.error("Git bash is not found, please make sure it " "is installed. Other terminals not supported.") raise NotImplementedError else: raise NotImplementedError @classmethod def live(cls, command, cwd=None): if cwd is None: cwd = os.getcwd() process = subprocess.Popen(shlex.split(command), cwd=cwd, stdout=subprocess.PIPE) result = b'' while True: output = process.stdout.read(1) if output == b'' and process.poll() is not None: break if output: result = result + output sys.stdout.write(output.decode("utf-8")) sys.stdout.flush() rc = process.poll() data = dotdict({ "status": rc, "text": output.decode("utf-8") }) return data @classmethod def get_python(cls): """ returns the python and pip version :return: python version, pip version """ python_version = sys.version_info[:3] v_string = [str(i) for i in python_version] python_version_s = '.'.join(v_string) # pip_version = pip.__version__ pip_version = Shell.pip("--version").split()[1] return python_version_s, pip_version @classmethod def check_output(cls, *args, **kwargs): """Thin wrapper around :func:`subprocess.check_output` """ return subprocess.check_output(*args, **kwargs) @classmethod def ls(cls, match="."): """ executes ls with the given arguments :param args: :return: list """ d = glob.glob(match) return d @classmethod # @NotImplementedInWindows def unix_ls(cls, *args): """ executes ls with the given arguments :param args: :return: """ return cls.execute('ls', args) @staticmethod def ps(): """ using psutil to return the process information pid, name and comdline, cmdline may be a list :return: a list of dicts of process information """ found = [] for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline']) except psutil.NoSuchProcess: pass else: found.append(pinfo) if len(pinfo) == 0: return None else: return found @classmethod def bash(cls, *args): """ executes bash with the given arguments :param args: :return: """ return cls.execute('bash', args) @classmethod # @NotImplementedInWindows def brew(cls, *args): """ executes bash with the given arguments :param args: :return: """ NotImplementedInWindows() return cls.execute('brew', args) @classmethod # @NotImplementedInWindows def cat(cls, *args): """ executes cat with the given arguments :param args: :return: """ NotImplementedInWindows() # TODO: replace with file read and reading the content. We need to deal # with line endings and add maybe a flag endings="unix"/"windows". # check the finction readlines. return cls.execute('cat', args) @classmethod def git(cls, *args): """ executes git with the given arguments :param args: :return: """ NotImplementedInWindows() return cls.execute('git', args) # noinspection PyPep8Naming @classmethod def VBoxManage(cls, *args): """ executes VboxManage with the given arguments :param args: :return: """ if platform == "darwin": command = "/Applications/VirtualBox.app/Contents/MacOS/VBoxManage" else: command = 'VBoxManage' return cls.execute(command, args) @classmethod def blockdiag(cls, *args): """ executes blockdiag with the given arguments :param args: :return: """ return cls.execute('blockdiag', args) @classmethod def cm(cls, *args): """ executes cm with the given arguments :param args: :return: """ return cls.execute('cm', args) @classmethod def cms(cls, *args): """ executes cm with the given arguments :param args: :return: """ return cls.execute('cms', args) @classmethod def cmsd(cls, *args): """ executes cm with the given arguments :param args: :return: """ return cls.execute('cmsd', args) @classmethod # @NotImplementedInWindows def head(cls, *args): """ executes head with the given arguments :param args: :return: """ NotImplementedInWindows() # TODO: reimplement with readlines return cls.execute('head', args) @classmethod def keystone(cls, *args): """ executes keystone with the given arguments :param args: :return: """ return cls.execute('keystone', args) @staticmethod def kill_pid(pid): if sys.platform == 'win32': try: result = Shell.run(f"taskkill /IM {pid} /F") except Exception as e: result = str(e) else: try: result = Shell.kill("-9", pid) except subprocess.CalledProcessError: result = 'server is already down...' return result @classmethod # @NotImplementedInWindows def kill(cls, *args): """ executes kill with the given arguments :param args: :return: """ NotImplementedInWindows() # TODO: use tasklisk, compare to linux return cls.execute('kill', args) @classmethod def download(cls, source, destination, force=False, provider=None, chunk_size=128): """ Given a source url and a destination filename, download the file at the source url to the destination. If provider is None, the request lib is used If provider is 'system', wget, curl, and requests lib are attempted in that order """ destination = path_expand(destination) if os.path.exists(destination) and not force: return destination if provider == 'system': # First try wget wget_return = os.system(f'wget -O {destination} {source}') if wget_return == 0: Console.info('Used wget') return destination # Then curl curl_return = os.system(f'curl -L -o {destination} {source}') if curl_return == 0: Console.info('Used curl') return destination # Default is requests lib. If provider is None, or if provider == 'system' # but wget and curl fail, default here r = requests.get(source, stream=True, allow_redirects=True) total_size = int(r.headers.get('content-length')) with open(destination, 'wb') as fd: with tqdm(total=total_size, unit="B", unit_scale=True, desc=destination, initial=0, ascii=True) as pbar: for chunk in r.iter_content(chunk_size=chunk_size): fd.write(chunk) pbar.update(len(chunk)) return destination @classmethod def mount(cls, *args): """ mounts a given mountpoint to a file :param args: :return: """ return cls.execute('mount', args) @classmethod def umount(cls, *args): """ umounts a given mountpoint to a file :param args: :return: """ return cls.execute('umount', args) @classmethod def nova(cls, *args): """ executes nova with the given arguments :param args: :return: """ return cls.execute('nova', args) @classmethod def ping(cls, host=None, count=1): """ execute ping :param host: the host to ping :param count: the number of pings :return: """ option = '-n' if platform == 'windows' else '-c' return cls.execute('ping', "{option} {count} {host}".format(option=option, count=count, host=host)) @classmethod def pwd(cls, *args): """ executes pwd with the given arguments :param args: :return: """ return os.getcwd() @classmethod def rackdiag(cls, *args): """ executes rackdiag with the given arguments :param args: :return: """ return cls.execute('rackdiag', args) @classmethod # @NotImplementedInWindows def rm(cls, location): """ executes rm tree with the given arguments :param args: :return: """ shutil.rmtree(path_expand(location)) @classmethod def rsync(cls, *args): """ executes rsync with the given arguments :param args: :return: """ return cls.execute('rsync', args) @classmethod def scp(cls, *args): """ executes scp with the given arguments :param args: :return: """ return cls.execute('scp', args) @classmethod # @NotImplementedInWindows def sort(cls, *args): """ executes sort with the given arguments :param args: :return: """ NotImplementedInWindows() # TODO: https://superuser.com/questions/1316317/is-there-a-windows-equivalent-to-the-unix-uniq return cls.execute('sort', args) @classmethod def sh(cls, *args): """ executes sh with the given arguments :param args: :return: """ return cls.execute('sh', args) @classmethod def ssh(cls, *args): """ executes ssh with the given arguments :param args: :return: """ return cls.execute('ssh', args) @classmethod # @NotImplementedInWindows def sudo(cls, *args): """ executes sudo with the given arguments :param args: :return: """ NotImplementedInWindows() # TODO: https://stackoverflow.com/questions/9652720/how-to-run-sudo-command-in-windows return cls.execute('sudo', args) @classmethod # @NotImplementedInWindows def tail(cls, *args): """ executes tail with the given arguments :param args: :return: """ NotImplementedInWindows() # TODO: implement with readlines on a file. return cls.execute('tail', args) @classmethod def vagrant(cls, *args): """ executes vagrant with the given arguments :param args: :return: """ return cls.execute('vagrant', args, shell=True) @classmethod def pandoc(cls, *args): """ executes vagrant with the given arguments :param args: :return: """ return cls.execute('pandoc', args) @classmethod def mongod(cls, *args): """ executes mongod with the given arguments :param args: :return: """ return cls.execute('mongod', args) @classmethod # @NotImplementedInWindows def dialog(cls, *args): """ executes dialof with the given arguments :param args: :return: """ NotImplementedInWindows() return cls.execute('dialog', args) @classmethod def pip(cls, *args): """ executes pip with the given arguments :param args: :return: """ return cls.execute('pip', args) @classmethod # @NotImplementedInWindows def fgrep(cls, *args): """ executes fgrep with the given arguments :param args: :return: """ NotImplementedInWindows() # TODO: see cm_grep return cls.execute('fgrep', args) @classmethod # @NotImplementedInWindows def grep(cls, *args): """ executes grep with the given arguments :param args: :return: """ NotImplementedInWindows() return cls.execute('grep', args) @classmethod def cm_grep(cls, lines, what): """ returns all lines that contain what :param lines: :param what: :return: """ if type(lines) == str: _lines = lines.splitlines() else: _lines = lines result = [] for line in _lines: if what in line: result.append(line) return result @classmethod def remove_line_with(cls, lines, what): """ returns all lines that do not contain what :param lines: :param what: :return: """ if type(lines) == str: _lines = lines.splitlines() else: _lines = lines result = [] for line in _lines: if what not in line: result = result + [line] return result @classmethod def find_lines_with(cls, lines, what): """ returns all lines that contain what :param lines: :param what: :return: """ if type(lines) == str: _lines = lines.splitlines() else: _lines = lines result = [] for line in _lines: if what in line: result = result + [line] return result @classmethod def find_lines_from(cls, lines, what): """ returns all lines that come after a particular line :param lines: :param what: :return: """ if type(lines) == str: _lines = lines.splitlines() else: _lines = lines result = [] found = False for line in _lines: found = found or what in line if found: result = result + [line] return result @classmethod def find_lines_between(cls, lines, what_from, what_to): """ returns all lines that come between the markers :param lines: :param what: :return: """ select = Shell.find_lines_from(lines, what_from) select = Shell.find_lines_to(select, what_to) return select @classmethod def find_lines_to(cls, lines, what): """ returns all lines that come before a particular line :param lines: :param what: :return: """ if type(lines) == str: _lines = lines.splitlines() else: _lines = lines result = [] found = True for line in _lines: if what in line: return result else: result = result + [line] return result @classmethod def terminal_type(cls): """ returns darwin, cygwin, cmd, or linux """ what = sys.platform kind = 'UNDEFINED_TERMINAL_TYPE' if 'linux' in what: kind = 'linux' elif 'darwin' in what: kind = 'darwin' elif 'cygwin' in what: kind = 'cygwin' elif what in ['windows', 'win32']: kind = 'windows' return kind @classmethod def which(cls, command): """ returns the path of the command with which :param command: teh command :return: the path """ return shutil.which(command) @classmethod def command_exists(cls, name): """ returns True if the command exists :param name: :return: """ return cls.which(name) is not None @classmethod def operating_system(cls): """ the name of the os :return: the name of the os """ return platform @staticmethod def get_pid(name, service="psutil"): pid = None for proc in psutil.process_iter(): if name in proc.name(): pid = proc.pid return pid @staticmethod def cms(command, encoding='utf-8'): return Shell.run("cms " + command, encoding=encoding) @classmethod def check_python(cls): """ checks if the python version is supported :return: True if it is supported """ python_version = sys.version_info[:3] v_string = [str(i) for i in python_version] python_version_s = '.'.join(v_string) if python_version[0] == 2: print( "You are running an unsupported version of python: {:}".format( python_version_s)) # python_version_s = '.'.join(v_string) # if (python_version[0] == 2) and (python_version[1] >= 7) and (python_version[2] >= 9): # print("You are running an unsupported version of python: {:}".format(python_version_s)) # else: # print("WARNING: You are running an unsupported version of python: {:}".format(python_version_s)) # print(" We recommend you update your python") elif python_version[0] == 3: if (python_version[0] == 3) and (python_version[1] >= 7) and (python_version[2] >= 0): print( "You are running a supported version of python: {:}".format( python_version_s)) else: print( "WARNING: You are running an unsupported version of python: {:}".format( python_version_s)) print(" We recommend you update your python") # pip_version = pip.__version__ python_version, pip_version = cls.get_python() if int(pip_version.split(".")[0]) >= 19: print("You are running a supported version of pip: " + str( pip_version)) else: print("WARNING: You are running an old version of pip: " + str( pip_version)) print(" We recommend you update your pip with \n") print(" pip install -U pip\n") @classmethod def mkdir(cls, directory): """ creates a directory with all its parents in ots name :param directory: the path of the directory :return: """ directory = path_expand(directory) Path(directory).mkdir(parents=True, exist_ok=True) #try: # os.makedirs(directory) #except OSError as e: # EEXIST (errno 17) occurs under two conditions when the path exists: # - it is a file # - it is a directory # # if it is a file, this is a valid error, otherwise, all # is fine. # if e.errno == errno.EEXIST and os.path.isdir(directory): # pass # else: # raise def unzip(cls, source_filename, dest_dir): """ unzips a file into the destination directory :param source_filename: the source :param dest_dir: the destination directory :return: """ with zipfile.ZipFile(source_filename) as zf: for member in zf.infolist(): # Path traversal defense copied from # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789 words = member.filename.split('/') path = path_expand(dest_dir) for word in words[:-1]: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir, ''): continue path = os.path.join(path, word) zf.extract(member, path) @staticmethod def edit(filename): if platform == 'darwin': os.system("emacs " + filename) elif platform == "windows": os.system("notepad " + filename) else: raise NotImplementedError("Editor not configured for OS") @classmethod # @NotImplementedInWindows def lsb_release(cls): """ executes lsb_release command :param args: :return: """ NotImplementedInWindows() return cls.execute('lsb_release', ['-a']) @classmethod def distribution(cls): """ executes lsb_release command :param args: :return: TODO: needs testing """ machine = platform.lower() result = {"platform": machine, "distribution": None} if machine == "linux": try: release = readfile("/etc/os-release") for line in release.splitlines(): attribute, value = line.split("=", 1) result[attribute] = value if "Debian" in result["NAME"]: result["distribution"] = "debian" elif "Ubuntu" in result["NAME"]: result["distribution"] = "ubuntu" except: try: r = cls.lsb_release() for line in r.split(): if ":" in line: attribute, value = line.split(":", 1) attribute = attribute.strip().replace(" ", "_").lower() value = value.strip() result[attribute] = value result["distribution"] = result["description"].split(" ")[ 0].lower() except: Console.error( f"lsb_release not found for the platform {machine}") raise NotImplementedError elif machine == 'darwin': result["distribution"] = "macos" result["version"] = os_platform.mac_ver()[0] elif machine == 'win32': result["distribution"] = "windows" result["version"] = os_platform.win_ver()[0] else: Console.error(f"not implemented for the platform {machine}") raise NotImplementedError return result def main(): """ a test that should actually be added into a pytest :return: """ print(Shell.terminal_type()) r = Shell.execute('pwd') # copy line replace print(r) # shell.list() # print json.dumps(shell.command, indent=4) # test some commands without args """ for cmd in ['whoami', 'pwd']: r = shell._execute(cmd) print ("---------------------") print ("Command: {:}".format(cmd)) print ("{:}".format(r)) print ("---------------------") """ r = Shell.execute('ls', ["-l", "-a"]) print(r) r = Shell.execute('ls', "-l -a") print(r) if sys.platform != "win32": r = Shell.unix_ls("-aux") print(r) r = Shell.unix_ls("-a", "-u", "-x") print(r) r = Shell.ls("./*.py") print(r) r = Shell.ls("*/*.py") print(r) r = Shell.pwd() print(r) if __name__ == "__main__": main()
cloudmesh/common/Shell.py
codereval_python_data_149
Run a function in a sub-process. Parameters ---------- func : function The function to be run. It must be in a module that is importable. *args : str Any additional command line arguments to be passed in the first argument to ``subprocess.run``. extra_env : dict[str, str] Any additional environment variables to be set for the subprocess. import subprocess def subprocess_run_helper(func, *args, timeout, extra_env=None): """ Run a function in a sub-process. Parameters ---------- func : function The function to be run. It must be in a module that is importable. *args : str Any additional command line arguments to be passed in the first argument to ``subprocess.run``. extra_env : dict[str, str] Any additional environment variables to be set for the subprocess. """ target = func.__name__ module = func.__module__ proc = subprocess.run( [sys.executable, "-c", f"from {module} import {target}; {target}()", *args], env={**os.environ, "SOURCE_DATE_EPOCH": "0", **(extra_env or {})}, timeout=timeout, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) return proc """ Helper functions for testing. """ from pathlib import Path from tempfile import TemporaryDirectory import locale import logging import os import subprocess import sys import matplotlib as mpl from matplotlib import _api _log = logging.getLogger(__name__) def set_font_settings_for_testing(): mpl.rcParams['font.family'] = 'DejaVu Sans' mpl.rcParams['text.hinting'] = 'none' mpl.rcParams['text.hinting_factor'] = 8 def set_reproducibility_for_testing(): mpl.rcParams['svg.hashsalt'] = 'matplotlib' def setup(): # The baseline images are created in this locale, so we should use # it during all of the tests. try: locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') except locale.Error: try: locale.setlocale(locale.LC_ALL, 'English_United States.1252') except locale.Error: _log.warning( "Could not set locale to English/United States. " "Some date-related tests may fail.") mpl.use('Agg') with _api.suppress_matplotlib_deprecation_warning(): mpl.rcdefaults() # Start with all defaults # These settings *must* be hardcoded for running the comparison tests and # are not necessarily the default values as specified in rcsetup.py. set_font_settings_for_testing() set_reproducibility_for_testing() def subprocess_run_helper(func, *args, timeout, extra_env=None): """ Run a function in a sub-process. Parameters ---------- func : function The function to be run. It must be in a module that is importable. *args : str Any additional command line arguments to be passed in the first argument to ``subprocess.run``. extra_env : dict[str, str] Any additional environment variables to be set for the subprocess. """ target = func.__name__ module = func.__module__ proc = subprocess.run( [sys.executable, "-c", f"from {module} import {target}; {target}()", *args], env={**os.environ, "SOURCE_DATE_EPOCH": "0", **(extra_env or {})}, timeout=timeout, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) return proc def _check_for_pgf(texsystem): """ Check if a given TeX system + pgf is available Parameters ---------- texsystem : str The executable name to check """ with TemporaryDirectory() as tmpdir: tex_path = Path(tmpdir, "test.tex") tex_path.write_text(r""" \documentclass{minimal} \usepackage{pgf} \begin{document} \typeout{pgfversion=\pgfversion} \makeatletter \@@end """, encoding="utf-8") try: subprocess.check_call( [texsystem, "-halt-on-error", str(tex_path)], cwd=tmpdir, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except (OSError, subprocess.CalledProcessError): return False return True def _has_tex_package(package): try: mpl.dviread._find_tex_file(f"{package}.sty") return True except FileNotFoundError: return False
lib/matplotlib/testing/__init__.py
codereval_python_data_150
Get the value from environment given a matcher containing a name and an optional default value. If the variable is not defined in environment and no default value is provided, an Error is raised. import os def _resolve_string(matcher): ''' Get the value from environment given a matcher containing a name and an optional default value. If the variable is not defined in environment and no default value is provided, an Error is raised. ''' name, default = matcher.group("name"), matcher.group("default") out = os.getenv(name, default=default) if out is None: raise ValueError("Cannot find variable ${name} in envivonment".format(name=name)) return out import io import os import re import ruamel.yaml _VARIABLE_PATTERN = re.compile(r'(?<!\\)\$\{(?P<name>[A-Za-z0-9_]+)((:?-)(?P<default>[^}]+))?\}') def set_values(config, keys, value): ''' Given a hierarchy of configuration dicts, a sequence of parsed key strings, and a string value, descend into the hierarchy based on the keys to set the value into the right place. ''' if not keys: return first_key = keys[0] if len(keys) == 1: config[first_key] = value return if first_key not in config: config[first_key] = {} set_values(config[first_key], keys[1:], value) def convert_value_type(value): ''' Given a string value, determine its logical type (string, boolean, integer, etc.), and return it converted to that type. Raise ruamel.yaml.error.YAMLError if there's a parse issue with the YAML. ''' return ruamel.yaml.YAML(typ='safe').load(io.StringIO(value)) def parse_overrides(raw_overrides): ''' Given a sequence of configuration file override strings in the form of "section.option=value", parse and return a sequence of tuples (keys, values), where keys is a sequence of strings. For instance, given the following raw overrides: ['section.my_option=value1', 'section.other_option=value2'] ... return this: ( (('section', 'my_option'), 'value1'), (('section', 'other_option'), 'value2'), ) Raise ValueError if an override can't be parsed. ''' if not raw_overrides: return () parsed_overrides = [] for raw_override in raw_overrides: try: raw_keys, value = raw_override.split('=', 1) parsed_overrides.append((tuple(raw_keys.split('.')), convert_value_type(value),)) except ValueError: raise ValueError( f"Invalid override '{raw_override}'. Make sure you use the form: SECTION.OPTION=VALUE" ) except ruamel.yaml.error.YAMLError as error: raise ValueError(f"Invalid override '{raw_override}': {error.problem}") return tuple(parsed_overrides) def apply_overrides(config, raw_overrides): ''' Given a sequence of configuration file override strings in the form of "section.option=value" and a configuration dict, parse each override and set it the configuration dict. ''' overrides = parse_overrides(raw_overrides) for (keys, value) in overrides: set_values(config, keys, value) def _resolve_string(matcher): ''' Get the value from environment given a matcher containing a name and an optional default value. If the variable is not defined in environment and no default value is provided, an Error is raised. ''' name, default = matcher.group("name"), matcher.group("default") out = os.getenv(name, default=default) if out is None: raise ValueError("Cannot find variable ${name} in envivonment".format(name=name)) return out def resolve_env_variables(item): ''' Resolves variables like or ${FOO} from given configuration with values from process environment Supported formats: - ${FOO} will return FOO env variable - ${FOO-bar} or ${FOO:-bar} will return FOO env variable if it exists, else "bar" If any variable is missing in environment and no default value is provided, an Error is raised. ''' if isinstance(item, str): return _VARIABLE_PATTERN.sub(_resolve_string, item) if isinstance(item, list): for i, subitem in enumerate(item): item[i] = resolve_env_variables(subitem) if isinstance(item, dict): for key, value in item.items(): item[key] = resolve_env_variables(value) return item
borgmatic/config/override.py
codereval_python_data_151
Parse an image href into composite parts. :param image_href: href of an image :returns: a tuple of the form (image_id, netloc, use_ssl) :raises ValueError: import urllib def _parse_image_ref(image_href: str) -> Tuple[str, str, bool]: """Parse an image href into composite parts. :param image_href: href of an image :returns: a tuple of the form (image_id, netloc, use_ssl) :raises ValueError: """ url = urllib.parse.urlparse(image_href) netloc = url.netloc image_id = url.path.split('/')[-1] use_ssl = (url.scheme == 'https') return (image_id, netloc, use_ssl) # Copyright 2010 OpenStack Foundation # Copyright 2013 NTT corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Implementation of an image service that uses Glance as the backend""" import copy import itertools import random import shutil import sys import textwrap import time from typing import (Any, Callable, Dict, Iterable, List, # noqa: H301 NoReturn, Optional, Tuple) # noqa: H301 import urllib import urllib.parse import glanceclient import glanceclient.exc from keystoneauth1.loading import session as ks_session from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import timeutils from cinder import context from cinder import exception from cinder.i18n import _ from cinder.image import image_utils from cinder import service_auth image_opts = [ cfg.ListOpt('allowed_direct_url_schemes', default=[], help='A list of url schemes that can be downloaded directly ' 'via the direct_url. Currently supported schemes: ' '[file, cinder].'), cfg.StrOpt('verify_glance_signatures', choices=['disabled', 'enabled'], default='enabled', help=textwrap.dedent( """ Enable image signature verification. Cinder uses the image signature metadata from Glance and verifies the signature of a signed image while downloading that image. There are two options here. 1. ``enabled``: verify when image has signature metadata. 2. ``disabled``: verification is turned off. If the image signature cannot be verified or if the image signature metadata is incomplete when required, then Cinder will not create the volume and update it into an error state. This provides end users with stronger assurances of the integrity of the image data they are using to create volumes. """)), cfg.StrOpt('glance_catalog_info', default='image:glance:publicURL', help='Info to match when looking for glance in the service ' 'catalog. Format is: separated values of the form: ' '<service_type>:<service_name>:<endpoint_type> - ' 'Only used if glance_api_servers are not provided.'), ] glance_core_properties_opts = [ cfg.ListOpt('glance_core_properties', default=['checksum', 'container_format', 'disk_format', 'image_name', 'image_id', 'min_disk', 'min_ram', 'name', 'size'], help='Default core properties of image') ] CONF = cfg.CONF CONF.register_opts(image_opts) CONF.register_opts(glance_core_properties_opts) _SESSION = None LOG = logging.getLogger(__name__) def _parse_image_ref(image_href: str) -> Tuple[str, str, bool]: """Parse an image href into composite parts. :param image_href: href of an image :returns: a tuple of the form (image_id, netloc, use_ssl) :raises ValueError: """ url = urllib.parse.urlparse(image_href) netloc = url.netloc image_id = url.path.split('/')[-1] use_ssl = (url.scheme == 'https') return (image_id, netloc, use_ssl) def _create_glance_client(context: context.RequestContext, netloc: str, use_ssl: bool) -> glanceclient.Client: """Instantiate a new glanceclient.Client object.""" params = {'global_request_id': context.global_id} if use_ssl and CONF.auth_strategy == 'noauth': params = {'insecure': CONF.glance_api_insecure, 'cacert': CONF.glance_ca_certificates_file, 'timeout': CONF.glance_request_timeout, 'split_loggers': CONF.split_loggers } if CONF.auth_strategy == 'keystone': global _SESSION if not _SESSION: config_options = {'insecure': CONF.glance_api_insecure, 'cacert': CONF.glance_ca_certificates_file, 'timeout': CONF.glance_request_timeout, 'cert': CONF.glance_certfile, 'key': CONF.glance_keyfile, 'split_loggers': CONF.split_loggers } _SESSION = ks_session.Session().load_from_options(**config_options) auth = service_auth.get_auth_plugin(context) params['auth'] = auth params['session'] = _SESSION scheme = 'https' if use_ssl else 'http' endpoint = '%s://%s' % (scheme, netloc) return glanceclient.Client('2', endpoint, **params) def get_api_servers(context: context.RequestContext) -> Iterable: """Return Iterable over shuffled api servers. Shuffle a list of glance_api_servers and return an iterator that will cycle through the list, looping around to the beginning if necessary. If CONF.glance_api_servers is None then they will be retrieved from the catalog. """ api_servers = [] api_servers_info = [] if CONF.glance_api_servers is None: info = CONF.glance_catalog_info try: service_type, service_name, endpoint_type = info.split(':') except ValueError: raise exception.InvalidConfigurationValue(_( "Failed to parse the configuration option " "'glance_catalog_info', must be in the form " "<service_type>:<service_name>:<endpoint_type>")) for entry in context.service_catalog: if entry.get('type') == service_type: api_servers.append( entry.get('endpoints')[0].get(endpoint_type)) else: for api_server in CONF.glance_api_servers: api_servers.append(api_server) for api_server in api_servers: if '//' not in api_server: api_server = 'http://' + api_server url = urllib.parse.urlparse(api_server) netloc = url.netloc + url.path use_ssl = (url.scheme == 'https') api_servers_info.append((netloc, use_ssl)) random.shuffle(api_servers_info) return itertools.cycle(api_servers_info) class GlanceClientWrapper(object): """Glance client wrapper class that implements retries.""" def __init__(self, context: Optional[context.RequestContext] = None, netloc: Optional[str] = None, use_ssl: bool = False): self.client: Optional[glanceclient.Client] if netloc is not None: assert context is not None self.client = self._create_static_client(context, netloc, use_ssl) else: self.client = None self.api_servers: Optional[Iterable] = None def _create_static_client(self, context: context.RequestContext, netloc: str, use_ssl: bool) -> glanceclient.Client: """Create a client that we'll use for every call.""" self.netloc = netloc self.use_ssl = use_ssl return _create_glance_client(context, self.netloc, self.use_ssl) def _create_onetime_client( self, context: context.RequestContext) -> glanceclient.Client: """Create a client that will be used for one call.""" if self.api_servers is None: self.api_servers = get_api_servers(context) self.netloc, self.use_ssl = next(self.api_servers) # type: ignore return _create_glance_client(context, self.netloc, self.use_ssl) def call(self, context: context.RequestContext, method: str, *args: Any, **kwargs: str) -> Any: """Call a glance client method. If we get a connection error, retry the request according to CONF.glance_num_retries. """ retry_excs = (glanceclient.exc.ServiceUnavailable, glanceclient.exc.InvalidEndpoint, glanceclient.exc.CommunicationError) num_attempts = 1 + CONF.glance_num_retries glance_controller = kwargs.pop('controller', 'images') store_id = kwargs.pop('store_id', None) base_image_ref = kwargs.pop('base_image_ref', None) for attempt in range(1, num_attempts + 1): client = self.client or self._create_onetime_client(context) keys = ('x-image-meta-store', 'x-openstack-base-image-ref',) values = (store_id, base_image_ref,) headers = {k: v for (k, v) in zip(keys, values) if v is not None} if headers: client.http_client.additional_headers = headers try: controller = getattr(client, glance_controller) return getattr(controller, method)(*args, **kwargs) except retry_excs as e: netloc = self.netloc extra = "retrying" error_msg = _("Error contacting glance server " "'%(netloc)s' for '%(method)s', " "%(extra)s.") if attempt == num_attempts: extra = 'done trying' LOG.exception(error_msg, {'netloc': netloc, 'method': method, 'extra': extra}) raise exception.GlanceConnectionFailed(reason=e) LOG.exception(error_msg, {'netloc': netloc, 'method': method, 'extra': extra}) time.sleep(1) except glanceclient.exc.HTTPOverLimit as e: raise exception.ImageLimitExceeded(e) class GlanceImageService(object): """Provides storage and retrieval of disk image objects within Glance.""" def __init__(self, client: Optional[Any] = None): self._client = client or GlanceClientWrapper() self._image_schema: Optional[glanceclient.v2.schemas.Schema] = None self.temp_images: Optional[image_utils.TemporaryImages] = None def detail(self, context: context.RequestContext, **kwargs: str) -> List[dict]: """Calls out to Glance for a list of detailed image information.""" params = self._extract_query_params(kwargs) try: images = self._client.call(context, 'list', **params) except Exception: _reraise_translated_exception() _images = [] for image in images: if self._is_image_available(context, image): _images.append(self._translate_from_glance(context, image)) return _images def _extract_query_params(self, params: dict) -> Dict[str, Any]: _params = {} accepted_params = ('filters', 'marker', 'limit', 'sort_key', 'sort_dir') for param in accepted_params: if param in params: _params[param] = params.get(param) return _params def list_members(self, context: context.RequestContext, image_id: str) -> List[dict]: """Returns a list of dicts with image member data.""" try: return self._client.call(context, 'list', controller='image_members', image_id=image_id) except Exception: _reraise_translated_image_exception(image_id) def get_stores(self, context: context.RequestContext): """Returns a list of dicts with stores information.""" try: return self._client.call(context, 'get_stores_info') except Exception: _reraise_translated_exception() def show(self, context: context.RequestContext, image_id: str) -> Dict[str, Any]: """Returns a dict with image data for the given opaque image id.""" try: image = self._client.call(context, 'get', image_id) except Exception: _reraise_translated_image_exception(image_id) if not self._is_image_available(context, image): raise exception.ImageNotFound(image_id=image_id) base_image_meta = self._translate_from_glance(context, image) return base_image_meta def get_location(self, context: context.RequestContext, image_id: str) -> Tuple[Optional[str], Any]: """Get backend storage location url. Returns a tuple containing the direct url and locations representing the backend storage location, or (None, None) if these attributes are not shown by Glance. """ try: # direct_url is returned by v2 api client = GlanceClientWrapper() image_meta = client.call(context, 'get', image_id) except Exception: _reraise_translated_image_exception(image_id) if not self._is_image_available(context, image_meta): raise exception.ImageNotFound(image_id=image_id) # some glance stores like nfs only meta data # is stored and returned as locations. # so composite of two needs to be returned. return (getattr(image_meta, 'direct_url', None), getattr(image_meta, 'locations', None)) def add_location(self, context: context.RequestContext, image_id: str, url: str, metadata: dict) -> dict: """Add a backend location url to an image. Returns a dict containing image metadata on success. """ client = GlanceClientWrapper() try: return client.call(context, 'add_location', image_id, url, metadata) except Exception: _reraise_translated_image_exception(image_id) def download(self, context: context.RequestContext, image_id: str, data=None): """Calls out to Glance for data and writes data.""" if data and 'file' in CONF.allowed_direct_url_schemes: direct_url, locations = self.get_location(context, image_id) urls = [direct_url] + [loc.get('url') for loc in locations or []] for url in urls: if url is None: continue parsed_url = urllib.parse.urlparse(url) if parsed_url.scheme == "file": # a system call to cp could have significant performance # advantages, however we do not have the path to files at # this point in the abstraction. with open(parsed_url.path, "rb") as f: shutil.copyfileobj(f, data) return try: image_chunks = self._client.call(context, 'data', image_id) except Exception: _reraise_translated_image_exception(image_id) if image_chunks is None: raise exception.ImageDownloadFailed( image_href=image_id, reason=_('image contains no data.')) if not data: return image_chunks else: for chunk in image_chunks: data.write(chunk) def create(self, context: context.RequestContext, image_meta: Dict[str, Any], data=None) -> Dict[str, Any]: """Store the image data and return the new image object.""" sent_service_image_meta = self._translate_to_glance(image_meta) if data: sent_service_image_meta['data'] = data recv_service_image_meta = self._client.call(context, 'create', **sent_service_image_meta) return self._translate_from_glance(context, recv_service_image_meta) def update(self, context: context.RequestContext, image_id: str, image_meta: dict, data=None, purge_props: bool = True, store_id: Optional[str] = None, base_image_ref: Optional[str] = None) -> dict: """Modify the given image with the new data.""" # For v2, _translate_to_glance stores custom properties in image meta # directly. We need the custom properties to identify properties to # remove if purge_props is True. Save the custom properties before # translate. if purge_props: props_to_update = image_meta.get('properties', {}).keys() image_meta = self._translate_to_glance(image_meta) # NOTE(bcwaldon): id is not an editable field, but it is likely to be # passed in by calling code. Let's be nice and ignore it. image_meta.pop('id', None) kwargs = {} if store_id: kwargs['store_id'] = store_id if base_image_ref: kwargs['base_image_ref'] = base_image_ref try: if data: self._client.call(context, 'upload', image_id, data, **kwargs) if image_meta: if purge_props: # Properties to remove are those not specified in # input properties. cur_image_meta = self.show(context, image_id) cur_props = cur_image_meta['properties'].keys() remove_props = list(set(cur_props) - set(props_to_update)) image_meta['remove_props'] = remove_props image_meta = self._client.call(context, 'update', image_id, **image_meta) else: image_meta = self._client.call(context, 'get', image_id) except Exception: _reraise_translated_image_exception(image_id) else: return self._translate_from_glance(context, image_meta) def delete(self, context: context.RequestContext, image_id: str) -> bool: """Delete the given image. :raises ImageNotFound: if the image does not exist. :raises NotAuthorized: if the user is not an owner. """ try: self._client.call(context, 'delete', image_id) except glanceclient.exc.NotFound: raise exception.ImageNotFound(image_id=image_id) return True def _translate_from_glance(self, context: context.RequestContext, image: Dict[str, Any]) -> dict: """Get image metadata from glance image. Extract metadata from image and convert it's properties to type cinder expected. :param image: glance image object :return: image metadata dictionary """ if self._image_schema is None: self._image_schema = self._client.call(context, 'get', controller='schemas', schema_name='image') assert self._image_schema is not None # NOTE(aarefiev): get base image property, store image 'schema' # is redundant, so ignore it. image_meta: dict = { key: getattr(image, key) for key in image.keys() if self._image_schema.is_base_property(key) is True and key != 'schema'} # Process 'cinder_encryption_key_id' as a metadata key if 'cinder_encryption_key_id' in image.keys(): image_meta['cinder_encryption_key_id'] = \ image['cinder_encryption_key_id'] # NOTE(aarefiev): nova is expected that all image properties # (custom or defined in schema-image.json) stores in # 'properties' key. image_meta['properties'] = { key: getattr(image, key) for key in image.keys() if self._image_schema.is_base_property(key) is False} image_meta = _convert_timestamps_to_datetimes(image_meta) image_meta = _convert_from_string(image_meta) return image_meta @staticmethod def _translate_to_glance(image_meta: Dict[str, Any]) -> Dict[str, Any]: image_meta = _convert_to_string(image_meta) image_meta = _remove_read_only(image_meta) # NOTE(tsekiyama): From the Image API v2, custom properties must # be stored in image_meta directly, instead of the 'properties' key. properties = image_meta.get('properties') if properties: image_meta.update(properties) del image_meta['properties'] return image_meta def _is_image_available(self, context: context.RequestContext, image) -> bool: """Check image availability. This check is needed in case Nova and Glance are deployed without authentication turned on. """ # The presence of an auth token implies this is an authenticated # request and we need not handle the noauth use-case. if hasattr(context, 'auth_token') and context.auth_token: return True if context.is_admin: return True if (getattr(image, 'is_public', False) or getattr(image, 'visibility', 'private') == 'public'): return True properties = image.properties if context.project_id and ('owner_id' in properties): return str(properties['owner_id']) == str(context.project_id) if context.project_id and ('project_id' in properties): return str(properties['project_id']) == str(context.project_id) if image.visibility == 'shared': for member in self.list_members(context, image.id): if (context.project_id == member['member_id'] and member['status'] == 'accepted'): return True try: user_id = properties['user_id'] except KeyError: return False return str(user_id) == str(context.user_id) def _convert_timestamps_to_datetimes(image_meta: dict) -> dict: """Returns image with timestamp fields converted to datetime objects.""" for attr in ['created_at', 'updated_at', 'deleted_at']: if image_meta.get(attr): image_meta[attr] = timeutils.parse_isotime(image_meta[attr]) return image_meta # NOTE(bcwaldon): used to store non-string data in glance metadata def _json_loads(properties: dict, attr: str) -> None: prop = properties[attr] if isinstance(prop, str): properties[attr] = jsonutils.loads(prop) def _json_dumps(properties: dict, attr: str) -> None: prop = properties[attr] if not isinstance(prop, str): properties[attr] = jsonutils.dumps(prop) _CONVERT_PROPS = ('block_device_mapping', 'mappings') def _convert(method: Callable[[dict, str], Optional[dict]], metadata: dict) -> dict: metadata = copy.deepcopy(metadata) properties = metadata.get('properties') if properties: for attr in _CONVERT_PROPS: if attr in properties: method(properties, attr) return metadata def _convert_from_string(metadata: dict) -> dict: return _convert(_json_loads, metadata) def _convert_to_string(metadata: dict) -> dict: return _convert(_json_dumps, metadata) def _extract_attributes(image): # NOTE(hdd): If a key is not found, base.Resource.__getattr__() may perform # a get(), resulting in a useless request back to glance. This list is # therefore sorted, with dependent attributes as the end # 'deleted_at' depends on 'deleted' # 'checksum' depends on 'status' == 'active' IMAGE_ATTRIBUTES = ('size', 'disk_format', 'owner', 'container_format', 'status', 'id', 'name', 'created_at', 'updated_at', 'deleted', 'deleted_at', 'checksum', 'min_disk', 'min_ram', 'protected', 'visibility', 'cinder_encryption_key_id') output: Dict[str, Any] = {} for attr in IMAGE_ATTRIBUTES: if attr == 'deleted_at' and not output['deleted']: output[attr] = None elif attr == 'checksum' and output['status'] != 'active': output[attr] = None else: output[attr] = getattr(image, attr, None) output['properties'] = getattr(image, 'properties', {}) return output def _remove_read_only(image_meta: dict) -> dict: IMAGE_ATTRIBUTES = ['status', 'updated_at', 'created_at', 'deleted_at'] output = copy.deepcopy(image_meta) for attr in IMAGE_ATTRIBUTES: if attr in output: del output[attr] return output def _reraise_translated_image_exception(image_id: str) -> NoReturn: """Transform the exception for the image but keep its traceback intact.""" _exc_type, exc_value, exc_trace = sys.exc_info() assert exc_value is not None new_exc = _translate_image_exception(image_id, exc_value) raise new_exc.with_traceback(exc_trace) def _reraise_translated_exception() -> NoReturn: """Transform the exception but keep its traceback intact.""" _exc_type, exc_value, exc_trace = sys.exc_info() assert exc_value is not None new_exc = _translate_plain_exception(exc_value) raise new_exc.with_traceback(exc_trace) def _translate_image_exception(image_id: str, exc_value: BaseException) -> BaseException: if isinstance(exc_value, (glanceclient.exc.Forbidden, glanceclient.exc.Unauthorized)): return exception.ImageNotAuthorized(image_id=image_id) if isinstance(exc_value, glanceclient.exc.NotFound): return exception.ImageNotFound(image_id=image_id) if isinstance(exc_value, glanceclient.exc.BadRequest): return exception.Invalid(exc_value) return exc_value def _translate_plain_exception(exc_value: BaseException) -> BaseException: if isinstance(exc_value, (glanceclient.exc.Forbidden, glanceclient.exc.Unauthorized)): return exception.NotAuthorized(exc_value) if isinstance(exc_value, glanceclient.exc.NotFound): return exception.NotFound(exc_value) if isinstance(exc_value, glanceclient.exc.BadRequest): return exception.Invalid(exc_value) return exc_value def get_remote_image_service(context: context.RequestContext, image_href) -> Tuple[GlanceImageService, str]: """Create an image_service and parse the id from the given image_href. The image_href param can be an href of the form 'http://example.com:9292/v1/images/b8b2c6f7-7345-4e2f-afa2-eedaba9cbbe3', or just an id such as 'b8b2c6f7-7345-4e2f-afa2-eedaba9cbbe3'. If the image_href is a standalone id, then the default image service is returned. :param image_href: href that describes the location of an image :returns: a tuple of the form (image_service, image_id) """ # NOTE(bcwaldon): If image_href doesn't look like a URI, assume its a # standalone image ID if '/' not in str(image_href): image_service = get_default_image_service() return image_service, image_href try: (image_id, glance_netloc, use_ssl) = _parse_image_ref(image_href) glance_client = GlanceClientWrapper(context=context, netloc=glance_netloc, use_ssl=use_ssl) except ValueError: raise exception.InvalidImageRef(image_href=image_href) image_service = GlanceImageService(client=glance_client) return image_service, image_id def get_default_image_service() -> GlanceImageService: return GlanceImageService()
cinder/image/glance.py
codereval_python_data_152
Iterate over a string list and remove trailing os seperator characters. Each string is tested if its length is greater than one and if the last character is the pathname seperator. If so, the pathname seperator character is removed. Args: input_list: list of strings Returns: Processed list of strings Raises: TypeError import os def remove_ending_os_sep(input_list): """ Iterate over a string list and remove trailing os seperator characters. Each string is tested if its length is greater than one and if the last character is the pathname seperator. If so, the pathname seperator character is removed. Args: input_list: list of strings Returns: Processed list of strings Raises: TypeError """ # Input could be None, so test for that case if input_list is None: return [] return [item[:-1] if len(item) >= 2 and item.endswith(os.sep) else item for item in input_list] #!/usr/bin/env python # -*- coding: utf-8 -*- """ The util module contains subroutines used everywhere. @package makeprojects.util """ from __future__ import absolute_import, print_function, unicode_literals import os import re import fnmatch from burger import string_to_bool, is_string, import_py_script from .enums import FileTypes from .config import DEFAULT_BUILD_RULES # pylint: disable=consider-using-f-string ######################################## def validate_enum_type(value, data_type): """ Verify a value is a specific data type. Check if the value is either None or an instance of a specfic data type. If so, return immediately. If the value is a string, call the lookup() function of the data type for conversion. Args: value: Value to check. data_type: Type instance of the class type to match. Returns: Value converted to data_type or None. Raises: TypeError """ if value is not None: # Perform the lookup new_value = data_type.lookup(value) if new_value is None: msg = '"{}" must be of type "{}".'.format( value, data_type.__name__) raise TypeError(msg) # Save the converted type value = new_value return value ######################################## def regex_dict(item): """ Convert *.cpp keys to regex keys Given a dict where the keys are all filenames with wildcards, convert only the keys into equivalent regexes and leave the values intact. Examples: rules = { '*.cpp': {'a': 'arf', 'b': 'bark', 'c': 'coo'}, '*.h': {'h': 'help'} } regex_keys = regex_dict(rules) Args: item: dict to convert Returns: dict with keys converted to regexes """ output = {} for key in item: output[re.compile(fnmatch.translate(key)).match] = item[key] return output ######################################## def validate_boolean(value): """ Verify a value is a boolean. Check if the value can be converted to a bool, if so, return the value as bool. None is converted to False. Args: value: Value to check. Returns: Value converted to data_type or None. Raises: ValueError """ if value is not None: # Convert to bool value = string_to_bool(value) return value ######################################## def validate_string(value): """ Verify a value is a string. Check if the value is a string, if so, return the value as is or None. Args: value: Value to check. Returns: Value is string or None. Raises: ValueError """ if value is not None: # Convert to bool if not is_string(value): raise ValueError('"{}" must be a string.'.format(value)) return value ######################################## def source_file_filter(file_list, file_type_list): """ Prune the file list for a specific type. Note: file_type_list can either be a single enums.FileTypes enum or an iterable list of enums.FileTypes Args: file_list: list of core.SourceFile entries. file_type_list: enums.FileTypes to match. Returns: list of matching core.SourceFile entries. """ result_list = [] # If a single item was passed, use a simple loop if isinstance(file_type_list, FileTypes): for item in file_list: if item.type is file_type_list: result_list.append(item) else: # A list was passed, so test against the list for item in file_list: if item.type in file_type_list: result_list.append(item) return result_list ######################################## def add_build_rules(build_rules_list, file_name, verbose, is_root, basename): """ Load in the file ``build_rules.py`` Load the build_rules.py file. If the variable ``*_GENERIC`` is ``True`` or if ``is_root`` is ``True``, append the module to ``build_rules_list``. If the variable ``*_CONTINUE`` was found in the file, check if it is set to ``True``. If so, return ``True`` to allow processing to continue. If the file is not found, return ``True`` to allow processing the parent folder. Since this is called from ``buildme``, ``cleanme``, and ``makeprojects``, the prefix needed for the tool is passed in ``basename``. An example is "CLEANME". Args: build_rules_list: List to add ``build_rules.py`` instances. file_name: Full path name of the build_rules.py to load. verbose: True for verbose output. is_root: True if *_GENERIC is ignored. basename: Variable prefix to substitute * in *_GENERIC Returns: True if the parent folder should be checked, False if not. """ # Ensure the absolute path is used. file_name = os.path.abspath(file_name) build_rules = import_py_script(file_name) # Not found? Continue parsing folders. if not build_rules: return True if is_root or getattr(build_rules, basename + "_GENERIC", False) or getattr(build_rules, "GENERIC", False): # Add to the list build_rules_list.append(build_rules) if verbose: print('Using configuration file {}'.format(file_name)) # Test if this is considered the last one in the chain. result = getattr(build_rules, basename + "_CONTINUE", None) # Not found? if result is None: # Try the catch all version result = getattr(build_rules, "CONTINUE", False) return result ######################################## def get_build_rules(working_directory, verbose, build_rules_name, basename): """ Find all ``build_rules.py`` files that apply to this directory. If no files are found, return an empty list. Args: working_directory: Directory to scan for ``build_rules.py`` verbose: True if verbose output is desired build_rules_name: ``build_rules.py`` or an override basename: "CLEANME", "BUILDME", etc. Returns: List of loaded ``build_rules.py`` file modules """ # Test if there is a specific build rule build_rules_list = [] # Load the configuration file at the current directory temp_dir = os.path.abspath(working_directory) # Is this the first pass? is_root = True while True: # Attempt to load in the build rules. if not add_build_rules( build_rules_list, os.path.join( temp_dir, build_rules_name), verbose, is_root, basename): # Abort if *_CONTINUE = False break # Directory traversal is active, require CLEANME_GENERIC is_root = False # Pop a folder to check for higher level build_rules.py temp_dir2 = os.path.dirname(temp_dir) # Already at the top of the directory? if temp_dir2 is None or temp_dir2 == temp_dir: add_build_rules( build_rules_list, DEFAULT_BUILD_RULES, verbose, True, basename) break # Use the new folder temp_dir = temp_dir2 return build_rules_list ######################################## def getattr_build_rules(build_rules_list, attributes, value): """ Find an attribute in a list of build rules. Iterate over the build rules list until an entry has an attribute value. It will return the first one found. If none are found, or there were no entries in ``build_rules_list``, this function returns ``value``. Args: build_rules_list: List of ``build_rules.py`` instances. attributes: Attribute name(s) to check for. value: Value to return if the attribute was not found. Returns: Attribute value found in ``build_rules_list`` entry, or ``value``. """ # Ensure if it is a single string if is_string(attributes): for build_rules in build_rules_list: # Does the entry have this attribute? try: return getattr(build_rules, attributes) except AttributeError: pass else: # Assume attributes is an iterable of strings for build_rules in build_rules_list: # Does the rules file have this attribute? for attribute in attributes: try: return getattr(build_rules, attribute) except AttributeError: pass # Return the default value return value ######################################## def remove_ending_os_sep(input_list): """ Iterate over a string list and remove trailing os seperator characters. Each string is tested if its length is greater than one and if the last character is the pathname seperator. If so, the pathname seperator character is removed. Args: input_list: list of strings Returns: Processed list of strings Raises: TypeError """ # Input could be None, so test for that case if input_list is None: return [] return [item[:-1] if len(item) >= 2 and item.endswith(os.sep) else item for item in input_list] ######################################## def was_processed(processed, path_name, verbose): """ Check if a file or directory has already been processed. To prevent recursion, expand the path name to an absolution path call this function with a set that will store all the entries and the entry to test. If the entry is already in the set, report the issue and return ``True``. Otherwise, add the entry to the set and return ``False`` to allow the path to be processed. Args: processed: Set to store processed pathnames path_name: Path to a directory or file verbose: True if verbose output is requested Returns: True if it's already in the set. False if not. """ # Test for recursion if path_name in processed: if verbose: print('{} has already been processed'.format(path_name)) return True # Mark this list as "processed" to prevent recursion if verbose: print('Processing {}.'.format(path_name)) processed.add(path_name) return False
makeprojects/util.py
codereval_python_data_153
This method converts the given string to regex pattern import re def get_pattern(pattern, strip=True): """ This method converts the given string to regex pattern """ if type(pattern) == re.Pattern: return pattern if strip and type(pattern) == str: pattern = pattern.strip() return re.compile(pattern) """ Goal: To search the given text in the data of type dict """ from collections import OrderedDict import re class Search: def __init__(self): pass def validate(self, data, dtype=OrderedDict): """ This method validates the given data """ if data == None: return None if type(data) != dtype: return None return True def get_pattern(self, pattern, strip=True): """ This method converts the given string to regex pattern """ if type(pattern) == re.Pattern: return pattern if strip and type(pattern) == str: pattern = pattern.strip() return re.compile(pattern) def search_in_tree(self, pattern, data=None): if not self.validate(data): return None p = self.get_pattern(pattern) for key in data.keys(): if p.match(key): return key return None def search_all_in_tree(self, pattern, data=None): if not self.validate(data): return None p = self.get_pattern(pattern) match = OrderedDict() for key in data.keys(): if p.match(key): match[key] = key return match if len(match) else None def search_in_tree_level(self, pattern, data=None, level=0): if not self.validate(data): return None p = self.get_pattern(pattern) for key in data: if p.match(key): return key if data[key] == None: continue if type(data[key]) == OrderedDict and level > 0: res = self.search_in_tree_level(p, data[key], level=level - 1) if res: return res return None def search_in_table(self, pattern, data=None, header_column=None): if not self.validate(data): return None p = self.get_pattern(pattern) for each_row in data: if p.match(each_row[header_column]): return each_row def search_all_in_table(self, pattern, data=None, header_column=None): if not self.validate(data): return None p = self.get_pattern(pattern) match = [] for each_row in data: if p.match(each_row[header_column]): match.append(each_row) return match if len(match) else None
shconfparser/search.py
codereval_python_data_154
Call the given command(s). import subprocess def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen( [command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs ) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode #!/usr/bin/env python # -*- coding: utf-8 -*- """ Module contains the core classes for makeproject. @package makeprojects.core """ # pylint: disable=consider-using-f-string # pylint: disable=useless-object-inheritance from __future__ import absolute_import, print_function, unicode_literals import os import sys from operator import attrgetter from copy import deepcopy from burger import get_windows_host_type, convert_to_windows_slashes, \ convert_to_linux_slashes, is_string, translate_to_regex_match, \ StringListProperty, BooleanProperty, NoneProperty, run_command from .enums import FileTypes, ProjectTypes, IDETypes, PlatformTypes from .enums import platformtype_short_code from .defaults import get_configuration_settings from .build_rules import rules as default_rules from .util import validate_enum_type, regex_dict, validate_boolean, \ validate_string ######################################## class BuildError(object): """ Error message generated by builders. When a builder completes, a BuildError class is created and appended to the ``results`` list for logging. Attributes: error: Integer error code. filename: File name that generated the error. configuration: Build configuration. msg: Error message. """ def __init__(self, error, filename, configuration=None, msg=None): """ Initializers for an BuildError. Args: error: Integer error code, zero if not error filename: File that generated the error configuration: If applicable, configuration that was compiled msg: Error message test, if available """ # Init all the values self.error = error self.filename = filename self.configuration = configuration self.msg = msg ######################################## def get_error_code(self): """ Return the integer error code. """ return self.error ######################################## def __repr__(self): """ Convert the error into a string. Returns: A full error string. """ if self.error: result = 'Error #{} in file {}'.format(self.error, self.filename) else: result = 'No error in file {}'.format(self.filename) if self.configuration: result += ' Configuration "{}"'.format(self.configuration) if self.msg: result += ' "{}"'.format(self.msg) return result def __str__(self): """ Convert the error into a string. Returns: A full error string. """ return self.__repr__() ######################################## class BuildObject(object): """ Object describing something to build. When the directory is parsed, a list of BuildObjects is generated and then sorted by priority and then built. Attributes: file_name: Name of file to build. priority: Numeric priorty in ascending order. configuration: Configuration if applicable """ def __init__(self, file_name, priority, configuration=None): """ Initializers for an BuildObject. Args: file_name: Name of the file to build. priority: Integer priority, lower will be built first. configuration: Configuration to build """ self.file_name = file_name self.priority = priority self.configuration = configuration ######################################## def build(self): """ Perform the build operation Returns: BuildError object as Unimplemented build. """ return BuildError(10, self.file_name, self.configuration, msg="Unimplemented build") ######################################## def run_command(self, cmd, verbose): """ Issue a command and return the generated BuildError Args: cmd: command line to execute verbose: True if verbose output is required Returns: BuildError object with error condition, if any. """ # Perform the command try: error_code = run_command( cmd, working_dir=os.path.dirname(self.file_name), quiet=not verbose)[0] msg = None except OSError as error: error_code = getattr(error, 'winerror', error.errno) msg = str(error) print(msg, file=sys.stderr) # Return the results return BuildError(error_code, self.file_name, configuration=self.configuration, msg=msg) ######################################## def __repr__(self): """ Convert the object into a string. Returns: A full string. """ result = ( '{} for file "{}" with priority {}').format( type(self).__name__, self.file_name, self.priority) if self.configuration: result += ' configuration "{}"'.format(self.configuration) return result def __str__(self): """ Convert the object into a string. Returns: A full string. """ return self.__repr__() ######################################## class Attributes(object): """ Base class for Solution parts to unify common code Attributes: parent: Reference to parent object for chained attribute lookups define_list: List of defines for the compiler include_folders_list: List of folders to add to compiler include list library_folders_list: List of folders to add to linker include list libraries_list: List of libraries to link frameworks_list: Darwin frameworks list exclude_from_build_list: List of patterns to exclude from this config exclude_list: List of files to exclude from directory scanning cw_environment_variables: List of CodeWarrior environment variables custom_rules: Custom build rules platform: @ref enums.PlatformTypes enum for target platform project_type: @ref enums.ProjectTypes enum for target output debug: Boolean for debug information generation link_time_code_generation: Boolean for LTCG optimization: Boolean for optimization enable analyze: Boolean for code analysis use_mfc: Boolean for Microsoft Foundation Classes usage use_atl: Boolean for Active Template Library usage clr_support: C# CLR support usage name: Name of the project or configuration working_directory: Base directory for relative paths deploy_folder: Directory to deploy binaries _source_include_list: Generated file folder list _platform: True @ref platform value _project_type: True @ref project_type _debug: True @ref debug _link_time_code_generation: True @ref link_time_code_generation _optimization: True @ref optimization _analyze: True @ref analyze _use_mfc: True @ref use_mfc _use_atl: True @ref use_atl _clr_support: True @ref clr_support _name: True @ref name _working_directory: True @ref working_directory _deploy_folder: True @ref deploy_folder """ # pylint: disable=too-many-instance-attributes define_list = StringListProperty('_define_list') include_folders_list = StringListProperty('_include_folders_list') library_folders_list = StringListProperty('_library_folders_list') libraries_list = StringListProperty('_libraries_list') frameworks_list = StringListProperty('_frameworks_list') exclude_from_build_list = StringListProperty('_exclude_from_build_list') exclude_list = StringListProperty('_exclude_list') cw_environment_variables = StringListProperty('_cw_environment_variables') def __init__(self): """ Perform initialization off all attributes. """ self.parent = None self.define_list = [] self.include_folders_list = [] self.library_folders_list = [] self.libraries_list = [] self.frameworks_list = [] self.exclude_from_build_list = [] self.exclude_list = [] self.cw_environment_variables = [] self.custom_rules = {} # These are internal values self._source_include_list = [] self._platform = None self._project_type = None self._debug = None self._link_time_code_generation = None self._optimization = None self._analyze = None self._use_mfc = None self._use_atl = None self._clr_support = None self._name = None self._working_directory = None self._deploy_folder = None ######################################## def get_chained_value(self, name): """ Follow the chain to find a value. Args: self: The 'this' reference. name: Name of the attribute Returns: None or the value. """ # Get the value value = getattr(self, name, None) # If not found, follow the chain, if any if value is None and self.parent is not None: value = self.parent.get_chained_value(name) return value ######################################## def get_chained_list(self, name): """ Return an chained attribute list. @details Obtain the list from the named attribute and append it with the same attribute in parent and return the entire list. This function does not modify the original lists. Args: name: Name of the attribute key Returns: A list of all items found. The list can be empty. """ value_list = list(getattr(self, name, [])) # Is there a reverse link? if self.parent is not None: value_list.extend(getattr(self.parent, name, [])) return value_list ######################################## def get_unique_chained_list(self, name): """ Return an chained attribute list with duplicates removed. @details Obtain the list from the named attribute and append it with the same attribute in parent and return the entire list. This function does not modify the original lists. All duplicates are removed. Args: name: Name of the attribute key Returns: A list of all items found. The list can be empty. See Also: get_chained_list """ return list(dict.fromkeys(self.get_chained_list(name))) ######################################## def _getplatform(self): """ Get the enums.PlatformTypes """ return self.get_chained_value('_platform') def _setplatform(self, value): """ Set the enums.PlatformTypes with validation Args: self: The 'this' reference. value: None or enums.PlatformTypes """ self._platform = validate_enum_type(value, PlatformTypes) platform = property(_getplatform, _setplatform) ######################################## def _getproject_type(self): """ Get the enums.ProjectTypes """ return self.get_chained_value('_project_type') def _setproject_type(self, value): """ Set the enums.ProjectTypes with validation Args: self: The 'this' reference. value: None or enums.ProjectTypes """ self._project_type = validate_enum_type(value, ProjectTypes) project_type = property(_getproject_type, _setproject_type) ######################################## def _getdebug(self): """ Get debug boolean """ return self.get_chained_value('_debug') def _setdebug(self, value): """ Set the boolean with validation Args: self: The 'this' reference. value: None, True or False """ self._debug = validate_boolean(value) debug = property(_getdebug, _setdebug) ######################################## def _getlink_time_code_generation(self): """ Get link time code generation boolean """ return self.get_chained_value('_link_time_code_generation') def _setlink_time_code_generation(self, value): """ Set the boolean with validation Args: self: The 'this' reference. value: None, True or False """ self._link_time_code_generation = validate_boolean(value) link_time_code_generation = property( _getlink_time_code_generation, _setlink_time_code_generation) ######################################## def _getoptimization(self): """ Get optimization boolean """ return self.get_chained_value('_optimization') def _setoptimization(self, value): """ Set the boolean with validation Args: self: The 'this' reference. value: None, True or False """ self._optimization = validate_boolean(value) optimization = property(_getoptimization, _setoptimization) ######################################## def _getanalyze(self): """ Get code analysis boolean """ return self.get_chained_value('_analyze') def _setanalyze(self, value): """ Set the boolean with validation Args: self: The 'this' reference. value: None, True or False """ self._analyze = validate_boolean(value) analyze = property(_getanalyze, _setanalyze) ######################################## def _getuse_mfc(self): """ Get use of Microsoft Foundation class boolean """ return self.get_chained_value('_use_mfc') def _setuse_mfc(self, value): """ Set the boolean with validation Args: self: The 'this' reference. value: None, True or False """ self._use_mfc = validate_boolean(value) use_mfc = property(_getuse_mfc, _setuse_mfc) ######################################## def _getuse_atl(self): """ Get Microsoft Active Template Library boolean """ return self.get_chained_value('_use_atl') def _setuse_atl(self, value): """ Set the boolean with validation Args: self: The 'this' reference. value: None, True or False """ self._use_atl = validate_boolean(value) use_atl = property(_getuse_atl, _setuse_atl) ######################################## def _getclr_support(self): """ Get Common Language Runtime boolean """ return self.get_chained_value('_clr_support') def _setclr_support(self, value): """ Set the boolean with validation Args: self: The 'this' reference. value: None, True or False """ self._clr_support = validate_boolean(value) clr_support = property(_getclr_support, _setclr_support) ######################################## def _getname(self): """ Get name string """ return self.get_chained_value('_name') def _setname(self, value): """ Set the string with validation Args: self: The 'this' reference. value: None, string """ self._name = validate_string(value) name = property(_getname, _setname) ######################################## def _getworking_directory(self): """ Get working directory string """ return self.get_chained_value('_working_directory') def _setworking_directory(self, value): """ Set the string with validation Args: self: The 'this' reference. value: None, string """ self._working_directory = validate_string(value) working_directory = property(_getworking_directory, _setworking_directory) ######################################## def _getdeploy_folder(self): """ Get deployment folder string """ return self.get_chained_value('_deploy_folder') def _setdeploy_folder(self, value): """ Set the string with validation Args: self: The 'this' reference. value: None, string """ self._deploy_folder = validate_string(value) deploy_folder = property(_getdeploy_folder, _setdeploy_folder) ######################################## class SourceFile(object): """ Object for each input file to insert to a solution. For every file that could be included into a project file one of these objects is created and attached to a Project object for processing. @note For hash consistency, @ref relative_pathname has all directory slashes in Windows format "\" instead of Linux/BSD format on all platforms. Attributes: relative_pathname: File base name with extension working_directory: Directory the file is relative to type: File type enumeration, @ref enums.FileTypes """ def __init__(self, relative_pathname, working_directory, filetype): """ Default constructor. Args: relative_pathname: Filename of the input file (relative to the root) working_directory: Pathname of the root directory filetype: Compiler to apply See Also: enums.FileTypes """ # Sanity check if not isinstance(filetype, FileTypes): raise TypeError("parameter 'filetype' must be of type FileTypes") self.relative_pathname = convert_to_windows_slashes(relative_pathname) self.working_directory = working_directory self.type = filetype ######################################## def get_group_name(self): r""" Get the group location for this source file. @details To determine if the file should be in a sub group in the project, scan the filename to find if it's a base filename or part of a directory. If it's a basename, return an empty string. If it's in a folder, remove any ``..\`` prefixes and ``.\`` prefixes and return the filename with the basename removed. Returns: The group name string with ``\`` delimiters. """ # Check if there's a group slash = '\\' index = self.relative_pathname.rfind(slash) if index == -1: slash = '/' index = self.relative_pathname.rfind(slash) if index == -1: # It's at the root return '' # Remove the basename group_name = self.relative_pathname[:index] # If there are ..\\ at the beginning, remove them while group_name.startswith('..' + slash): group_name = group_name[3:] # If there is a .\\, remove the single prefix while group_name.startswith('.' + slash): group_name = group_name[2:] return group_name ######################################## def get_abspath(self): """ Return the full pathname of the file entry. Directory slashes will be set to the type that matches the host platform. Returns: Absolute pathname for the file. """ if get_windows_host_type(): file_name = self.relative_pathname else: file_name = convert_to_linux_slashes(self.relative_pathname) return os.path.abspath(os.path.join(self.working_directory, file_name)) ######################################## def __repr__(self): """ Convert the file record into a human readable file description. Returns: Human readable string. """ return 'FileType: {} Pathname: "{}"'.format(str(self.type), self.get_abspath()) def __str__(self): """ Convert the file record into a human readable file description. Returns: Human readable string. """ return self.__repr__() ######################################## class Configuration(Attributes): """ Object for containing attributes specific to a build configuration. This object contains all of the items needed to create a specific configuration of a project. Valid attributes: - ``name`` name of the configuration - ``short_code`` Short code suffix for configuration name - ``platform`` Platform to build for - ``project_type`` Type of binary to generate - ``exclude_from_build_list`` List of files to exclude from this configuration - ``include_folders_list`` List of directories for headers - ``library_folders_list`` List of directories for libraries - ``libraries_list`` List of libraries to include - ``frameworks_list`` List of frameworks to include (macOS/iOS) - ``define_list`` List of defines for compilation - ``debug`` True if debugging defaults are enabled - ``optimization`` 0-4 level of optimization - ``link_time_code_generation`` Enable link time code genration If any of these attributes are read, they will always return None. To modify them, use the parent @ref Project - ``source_folders_list`` See Project.source_folders_list - ``vs_props`` See Project.vs_props - ``vs_targets`` See Project.vs_targets - ``vs_rules`` See Project.vs_rules Attributes: source_folders_list: Don't allow source folders vs_props: Don't allow Visual Studio props files vs_targets: Don't allow Visual Studio targets files vs_rules: Don't allow Visual Studio rules files project: Project this Configuration is attached to. ide: Get the @ref enums.IDETypes of the parent (Read only) short_code: Short config string for file name suffix _short_code: True @ref short_code See Also: Project, Solution """ # Disable these attributes that are present in the parent Project source_folders_list = NoneProperty('_source_folders_list') vs_props = NoneProperty('_vs_props') vs_targets = NoneProperty('_vs_targets') vs_rules = NoneProperty('_vs_rules') def __init__(self, *args, **kargs): """ Init defaults. Args: args: name and setting_name for get_configuration_settings() kargs: List of defaults. """ # Init the base class super().__init__() self._short_code = None # Were there nameless parameters? if args: # Too many parameters? if len(args) >= 3: raise ValueError( 'Only one or two nameless parameters are allowed') # Get the default settings setting_name = None if len(args) == 2: setting_name = args[1] new_args = get_configuration_settings(args[0], setting_name) if new_args is None: new_args = {'name': args[0]} # Were there defaults found? for item in new_args: # Only add, never override if item not in kargs: kargs[item] = new_args[item] # Check the default name if not is_string(kargs.get('name', None)): raise TypeError( "string parameter 'name' is required") # Set all the variables for key in kargs.items(): setattr(self, key[0], key[1]) self.project = None ######################################## def _getide(self): """ Return the preferred IDE """ if self.parent is not None: return self.parent.ide return None ide = property(_getide) ######################################## def _getshort_code(self): """ Return the short code """ short_code = getattr(self, '_short_code', None) if short_code is None: return self.name return short_code def _setshort_code(self, value): """ Set the filename suffix Args: self: The 'this' reference. value: New short code """ self._short_code = validate_string(value) short_code = property(_getshort_code, _setshort_code) ######################################## def parse_attributes(self, build_rules_list, working_directory): """ Initialize the default attributes. Args: build_rules_list: List to append a valid build_rules file instance. working_directory: Full path name of the build_rules.py to load. """ default_rules('configuration_settings', working_directory=working_directory, configuration=self) for rules in build_rules_list: default = rules( 'configuration_settings', working_directory=working_directory, configuration=self) # Must test for zero, since None is a break. if default != 0: break ######################################## def get_suffix(self, force_short=False): """ Return the proposed suffix. @details Each configuration can generate a seperate binary and if they are stored in the same folder, a suffix is appended to make the filename unique. Args: force_short: True to force the platform code to 3 characters Returns: A suffix of the IDE, Platform and Configuration short codes. """ # It's possible to have a platform for # projects that consist of platform neutral data platform = self.platform if platform is not None: platform_text = platform.get_short_code() if force_short: platform_text = platform_text[:3] else: # Platform neutral platform_text = '' return '{}{}{}'.format( self.ide.get_short_code(), platform_text, self.short_code) ######################################## def __repr__(self): """ Convert the configuration record into a human readable description. Returns: Human readable string. """ result_list = [] for item in self.__dict__.items(): if item[0] == 'parent': continue if item[0] == 'project': result_list.append( 'Project: "{}"'.format( item[1].name)) continue item_name = item[0][1:] if item[0].startswith('_') else item[0] result_list.append( '{0}: {1!s}'.format( item_name, item[1])) return 'Configuration: ' + ', '.join(result_list) ######################################## def __str__(self): """ Convert the configuration record into a human readable description. Returns: Human readable string. """ return self.__repr__() ######################################## class Project(Attributes): """ Object for processing a project file. This object contains all of the items needed to generate a project. @note On most IDEs, this is merged into one file, but Visual Studio generates a project file for each project. Attributes: source_folders_list: List of directories to scan for source code source_files_list: Generated source file list to include in the project vs_props: List of props files for Visual Studio vs_targets: List of targets file for Visual Studio vs_rules: List of rules file for Visual Studio 2005-2008 name: Project name working_directory: Working directory for the project solution: No parent solution yet configuration_list: Generate the default configurations project_list: Project records that need to be built first codefiles: Initial array of SourceFile in the solution file_list: Used by scan_directory include_list: Used by scan_directory platform_code: Platform code for generation exclude_list_regex: Regex iterable of files to exclude """ # pylint: disable=too-many-instance-attributes source_folders_list = StringListProperty('_source_folders_list') source_files_list = StringListProperty('_source_files_list') vs_props = StringListProperty('_vs_props') vs_targets = StringListProperty('_vs_targets') vs_rules = StringListProperty('_vs_rules') def __init__(self, name=None, **kargs): """ Set defaults. Args: name: Name of the project kargs: dict of arguments. """ # Init the base class super().__init__() self.source_folders_list = ['.', 'source', 'src'] self.source_files_list = [] self.vs_props = [] self.vs_targets = [] self.vs_rules = [] working_directory = os.getcwd() # Set a default project name if name is None: self.name = os.path.basename(working_directory) else: self.name = name # Default directory self.working_directory = working_directory # Init the rest self.solution = None self.configuration_list = [] self.project_list = [] self.codefiles = [] self.file_list = None self.include_list = None self.platform_code = '' # Set all the variables for key in kargs.items(): setattr(self, key[0], key[1]) ######################################## def _getide(self): """ Return the preferred IDE """ if self.parent is not None: return self.parent.ide return None ide = property(_getide) ######################################## def add_configuration(self, configuration): """ Add a configuration to the list of configurations found in this project. @details Given a new Configuration class instance, append it to the list of configurations that this project is managing. Args: self: The 'this' reference. configuration: Reference to an instance of a Configuration. Raises: TypeError """ if configuration is None or is_string(configuration): configuration = Configuration(configuration) # Singular if not isinstance(configuration, Configuration): raise TypeError(("parameter 'configuration' " "must be of type Configuration")) # Set the configuration's parent if configuration.platform is None: configuration.platform = PlatformTypes.default() if configuration.platform.is_expandable(): for platform in configuration.platform.get_expanded(): config = deepcopy(configuration) config.platform = platform config.project = self config.parent = self self.configuration_list.append(config) else: configuration.project = self configuration.parent = self self.configuration_list.append(configuration) ######################################## def add_project(self, project): """ Add a dependent project. Args: project: Project to depend on. Raises: TypeError """ if project is None or is_string(project): project = Project(project) # Sanity check if not isinstance(project, Project): raise TypeError( "parameter 'project' must be of type Project or name") project.solution = self.solution project.parent = self.solution self.project_list.append(project) return project ######################################## def get_project_list(self): """ Return the project list for all projects. @details Iterate over every project and sub project and return a flattened list. Returns: list of every project in the solution. """ # Make a copy of the current list project_list = list(self.project_list) # Scan the sub projects and add their projects to the # generated list. for project in self.project_list: project_list.extend(project.get_project_list()) return project_list ######################################## def set_platforms(self, platform): """ Update all configurations to a new platform. @details If there are no configurations, Debug and Release will be created. Args: platform: Platform to change the configurations to. """ if not self.configuration_list: for item in ('Debug', 'Release'): self.add_configuration(Configuration(item, platform=platform)) else: # Create a set of configurations by name config_list = [] name_list = [] for configuration in self.configuration_list: if configuration.name in name_list: continue name_list.append(configuration.name) config_list.append(configuration) # Expand platform groups self.configuration_list = [] for item in platform.get_expanded(): for configuration in config_list: configuration.platform = item self.add_configuration(deepcopy(configuration)) ######################################## def parse_attributes(self, build_rules_list, working_directory): """ Initialize the default attributes. Args: build_rules_list: List to append a valid build_rules file instance. working_directory: Full path name of the build_rules.py to load. """ default_rules('project_settings', working_directory=working_directory, project=self) for rules in build_rules_list: default = rules('project_settings', working_directory=working_directory, project=self) # Must test for zero, since None is a break. if default != 0: break ######################################## def _scan_directory(self, working_directory, recurse, acceptable_list): """ Given a base directory and a relative directory scan for all the files that are to be included in the project Args: working_directory: Directory to scan recurse: Enable recursion acceptable_list: list to store SourceFile records """ # Absolute or relative? if not os.path.isabs(working_directory): working_directory = os.path.abspath( os.path.join(self.working_directory, working_directory)) # Is this a valid directory? if not os.path.isdir(working_directory): return # Scan the directory for base_name in os.listdir(working_directory): # Is this file in the exclusion list? for item in self.exclude_list_regex: if item(base_name): break else: # Is it a file? (Skip links and folders) file_name = os.path.join(working_directory, base_name) if os.path.isfile(file_name): # Check against the extension list (Skip if not # supported) file_type = FileTypes.lookup(base_name) if file_type is None: continue # Found a match, test if the type is in # the acceptable list if file_type in acceptable_list: # Create a new entry (Using windows style slashes # for consistency) self.file_list.append(SourceFile( os.path.relpath( file_name, self.working_directory), working_directory, file_type)) # Add the directory the file was found for header search self.include_list.add( os.path.relpath( working_directory, self.working_directory)) # Process folders only if in recursion mode elif recurse and os.path.isdir(file_name): self._scan_directory( file_name, recurse, acceptable_list) ######################################## def get_file_list(self, acceptable_list): """ Obtain the list of source files. @details Set up the variables ``codefiles`` with the list of source files found and ``_source_include_list`` with a list of relative to the working directory folders where the source code was found. - ``exclude_list`` for wildcard matching for files to exclude - ``source_folders_list`` for list of folders to search for source code - ``source_files_list`` list of files to add Args: acceptable_list: List of acceptable FileTypes """ # pylint: disable=attribute-defined-outside-init # Get the files to exclude in this self.exclude_list_regex = translate_to_regex_match( self.get_unique_chained_list('exclude_list')) self.file_list = [] self.include_list = set() working_directory = self.working_directory for item in self.get_unique_chained_list('source_files_list'): if not os.path.isabs(item): abs_path = os.path.abspath( os.path.join(working_directory, item)) else: abs_path = item # Check against the extension list (Skip if not # supported) file_type = FileTypes.lookup(os.path.basename(abs_path)) if file_type is None: continue # Found a match, test if the type is in # the acceptable list if file_type in acceptable_list: # Create a new entry (Using windows style slashes # for consistency) self.file_list.append(SourceFile( os.path.relpath( abs_path, working_directory), os.path.dirname(abs_path), file_type)) # Add the directory the file was found for header search self.include_list.add( os.path.relpath( os.path.dirname(abs_path), working_directory)) # Pull in all the source folders and scan them for item in self.get_unique_chained_list('source_folders_list'): # Is it a recursive test? recurse = False if item.endswith('/*.*'): # Remove the trailing /*.* item = item[:-4] recurse = True # Scan the folder for files self._scan_directory(item, recurse, acceptable_list) # Since the slashes are all windows (No matter what # host this script is running on, the sort will yield consistent # results so it doesn't matter what platform generated the # file list, it's the same output. self.codefiles = sorted( self.file_list, key=attrgetter('relative_pathname')) self._source_include_list = sorted(self.include_list) # Cleanup self.file_list = None self.include_list = None del self.exclude_list_regex ######################################## def __repr__(self): """ Convert the solultion record into a human readable description Returns: Human readable string or None if the solution is invalid """ result_list = [] for item in self.__dict__.items(): if item[0] == 'parent': continue if item[0] == 'solution': if item[1] is None: continue result_list.append( 'Solution: "{}"'.format( item[1].name)) continue item_name = item[0][1:] if item[0].startswith('_') else item[0] result_list.append( '{0}: {1!s}'.format( item_name, item[1])) return 'Project: ' + ', '.join(result_list) def __str__(self): """ Convert the solultion record into a human readable description Returns: Human readable string or None if the solution is invalid """ return self.__repr__() ######################################## class Solution(Attributes): """ Object for processing a solution file. This object contains all of the items needed to create a solution. Attributes: source_folders_list: List of directories to scan for source code source_files_list: List of source files to include in the project vs_props: Don't allow Visual Studio props files vs_targets: Don't allow Visual Studio targets files vs_rules: Don't allow Visual Studio rules files perforce: Boolean for using perforce verbose: Boolean for verbose output suffix_enable: Boolean for enabling unique suffixes name: Solution name working_directory: Working directory for the solution ide: @ref enums.IDETypes of the IDE being generated for ide_code: IDE code for generation platform_code: Platform code for generation project_list: List of dependent projects project_type: @ref enums.ProjectTypes enum for target output _ide: Private instance of @ref enums.IDETypes """ # pylint: disable=too-many-instance-attributes source_folders_list = StringListProperty('_source_folders_list') source_files_list = StringListProperty('_source_files_list') vs_props = NoneProperty('_vs_props') vs_targets = NoneProperty('_vs_targets') vs_rules = NoneProperty('_vs_rules') perforce = BooleanProperty('_perforce') verbose = BooleanProperty('_verbose') suffix_enable = BooleanProperty('_suffix_enable') def __init__(self, name=None, **kargs): """ Init defaults. Args: name: Name of the Solution kargs: dict of arguments. """ # Init the base class super().__init__() self._ide = None self.source_folders_list = [] self.source_files_list = [] self.perforce = True self.verbose = False self.suffix_enable = True working_directory = os.getcwd() # Use a default solution name if name is None: self.name = os.path.basename(working_directory) else: self.name = name # Default directory self.working_directory = working_directory # Set a default project type if self.project_type is None: self.project_type = ProjectTypes.default() self.project_list = [] self.ide_code = '' self.platform_code = '' # Set all the variables for key in kargs.items(): setattr(self, key[0], key[1]) ######################################## def _getide(self): """ Return the ide type """ return self._ide def _setide(self, value): """ Set the IDE type with validation Args: self: The 'this' reference. value: None or new IDE type """ self._ide = validate_enum_type(value, IDETypes) ide = property(_getide, _setide) ######################################## def add_project(self, project=None, project_type=None): """ Add a project to the list of projects found in this solution. @details Given a new Project class instance, append it to the list of projects that this solution is managing. Args: self: The 'this' reference. project: Reference to an instance of a Project. project_type: Type of project to create. """ if project is None or is_string(project): project = Project(project, project_type=project_type) # Sanity check if not isinstance(project, Project): raise TypeError( "parameter 'project' must be of type Project or name") project.solution = self project.parent = self self.project_list.append(project) return project ######################################## def add_tool(self, project=None): """ Add a project to build a command line tool. See Also: add_project """ return self.add_project(project, ProjectTypes.tool) def add_app(self, project=None): """ Add a project to build an application. See Also: add_project """ return self.add_project(project, ProjectTypes.app) def add_library(self, project=None): """ Add a project to build a static library. See Also: add_project """ return self.add_project(project, ProjectTypes.library) def add_shared_library(self, project=None): """ Add a project to build a dynamic library. See Also: add_project """ return self.add_project(project, ProjectTypes.sharedlibrary) ######################################## def get_project_list(self): """ Return the project list for all sub projects. @details Create a flattened list by iterating over every sub project. Returns: List of every project in the project. """ # Make a copy of the current list project_list = list(self.project_list) # Scan the sub projects and add their projects to the # generated list. for project in self.project_list: project_list.extend(project.get_project_list()) return project_list ######################################## def set_platforms(self, platform): """ Update all configurations to a new platform. If there are no configurations, Debug and Release will be created. Args: platform: Platform to change the configurations to. """ for project in self.get_project_list(): project.set_platforms(platform) ######################################## def generate(self, ide=None): """ Generate a project file and write it out to disk. """ # pylint: disable=import-outside-toplevel # Work from a copy to ensure the original is not touched. solution = deepcopy(self) # If an ide was passed, check it, otherwise assume # solution.ide is valid if ide is not None: # Note, this will throw if IDE is not an IDE value solution.ide = ide # Grab the value back if there was conversion ide = solution.ide # Set the default IDE to whatever the system uses if ide is None: ide = IDETypes.default() solution.ide = ide # Determine which generator to use based on the selected IDE import makeprojects.watcom import makeprojects.makefile import makeprojects.visual_studio import makeprojects.visual_studio_2010 import makeprojects.codewarrior import makeprojects.xcode import makeprojects.codeblocks generator_list = ( makeprojects.visual_studio, makeprojects.visual_studio_2010, makeprojects.watcom, makeprojects.makefile, makeprojects.codewarrior, makeprojects.xcode, makeprojects.codeblocks) for generator in generator_list: if ide in generator.SUPPORTED_IDES: break else: print('IDE {} is not supported.'.format(ide)) return 10 # Convert keys that need to be regexes from *.cpp to regex solution.custom_rules = regex_dict(solution.custom_rules) all_configurations_list = [] # Process all the projects and configurations for project in solution.get_project_list(): # Handle projects project.custom_rules = regex_dict(project.custom_rules) # Purge unsupported configurations configuration_list = [] if not project.configuration_list: for item in ('Debug', 'Release'): project.add_configuration(item) for configuration in project.configuration_list: if generator.test(ide, configuration.platform): configuration_list.append(configuration) # Sort the configurations to ensure consistency configuration_list = sorted( configuration_list, key=lambda x: ( x.name, x.platform)) project.configuration_list = configuration_list all_configurations_list.extend(configuration_list) project.platform_code = platformtype_short_code(configuration_list) # Handle regexes for configurations that will be used for configuration in configuration_list: configuration.custom_rules = regex_dict( configuration.custom_rules) configuration.exclude_list_regex = translate_to_regex_match( configuration.exclude_list) # Get the platform code solution.platform_code = platformtype_short_code( all_configurations_list) # Set the IDE code solution.ide_code = ide.get_short_code() # Create project files return generator.generate(solution) def __repr__(self): """ Convert the solultion record into a human readable description Returns: Human readable string or None if the solution is invalid """ result_list = [] for item in self.__dict__.items(): if item[0] == 'parent': continue item_name = item[0][1:] if item[0].startswith('_') else item[0] result_list.append( '{0}: {1!s}'.format( item_name, item[1])) return 'Solution: ' + ', '.join(result_list) def __str__(self): """ Convert the solultion record into a human readable description Returns: Human readable string or None if the solution is invalid """ return self.__repr__()
makeprojects/core.py
codereval_python_data_155
Test if IPv4 address or not import ipaddress def is_ipv4(target): """ Test if IPv4 address or not """ try: chk = ipaddress.IPv4Address(target) return True except ipaddress.AddressValueError: return False """ Gopad OpenAPI API definition for Gopad # noqa: E501 The version of the OpenAPI document: 1.0.0-alpha1 Generated by: https://openapi-generator.tech """ import io import json import logging import re import ssl from urllib.parse import urlencode from urllib.parse import urlparse from urllib.request import proxy_bypass_environment import urllib3 import ipaddress from gopad.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError logger = logging.getLogger(__name__) class RESTResponse(io.IOBase): def __init__(self, resp): self.urllib3_response = resp self.status = resp.status self.reason = resp.reason self.data = resp.data def getheaders(self): """Returns a dictionary of the response headers.""" return self.urllib3_response.getheaders() def getheader(self, name, default=None): """Returns a given response header.""" return self.urllib3_response.getheader(name, default) class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs if configuration.verify_ssl: cert_reqs = ssl.CERT_REQUIRED else: cert_reqs = ssl.CERT_NONE addition_pool_args = {} if configuration.assert_hostname is not None: addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 if configuration.retries is not None: addition_pool_args['retries'] = configuration.retries if configuration.socket_options is not None: addition_pool_args['socket_options'] = configuration.socket_options if maxsize is None: if configuration.connection_pool_maxsize is not None: maxsize = configuration.connection_pool_maxsize else: maxsize = 4 # https pool manager if configuration.proxy and not should_bypass_proxies(configuration.host, no_proxy=configuration.no_proxy or ''): self.pool_manager = urllib3.ProxyManager( num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, proxy_url=configuration.proxy, proxy_headers=configuration.proxy_headers, **addition_pool_args ) else: self.pool_manager = urllib3.PoolManager( num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, **addition_pool_args ) def request(self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None): """Perform requests. :param method: http request method :param url: http request url :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] if post_params and body: raise ApiValueError( "body parameter cannot be used with post_params parameter." ) post_params = post_params or {} headers = headers or {} timeout = None if _request_timeout: if isinstance(_request_timeout, (int, float)): # noqa: E501,F821 timeout = urllib3.Timeout(total=_request_timeout) elif (isinstance(_request_timeout, tuple) and len(_request_timeout) == 2): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests if (method != 'DELETE') and ('Content-Type' not in headers): headers['Content-Type'] = 'application/json' if query_params: url += '?' + urlencode(query_params) if ('Content-Type' not in headers) or (re.search('json', headers['Content-Type'], re.IGNORECASE)): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( method, url, body=request_body, preload_content=_preload_content, timeout=timeout, headers=headers) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 r = self.pool_manager.request( method, url, fields=post_params, encode_multipart=False, preload_content=_preload_content, timeout=timeout, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] r = self.pool_manager.request( method, url, fields=post_params, encode_multipart=True, preload_content=_preload_content, timeout=timeout, headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is # provided in serialized form elif isinstance(body, str) or isinstance(body, bytes): request_body = body r = self.pool_manager.request( method, url, body=request_body, preload_content=_preload_content, timeout=timeout, headers=headers) else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided arguments. Please check that your arguments match declared content type.""" raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, fields=query_params, preload_content=_preload_content, timeout=timeout, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) if _preload_content: r = RESTResponse(r) # log response body logger.debug("response body: %s", r.data) if not 200 <= r.status <= 299: if r.status == 401: raise UnauthorizedException(http_resp=r) if r.status == 403: raise ForbiddenException(http_resp=r) if r.status == 404: raise NotFoundException(http_resp=r) if 500 <= r.status <= 599: raise ServiceException(http_resp=r) raise ApiException(http_resp=r) return r def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("GET", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("HEAD", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) # end of class RESTClientObject def is_ipv4(target): """ Test if IPv4 address or not """ try: chk = ipaddress.IPv4Address(target) return True except ipaddress.AddressValueError: return False def in_ipv4net(target, net): """ Test if target belongs to given IPv4 network """ try: nw = ipaddress.IPv4Network(net) ip = ipaddress.IPv4Address(target) if ip in nw: return True return False except ipaddress.AddressValueError: return False except ipaddress.NetmaskValueError: return False def should_bypass_proxies(url, no_proxy=None): """ Yet another requests.should_bypass_proxies Test if proxies should not be used for a particular url. """ parsed = urlparse(url) # special cases if parsed.hostname in [None, '']: return True # special cases if no_proxy in [None , '']: return False if no_proxy == '*': return True no_proxy = no_proxy.lower().replace(' ',''); entries = ( host for host in no_proxy.split(',') if host ) if is_ipv4(parsed.hostname): for item in entries: if in_ipv4net(parsed.hostname, item): return True return proxy_bypass_environment(parsed.hostname, {'no': no_proxy} )
gopad/rest.py
codereval_python_data_156
Find the roots in some sort of transitive hierarchy. find_roots(graph, rdflib.RDFS.subClassOf) will return a set of all roots of the sub-class hierarchy Assumes triple of the form (child, prop, parent), i.e. the direction of RDFS.subClassOf or SKOS.broader import rdflib def find_roots( graph: "Graph", prop: "URIRef", roots: Optional[Set["Node"]] = None ) -> Set["Node"]: """ Find the roots in some sort of transitive hierarchy. find_roots(graph, rdflib.RDFS.subClassOf) will return a set of all roots of the sub-class hierarchy Assumes triple of the form (child, prop, parent), i.e. the direction of RDFS.subClassOf or SKOS.broader """ non_roots: Set[Node] = set() if roots is None: roots = set() for x, y in graph.subject_objects(prop): non_roots.add(x) if x in roots: roots.remove(x) if y not in non_roots: roots.add(y) return roots """ Some utility functions. Miscellaneous utilities * list2set * first * uniq * more_than Term characterisation and generation * to_term * from_n3 Date/time utilities * date_time * parse_date_time """ from calendar import timegm from os.path import splitext # from time import daylight from time import altzone, gmtime, localtime, time, timezone from typing import ( TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Set, Tuple, TypeVar, ) import rdflib.graph # avoid circular dependency from rdflib.compat import sign from rdflib.namespace import XSD, Namespace, NamespaceManager from rdflib.term import BNode, IdentifiedNode, Literal, Node, URIRef if TYPE_CHECKING: from rdflib.graph import Graph __all__ = [ "list2set", "first", "uniq", "more_than", "to_term", "from_n3", "date_time", "parse_date_time", "guess_format", "find_roots", "get_tree", "_coalesce", ] def list2set(seq): """ Return a new list without duplicates. Preserves the order, unlike set(seq) """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)] def first(seq): """ return the first element in a python sequence for graphs, use graph.value instead """ for result in seq: return result return None def uniq(sequence, strip=0): """removes duplicate strings from the sequence.""" if strip: return set(s.strip() for s in sequence) else: return set(sequence) def more_than(sequence, number): "Returns 1 if sequence has more items than number and 0 if not." i = 0 for item in sequence: i += 1 if i > number: return 1 return 0 def to_term(s, default=None): """ Creates and returns an Identifier of type corresponding to the pattern of the given positional argument string ``s``: '' returns the ``default`` keyword argument value or ``None`` '<s>' returns ``URIRef(s)`` (i.e. without angle brackets) '"s"' returns ``Literal(s)`` (i.e. without doublequotes) '_s' returns ``BNode(s)`` (i.e. without leading underscore) """ if not s: return default elif s.startswith("<") and s.endswith(">"): return URIRef(s[1:-1]) elif s.startswith('"') and s.endswith('"'): return Literal(s[1:-1]) elif s.startswith("_"): return BNode(s) else: msg = "Unrecognised term syntax: '%s'" % s raise Exception(msg) def from_n3(s: str, default=None, backend=None, nsm=None): r''' Creates the Identifier corresponding to the given n3 string. >>> from_n3('<http://ex.com/foo>') == URIRef('http://ex.com/foo') True >>> from_n3('"foo"@de') == Literal('foo', lang='de') True >>> from_n3('"""multi\nline\nstring"""@en') == Literal( ... 'multi\nline\nstring', lang='en') True >>> from_n3('42') == Literal(42) True >>> from_n3(Literal(42).n3()) == Literal(42) True >>> from_n3('"42"^^xsd:integer') == Literal(42) True >>> from rdflib import RDFS >>> from_n3('rdfs:label') == RDFS['label'] True >>> nsm = NamespaceManager(rdflib.graph.Graph()) >>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/') >>> berlin = URIRef('http://dbpedia.org/resource/Berlin') >>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin True ''' if not s: return default if s.startswith("<"): # Hack: this should correctly handle strings with either native unicode # characters, or \u1234 unicode escapes. return URIRef(s[1:-1].encode("raw-unicode-escape").decode("unicode-escape")) elif s.startswith('"'): if s.startswith('"""'): quotes = '"""' else: quotes = '"' value, rest = s.rsplit(quotes, 1) value = value[len(quotes) :] # strip leading quotes datatype = None language = None # as a given datatype overrules lang-tag check for it first dtoffset = rest.rfind("^^") if dtoffset >= 0: # found a datatype # datatype has to come after lang-tag so ignore everything before # see: http://www.w3.org/TR/2011/WD-turtle-20110809/ # #prod-turtle2-RDFLiteral datatype = from_n3(rest[dtoffset + 2 :], default, backend, nsm) else: if rest.startswith("@"): language = rest[1:] # strip leading at sign value = value.replace(r"\"", '"') # unicode-escape interprets \xhh as an escape sequence, # but n3 does not define it as such. value = value.replace(r"\x", r"\\x") # Hack: this should correctly handle strings with either native unicode # characters, or \u1234 unicode escapes. value = value.encode("raw-unicode-escape").decode("unicode-escape") return Literal(value, language, datatype) elif s == "true" or s == "false": return Literal(s == "true") elif ( s.lower() .replace('.', '', 1) .replace('-', '', 1) .replace('e', '', 1) .isnumeric() ): if "e" in s.lower(): return Literal(s, datatype=XSD.double) if "." in s: return Literal(float(s), datatype=XSD.decimal) return Literal(int(s), datatype=XSD.integer) elif s.startswith("{"): identifier = from_n3(s[1:-1]) return rdflib.graph.QuotedGraph(backend, identifier) elif s.startswith("["): identifier = from_n3(s[1:-1]) return rdflib.graph.Graph(backend, identifier) elif s.startswith("_:"): return BNode(s[2:]) elif ":" in s: if nsm is None: # instantiate default NamespaceManager and rely on its defaults nsm = NamespaceManager(rdflib.graph.Graph()) prefix, last_part = s.split(":", 1) ns = dict(nsm.namespaces())[prefix] return Namespace(ns)[last_part] else: return BNode(s) def date_time(t=None, local_time_zone=False): """http://www.w3.org/TR/NOTE-datetime ex: 1997-07-16T19:20:30Z >>> date_time(1126482850) '2005-09-11T23:54:10Z' @@ this will change depending on where it is run #>>> date_time(1126482850, local_time_zone=True) #'2005-09-11T19:54:10-04:00' >>> date_time(1) '1970-01-01T00:00:01Z' >>> date_time(0) '1970-01-01T00:00:00Z' """ if t is None: t = time() if local_time_zone: time_tuple = localtime(t) if time_tuple[8]: tz_mins = altzone // 60 else: tz_mins = timezone // 60 tzd = "-%02d:%02d" % (tz_mins // 60, tz_mins % 60) else: time_tuple = gmtime(t) tzd = "Z" year, month, day, hh, mm, ss, wd, y, z = time_tuple s = "%0004d-%02d-%02dT%02d:%02d:%02d%s" % (year, month, day, hh, mm, ss, tzd) return s def parse_date_time(val): """always returns seconds in UTC # tests are written like this to make any errors easier to understand >>> parse_date_time('2005-09-11T23:54:10Z') - 1126482850.0 0.0 >>> parse_date_time('2005-09-11T16:54:10-07:00') - 1126482850.0 0.0 >>> parse_date_time('1970-01-01T00:00:01Z') - 1.0 0.0 >>> parse_date_time('1970-01-01T00:00:00Z') - 0.0 0.0 >>> parse_date_time("2005-09-05T10:42:00") - 1125916920.0 0.0 """ if "T" not in val: val += "T00:00:00Z" ymd, time = val.split("T") hms, tz_str = time[0:8], time[8:] if not tz_str or tz_str == "Z": time = time[:-1] tz_offset = 0 else: signed_hrs = int(tz_str[:3]) mins = int(tz_str[4:6]) secs = (sign(signed_hrs) * mins + signed_hrs * 60) * 60 tz_offset = -secs year, month, day = ymd.split("-") hour, minute, second = hms.split(":") t = timegm( (int(year), int(month), int(day), int(hour), int(minute), int(second), 0, 0, 0) ) t = t + tz_offset return t SUFFIX_FORMAT_MAP = { "xml": "xml", "rdf": "xml", "owl": "xml", "n3": "n3", "ttl": "turtle", "nt": "nt", "trix": "trix", "xhtml": "rdfa", "html": "rdfa", "svg": "rdfa", "nq": "nquads", "nquads": "nquads", "trig": "trig", "json": "json-ld", "jsonld": "json-ld", "json-ld": "json-ld", } def guess_format(fpath, fmap=None) -> Optional[str]: """ Guess RDF serialization based on file suffix. Uses ``SUFFIX_FORMAT_MAP`` unless ``fmap`` is provided. Examples: >>> guess_format('path/to/file.rdf') 'xml' >>> guess_format('path/to/file.owl') 'xml' >>> guess_format('path/to/file.ttl') 'turtle' >>> guess_format('path/to/file.json') 'json-ld' >>> guess_format('path/to/file.xhtml') 'rdfa' >>> guess_format('path/to/file.svg') 'rdfa' >>> guess_format('path/to/file.xhtml', {'xhtml': 'grddl'}) 'grddl' This also works with just the suffixes, with or without leading dot, and regardless of letter case:: >>> guess_format('.rdf') 'xml' >>> guess_format('rdf') 'xml' >>> guess_format('RDF') 'xml' """ fmap = fmap or SUFFIX_FORMAT_MAP return fmap.get(_get_ext(fpath)) or fmap.get(fpath.lower()) def _get_ext(fpath, lower=True): """ Gets the file extension from a file(path); stripped of leading '.' and in lower case. Examples: >>> _get_ext("path/to/file.txt") 'txt' >>> _get_ext("OTHER.PDF") 'pdf' >>> _get_ext("noext") '' >>> _get_ext(".rdf") 'rdf' """ ext = splitext(fpath)[-1] if ext == "" and fpath.startswith("."): ext = fpath if lower: ext = ext.lower() if ext.startswith("."): ext = ext[1:] return ext def find_roots( graph: "Graph", prop: "URIRef", roots: Optional[Set["Node"]] = None ) -> Set["Node"]: """ Find the roots in some sort of transitive hierarchy. find_roots(graph, rdflib.RDFS.subClassOf) will return a set of all roots of the sub-class hierarchy Assumes triple of the form (child, prop, parent), i.e. the direction of RDFS.subClassOf or SKOS.broader """ non_roots: Set[Node] = set() if roots is None: roots = set() for x, y in graph.subject_objects(prop): non_roots.add(x) if x in roots: roots.remove(x) if y not in non_roots: roots.add(y) return roots def get_tree( graph: "Graph", root: "IdentifiedNode", prop: "URIRef", mapper: Callable[["IdentifiedNode"], "IdentifiedNode"] = lambda x: x, sortkey: Optional[Callable[[Any], Any]] = None, done: Optional[Set["IdentifiedNode"]] = None, dir: str = "down", ) -> Optional[Tuple[IdentifiedNode, List[Any]]]: """ Return a nested list/tuple structure representing the tree built by the transitive property given, starting from the root given i.e. get_tree(graph, rdflib.URIRef("http://xmlns.com/foaf/0.1/Person"), rdflib.RDFS.subClassOf) will return the structure for the subClassTree below person. dir='down' assumes triple of the form (child, prop, parent), i.e. the direction of RDFS.subClassOf or SKOS.broader Any other dir traverses in the other direction """ if done is None: done = set() if root in done: # type error: Return value expected return # type: ignore[return-value] done.add(root) tree = [] branches: Iterable[IdentifiedNode] if dir == "down": branches = graph.subjects(prop, root) else: # type error: Incompatible types in assignment (expression has type "Iterable[Node]", variable has type "Iterable[IdentifiedNode]") branches = graph.objects(root, prop) # type: ignore[assignment] for branch in branches: t = get_tree(graph, branch, prop, mapper, sortkey, done, dir) if t: tree.append(t) return (mapper(root), sorted(tree, key=sortkey)) _AnyT = TypeVar("_AnyT") def _coalesce(*args: Optional[_AnyT]) -> Optional[_AnyT]: """ This is a null coalescing function, it will return the first non-`None` argument passed to it, otherwise it will return `None`. For more info regarding the rationale of this function see deferred `PEP 505 <https://peps.python.org/pep-0505/>`_. :param args: Values to consider as candidates to return, the first arg that is not `None` will be returned. If no argument is passed this function will return None. :return: The first ``arg`` that is not `None`, otherwise `None` if there are no args or if all args are `None`. """ for arg in args: if arg is not None: return arg return None
rdflib/util.py
codereval_python_data_157
Dump to a py2-unicode or py3-string import yaml def _dump_string(obj, dumper=None): """Dump to a py2-unicode or py3-string""" if PY3: return yaml.dump(obj, Dumper=dumper) else: return yaml.dump(obj, Dumper=dumper, encoding=None) from __future__ import absolute_import, division, print_function __metaclass__ = type import io import yaml from ansible.module_utils.six import PY3 from ansible.parsing.yaml.loader import AnsibleLoader from ansible.parsing.yaml.dumper import AnsibleDumper class YamlTestUtils(object): """Mixin class to combine with a unittest.TestCase subclass.""" def _loader(self, stream): """Vault related tests will want to override this. Vault cases should setup a AnsibleLoader that has the vault password.""" return AnsibleLoader(stream) def _dump_stream(self, obj, stream, dumper=None): """Dump to a py2-unicode or py3-string stream.""" if PY3: return yaml.dump(obj, stream, Dumper=dumper) else: return yaml.dump(obj, stream, Dumper=dumper, encoding=None) def _dump_string(self, obj, dumper=None): """Dump to a py2-unicode or py3-string""" if PY3: return yaml.dump(obj, Dumper=dumper) else: return yaml.dump(obj, Dumper=dumper, encoding=None) def _dump_load_cycle(self, obj): # Each pass though a dump or load revs the 'generation' # obj to yaml string string_from_object_dump = self._dump_string(obj, dumper=AnsibleDumper) # wrap a stream/file like StringIO around that yaml stream_from_object_dump = io.StringIO(string_from_object_dump) loader = self._loader(stream_from_object_dump) # load the yaml stream to create a new instance of the object (gen 2) obj_2 = loader.get_data() # dump the gen 2 objects directory to strings string_from_object_dump_2 = self._dump_string( obj_2, dumper=AnsibleDumper ) # The gen 1 and gen 2 yaml strings self.assertEqual(string_from_object_dump, string_from_object_dump_2) # the gen 1 (orig) and gen 2 py object self.assertEqual(obj, obj_2) # again! gen 3... load strings into py objects stream_3 = io.StringIO(string_from_object_dump_2) loader_3 = self._loader(stream_3) obj_3 = loader_3.get_data() string_from_object_dump_3 = self._dump_string( obj_3, dumper=AnsibleDumper ) self.assertEqual(obj, obj_3) # should be transitive, but... self.assertEqual(obj_2, obj_3) self.assertEqual(string_from_object_dump, string_from_object_dump_3) def _old_dump_load_cycle(self, obj): """Dump the passed in object to yaml, load it back up, dump again, compare.""" stream = io.StringIO() yaml_string = self._dump_string(obj, dumper=AnsibleDumper) self._dump_stream(obj, stream, dumper=AnsibleDumper) yaml_string_from_stream = stream.getvalue() # reset stream stream.seek(0) loader = self._loader(stream) # loader = AnsibleLoader(stream, vault_password=self.vault_password) obj_from_stream = loader.get_data() stream_from_string = io.StringIO(yaml_string) loader2 = self._loader(stream_from_string) # loader2 = AnsibleLoader(stream_from_string, vault_password=self.vault_password) obj_from_string = loader2.get_data() stream_obj_from_stream = io.StringIO() stream_obj_from_string = io.StringIO() if PY3: yaml.dump( obj_from_stream, stream_obj_from_stream, Dumper=AnsibleDumper ) yaml.dump( obj_from_stream, stream_obj_from_string, Dumper=AnsibleDumper ) else: yaml.dump( obj_from_stream, stream_obj_from_stream, Dumper=AnsibleDumper, encoding=None, ) yaml.dump( obj_from_stream, stream_obj_from_string, Dumper=AnsibleDumper, encoding=None, ) yaml_string_stream_obj_from_stream = stream_obj_from_stream.getvalue() yaml_string_stream_obj_from_string = stream_obj_from_string.getvalue() stream_obj_from_stream.seek(0) stream_obj_from_string.seek(0) if PY3: yaml_string_obj_from_stream = yaml.dump( obj_from_stream, Dumper=AnsibleDumper ) yaml_string_obj_from_string = yaml.dump( obj_from_string, Dumper=AnsibleDumper ) else: yaml_string_obj_from_stream = yaml.dump( obj_from_stream, Dumper=AnsibleDumper, encoding=None ) yaml_string_obj_from_string = yaml.dump( obj_from_string, Dumper=AnsibleDumper, encoding=None ) assert yaml_string == yaml_string_obj_from_stream assert ( yaml_string == yaml_string_obj_from_stream == yaml_string_obj_from_string ) assert ( yaml_string == yaml_string_obj_from_stream == yaml_string_obj_from_string == yaml_string_stream_obj_from_stream == yaml_string_stream_obj_from_string ) assert obj == obj_from_stream assert obj == obj_from_string assert obj == yaml_string_obj_from_stream assert obj == yaml_string_obj_from_string assert ( obj == obj_from_stream == obj_from_string == yaml_string_obj_from_stream == yaml_string_obj_from_string ) return { "obj": obj, "yaml_string": yaml_string, "yaml_string_from_stream": yaml_string_from_stream, "obj_from_stream": obj_from_stream, "obj_from_string": obj_from_string, "yaml_string_obj_from_string": yaml_string_obj_from_string, }
tests/unit/mock/yaml_helper.py
codereval_python_data_158
General purpose application logger. Useful mainly for debugging import os,logging def build_app_logger(name='app', logfile='app.log', debug=True): """ General purpose application logger. Useful mainly for debugging """ # level = logging.DEBUG if settings.DEBUG else logging.INFO level = logging.INFO logdir = './logs' # TODO: move this to settings if not os.path.exists(logdir): os.mkdir(logdir) logpath = os.path.join(logdir, logfile) maxBytes = 1024 * 1024 * 10 handler = RotatingFileHandler(logpath, maxBytes=maxBytes, backupCount=100) handler.setLevel(level) formatter = logging.Formatter('[%(levelname)s] %(asctime)s: %(message)s') handler.setFormatter(formatter) logger = logging.getLogger(name) logger.addHandler(handler) logger.setLevel(level) return logger import os import logging from logging.handlers import RotatingFileHandler from loguru import logger as loguru_logger from converge import settings def build_api_logger(): """ Builds multiprocess-safe (hence loguru over stdlib logger) API logger """ level = settings.API_LOGGER.LEVEL handler = settings.API_LOGGER.FILEPATH if handler: # Else log to sys.stderr by default rotation = settings.API_LOGGER.ROTATION retention = settings.API_LOGGER.RETENTION loguru_logger.add(handler, retention=retention, rotation=rotation, format="{time:YYYY-MM-DD HH:mm:ss} | {message}", enqueue=True, level=level) return loguru_logger def build_app_logger(name='app', logfile='app.log', debug=True): """ General purpose application logger. Useful mainly for debugging """ level = logging.DEBUG if settings.DEBUG else logging.INFO logdir = 'logs' # TODO: move this to settings if not os.path.exists(logdir): os.mkdir(logdir) logpath = os.path.join(logdir, logfile) maxBytes = 1024 * 1024 * 10 handler = RotatingFileHandler(logpath, maxBytes=maxBytes, backupCount=100) handler.setLevel(level) formatter = logging.Formatter('[%(levelname)s] %(asctime)s: %(message)s') handler.setFormatter(formatter) logger = logging.getLogger(name) logger.addHandler(handler) logger.setLevel(level) return logger api_logger = build_api_logger() if settings.API_LOGGER.ENABLED else None app_logger = build_app_logger()
apphelpers/loggers.py
codereval_python_data_159
Function to create an array with shape and dtype. Parameters ---------- shape : tuple shape of the array to create dtype : `numpy.dtype` data-type of the array to create import numpy as np def make_array(shape, dtype=np.dtype("float32")): """ Function to create an array with shape and dtype. Parameters ---------- shape : tuple shape of the array to create dtype : `numpy.dtype` data-type of the array to create """ return np.zeros(shape, dtype=dtype) """ Classes for spectral analysis. """ import datetime from copy import copy from math import floor from random import randint from distutils.version import LooseVersion import numpy as np from matplotlib import pyplot as plt from matplotlib.colorbar import Colorbar from matplotlib.figure import Figure from matplotlib.ticker import FuncFormatter, IndexLocator, MaxNLocator from numpy import ma from scipy import ndimage from sunpy import __version__ from sunpy.time import parse_time from radiospectra.spectrum import Spectrum from radiospectra.util import ConditionalDispatch, Parent, common_base, get_day, merge, to_signed __all__ = ["Spectrogram", "LinearTimeSpectrogram"] SUNPY_LT_1 = LooseVersion(__version__) < LooseVersion("1.0") # 1080 because that usually is the maximum vertical pixel count on modern # screens nowadays (2012). DEFAULT_YRES = 1080 # This should not be necessary, as observations do not take more than a day # but it is used for completeness' and extendibility's sake. # XXX: Leap second? SECONDS_PER_DAY = 86400 # Used for COPY_PROPERTIES REFERENCE = 0 COPY = 1 DEEPCOPY = 2 def figure(*args, **kwargs): """ Returns a new SpectroFigure, a figure extended with features useful for analysis of spectrograms. Compare pyplot.figure. """ kw = { "FigureClass": SpectroFigure, } kw.update(kwargs) return plt.figure(*args, **kw) def _min_delt(arr): deltas = arr[:-1] - arr[1:] # Multiple values at the same frequency are just thrown away # in the process of linearizaion return deltas[deltas != 0].min() def _list_formatter(lst, fun=None): """ Returns a function that takes x, pos and returns fun(lst[x]) if fun is not None, else lst[x] or "" if x is out of range. """ def _fun(x, pos): x = int(x) if x >= len(lst) or x < 0: return "" elem = lst[x] if fun is None: return elem return fun(elem) return _fun def _union(sets): """ Returns a union of sets. """ union = set() for s in sets: union |= s return union class _LinearView(object): """ Helper class for frequency channel linearization. Attributes ---------- arr : Spectrogram Spectrogram to linearize. delt : float Delta between frequency channels in linearized spectrogram. Defaults to (minimum delta / 2.) because of the Shannon sampling theorem. """ def __init__(self, arr, delt=None): self.arr = arr if delt is None: # Nyquist–Shannon sampling theorem delt = _min_delt(arr.freq_axis) / 2.0 self.delt = delt midpoints = (self.arr.freq_axis[:-1] + self.arr.freq_axis[1:]) / 2 self.midpoints = np.concatenate([midpoints, arr.freq_axis[-1:]]) self.max_mp_delt = np.min(self.midpoints[1:] - self.midpoints[:-1]) self.freq_axis = np.arange(self.arr.freq_axis[0], self.arr.freq_axis[-1], -self.delt) self.time_axis = self.arr.time_axis self.shape = (len(self), arr.data.shape[1]) def __len__(self): return int(1 + (self.arr.freq_axis[0] - self.arr.freq_axis[-1]) / self.delt) def _find(self, arr, item): if item < 0: item = item % len(self) if item >= len(self): raise IndexError freq_offset = item * self.delt freq = self.arr.freq_axis[0] - freq_offset # The idea is that when we take the biggest delta in the mid points, # we do not have to search anything that is between the beginning and # the first item that can possibly be that frequency. min_mid = int(max(0, (freq - self.midpoints[0]) // self.max_mp_delt)) for n, mid in enumerate(self.midpoints[min_mid:]): if mid <= freq: return arr[min_mid + n] return arr[min_mid + n] def __getitem__(self, item): return self._find(self.arr, item) def get_freq(self, item): return self._find(self.arr.freq_axis, item) def make_mask(self, max_dist): mask = np.zeros(self.shape, dtype=np.bool) for n, item in enumerate(range(len(self))): freq = self.arr.freq_axis[0] - item * self.delt if abs(self.get_freq(item) - freq) > max_dist: mask[n, :] = True return mask class SpectroFigure(Figure): def _init(self, data, freqs): self.data = data self.freqs = freqs def ginput_to_time(self, inp): return [self.data.start + datetime.timedelta(seconds=secs) for secs in self.ginput_to_time_secs(inp)] def ginput_to_time_secs(self, inp): return np.array([float(self.data.time_axis[x]) for x, y in inp]) def ginput_to_time_offset(self, inp): v = self.ginput_to_time_secs(inp) return v - v.min() def ginput_to_freq(self, inp): return np.array([self.freqs[y] for x, y in inp]) def time_freq(self, points=0): inp = self.ginput(points) min_ = self.ginput_to_time_secs(inp).min() start = self.data.start + datetime.timedelta(seconds=min_) return TimeFreq(start, self.ginput_to_time_offset(inp), self.ginput_to_freq(inp)) class TimeFreq(object): """ Class to use for plotting frequency vs time. Attributes ---------- start : `datetime.datetime` Start time of the plot. time : `~numpy.ndarray` Time of the data points as offset from start in seconds. freq : `~numpy.ndarray` Frequency of the data points in MHz. """ def __init__(self, start, time, freq): self.start = start self.time = time self.freq = freq def plot(self, time_fmt="%H:%M:%S", **kwargs): """ Plot the spectrum. Parameters ---------- time_fmt : str The time format in a `~datetime.datetime` compatible format **kwargs : dict Any additional plot arguments that should be used when plotting. Returns ------- fig : `~matplotlib.Figure` A plot figure. """ figure = plt.gcf() axes = figure.add_subplot(111) axes.plot(self.time, self.freq, **kwargs) xa = axes.get_xaxis() xa.set_major_formatter( FuncFormatter(lambda x, pos: (self.start + datetime.timedelta(seconds=x)).strftime(time_fmt)) ) axes.set_xlabel("Time [UT]") axes.set_ylabel("Frequency [MHz]") xa = axes.get_xaxis() for tl in xa.get_ticklabels(): tl.set_fontsize(10) tl.set_rotation(30) figure.add_axes(axes) figure.subplots_adjust(bottom=0.2) figure.subplots_adjust(left=0.2) return figure def peek(self, *args, **kwargs): """ Plot spectrum onto current axes. Parameters ---------- *args : dict **kwargs : dict Any additional plot arguments that should be used when plotting. Returns ------- fig : `~matplotlib.Figure` A plot figure. """ plt.figure() ret = self.plot(*args, **kwargs) plt.show() return ret class Spectrogram(Parent): """ Spectrogram Class. .. warning:: This module is under development! Use at your own risk. Attributes ---------- data : `~numpy.ndarray` two-dimensional array of the image data of the spectrogram. time_axis : `~numpy.ndarray` one-dimensional array containing the offset from the start for each column of data. freq_axis : `~numpy.ndarray` one-dimensional array containing information about the frequencies each row of the image corresponds to. start : `~datetime.datetime` starting time of the measurement end : `~datetime.datetime` end time of the measurement t_init : int offset from the start of the day the measurement began. If None gets automatically set from start. t_label : str label for the time axis f_label : str label for the frequency axis content : str header for the image instruments : str array instruments that recorded the data, may be more than one if it was constructed using combine_frequencies or join_many. """ # Contrary to what pylint may think, this is not an old-style class. # pylint: disable=E1002,W0142,R0902 # This needs to list all attributes that need to be # copied to maintain the object and how to handle them. COPY_PROPERTIES = [ ("time_axis", COPY), ("freq_axis", COPY), ("instruments", COPY), ("start", REFERENCE), ("end", REFERENCE), ("t_label", REFERENCE), ("f_label", REFERENCE), ("content", REFERENCE), ("t_init", REFERENCE), ] _create = ConditionalDispatch.from_existing(Parent._create) @property def shape(self): return self.data.shape @property def dtype(self): return self.data.dtype def _get_params(self): """ Implementation detail. """ return {name: getattr(self, name) for name, _ in self.COPY_PROPERTIES} def _slice(self, y_range, x_range): """ Return new spectrogram reduced to the values passed as slices. Implementation detail. """ data = self.data[y_range, x_range] params = self._get_params() soffset = 0 if x_range.start is None else x_range.start soffset = int(soffset) eoffset = self.shape[1] if x_range.stop is None else x_range.stop # pylint: disable=E1101 eoffset -= 1 eoffset = int(eoffset) params.update( { "time_axis": self.time_axis[x_range.start : x_range.stop : x_range.step] - self.time_axis[soffset], "freq_axis": self.freq_axis[y_range.start : y_range.stop : y_range.step], "start": self.start + datetime.timedelta(seconds=self.time_axis[soffset]), "end": self.start + datetime.timedelta(seconds=self.time_axis[eoffset]), "t_init": self.t_init + self.time_axis[soffset], } ) return self.__class__(data, **params) def _with_data(self, data): new = copy(self) new.data = data return new def __init__( self, data, time_axis, freq_axis, start, end, t_init=None, t_label="Time", f_label="Frequency", content="", instruments=None, ): # Because of how object creation works, there is no avoiding # unused arguments in this case. self.data = data if t_init is None: diff = start - get_day(start) t_init = diff.seconds if instruments is None: instruments = set() self.start = start self.end = end self.t_label = t_label self.f_label = f_label self.t_init = t_init self.time_axis = time_axis self.freq_axis = freq_axis self.content = content self.instruments = instruments def time_formatter(self, x, pos): """ This returns the label for the tick of value x at a specified pos on the time axis. """ # Callback, cannot avoid unused arguments. # pylint: disable=W0613 x = int(x) if x >= len(self.time_axis) or x < 0: return "" return self.format_time(self.start + datetime.timedelta(seconds=float(self.time_axis[x]))) @staticmethod def format_time(time): """ Override to configure default plotting. """ return time.strftime("%H:%M:%S") @staticmethod def format_freq(freq): """ Override to configure default plotting. """ return "{freq:0.1f}".format(freq=freq) def peek(self, *args, **kwargs): """ Plot spectrum onto current axes. Parameters ---------- *args : dict **kwargs : dict Any additional plot arguments that should be used when plotting. Returns ------- fig : `~matplotlib.Figure` A plot figure. """ figure() ret = self.plot(*args, **kwargs) plt.show() return ret def plot( self, figure=None, overlays=[], colorbar=True, vmin=None, vmax=None, linear=True, showz=True, yres=DEFAULT_YRES, max_dist=None, **matplotlib_args ): """ Plot spectrogram onto figure. Parameters ---------- figure : `~matplotlib.Figure` Figure to plot the spectrogram on. If None, new Figure is created. overlays : list List of overlays (functions that receive figure and axes and return new ones) to be applied after drawing. colorbar : bool Flag that determines whether or not to draw a colorbar. If existing figure is passed, it is attempted to overdraw old colorbar. vmin : float Clip intensities lower than vmin before drawing. vmax : float Clip intensities higher than vmax before drawing. linear : bool If set to True, "stretch" image to make frequency axis linear. showz : bool If set to True, the value of the pixel that is hovered with the mouse is shown in the bottom right corner. yres : int or None To be used in combination with linear=True. If None, sample the image with half the minimum frequency delta. Else, sample the image to be at most yres pixels in vertical dimension. Defaults to 1080 because that's a common screen size. max_dist : float or None If not None, mask elements that are further than max_dist away from actual data points (ie, frequencies that actually have data from the receiver and are not just nearest-neighbour interpolated). """ # [] as default argument is okay here because it is only read. # pylint: disable=W0102,R0914 if linear: delt = yres if delt is not None: delt = max((self.freq_axis[0] - self.freq_axis[-1]) / (yres - 1), _min_delt(self.freq_axis) / 2.0) delt = float(delt) data = _LinearView(self.clip_values(vmin, vmax), delt) freqs = np.arange(self.freq_axis[0], self.freq_axis[-1], -data.delt) else: data = np.array(self.clip_values(vmin, vmax)) freqs = self.freq_axis figure = plt.gcf() if figure.axes: axes = figure.axes[0] else: axes = figure.add_subplot(111) params = { "origin": "lower", "aspect": "auto", } params.update(matplotlib_args) if linear and max_dist is not None: toplot = ma.masked_array(data, mask=data.make_mask(max_dist)) else: toplot = data im = axes.imshow(toplot, **params) xa = axes.get_xaxis() ya = axes.get_yaxis() xa.set_major_formatter(FuncFormatter(self.time_formatter)) if linear: # Start with a number that is divisible by 5. init = (self.freq_axis[0] % 5) / data.delt nticks = 15.0 # Calculate MHz difference between major ticks. dist = (self.freq_axis[0] - self.freq_axis[-1]) / nticks # Round to next multiple of 10, at least ten. dist = max(round(dist, -1), 10) # One pixel in image space is data.delt MHz, thus we can convert # our distance between the major ticks into image space by dividing # it by data.delt. ya.set_major_locator(IndexLocator(dist / data.delt, init)) ya.set_minor_locator(IndexLocator(dist / data.delt / 10, init)) def freq_fmt(x, pos): # This is necessary because matplotlib somehow tries to get # the mid-point of the row, which we do not need here. x = x + 0.5 return self.format_freq(self.freq_axis[0] - x * data.delt) else: freq_fmt = _list_formatter(freqs, self.format_freq) ya.set_major_locator(MaxNLocator(integer=True, steps=[1, 5, 10])) ya.set_major_formatter(FuncFormatter(freq_fmt)) axes.set_xlabel(self.t_label) axes.set_ylabel(self.f_label) # figure.suptitle(self.content) figure.suptitle( " ".join( [ get_day(self.start).strftime("%d %b %Y"), "Radio flux density", "(" + ", ".join(self.instruments) + ")", ] ) ) for tl in xa.get_ticklabels(): tl.set_fontsize(10) tl.set_rotation(30) figure.add_axes(axes) figure.subplots_adjust(bottom=0.2) figure.subplots_adjust(left=0.2) if showz: axes.format_coord = self._mk_format_coord(data, figure.gca().format_coord) if colorbar: if len(figure.axes) > 1: Colorbar(figure.axes[1], im).set_label("Intensity") else: figure.colorbar(im).set_label("Intensity") for overlay in overlays: figure, axes = overlay(figure, axes) for ax in figure.axes: ax.autoscale() if isinstance(figure, SpectroFigure): figure._init(self, freqs) return axes def __getitem__(self, key): only_y = not isinstance(key, tuple) if only_y: return self.data[int(key)] elif isinstance(key[0], slice) and isinstance(key[1], slice): return self._slice(key[0], key[1]) elif isinstance(key[1], slice): # return Spectrum( # XXX: Right class # super(Spectrogram, self).__getitem__(key), # self.time_axis[key[1].start:key[1].stop:key[1].step] # ) return np.array(self.data[key]) elif isinstance(key[0], slice): return Spectrum(self.data[key], self.freq_axis[key[0].start : key[0].stop : key[0].step]) return self.data[int(key)] def clip_freq(self, vmin=None, vmax=None): """ Return a new spectrogram only consisting of frequencies in the interval. [vmin, vmax]. Parameters ---------- vmin : float All frequencies in the result are greater or equal to this. vmax : float All frequencies in the result are smaller or equal to this. """ left = 0 if vmax is not None: while self.freq_axis[left] > vmax: left += 1 right = len(self.freq_axis) - 1 if vmin is not None: while self.freq_axis[right] < vmin: right -= 1 return self[left : right + 1, :] def auto_find_background(self, amount=0.05): """ Automatically find the background. This is done by first subtracting the average value in each channel and then finding those times which have the lowest standard deviation. Parameters ---------- amount : float The percent amount (out of 1) of lowest standard deviation to consider. """ # pylint: disable=E1101,E1103 data = self.data.astype(to_signed(self.dtype)) # Subtract average value from every frequency channel. tmp = data - np.average(self.data, 1).reshape(self.shape[0], 1) # Get standard deviation at every point of time. # Need to convert because otherwise this class's __getitem__ # is used which assumes two-dimensionality. sdevs = np.asarray(np.std(tmp, 0)) # Get indices of values with lowest standard deviation. cand = sorted(list(range(self.shape[1])), key=lambda y: sdevs[y]) # Only consider the best 5 %. return cand[: max(1, int(amount * len(cand)))] def auto_const_bg(self): """ Automatically determine background. """ realcand = self.auto_find_background() bg = np.average(self.data[:, realcand], 1) return bg.reshape(self.shape[0], 1) def subtract_bg(self): """ Perform constant background subtraction. """ return self._with_data(self.data - self.auto_const_bg()) def randomized_auto_const_bg(self, amount): """ Automatically determine background. Only consider a randomly chosen subset of the image. Parameters ---------- amount : int Size of random sample that is considered for calculation of the background. """ cols = [randint(0, self.shape[1] - 1) for _ in range(amount)] # pylint: disable=E1101,E1103 data = self.data.astype(to_signed(self.dtype)) # Subtract average value from every frequency channel. tmp = data - np.average(self.data, 1).reshape(self.shape[0], 1) # Get standard deviation at every point of time. # Need to convert because otherwise this class's __getitem__ # is used which assumes two-dimensionality. tmp = tmp[:, cols] sdevs = np.asarray(np.std(tmp, 0)) # Get indices of values with lowest standard deviation. cand = sorted(list(range(amount)), key=lambda y: sdevs[y]) # Only consider the best 5 %. realcand = cand[: max(1, int(0.05 * len(cand)))] # Average the best 5 % bg = np.average(self[:, [cols[r] for r in realcand]], 1) return bg.reshape(self.shape[0], 1) def randomized_subtract_bg(self, amount): """ Perform randomized constant background subtraction. Does not produce the same result every time it is run. Parameters ---------- amount : int Size of random sample that is considered for calculation of the background. """ return self._with_data(self.data - self.randomized_auto_const_bg(amount)) def clip_values(self, vmin=None, vmax=None, out=None): """ Clip intensities to be in the interval [vmin, vmax]. Any values greater than the maximum will be assigned the maximum, any values lower than the minimum will be assigned the minimum. If either is left out or None, do not clip at that side of the interval. Parameters ---------- min : int or float New minimum value for intensities. max : int or float New maximum value for intensities """ # pylint: disable=E1101 if vmin is None: vmin = int(self.data.min()) if vmax is None: vmax = int(self.data.max()) return self._with_data(self.data.clip(vmin, vmax, out)) def rescale(self, vmin=0, vmax=1, dtype=np.dtype("float32")): """ Rescale intensities to [vmin, vmax]. Note that vmin ≠ vmax and spectrogram.min() ≠ spectrogram.max(). Parameters ---------- vmin : float or int New minimum value in the resulting spectrogram. vmax : float or int New maximum value in the resulting spectrogram. dtype : `numpy.dtype` Data-type of the resulting spectrogram. """ if vmax == vmin: raise ValueError("Maximum and minimum must be different.") if self.data.max() == self.data.min(): raise ValueError("Spectrogram needs to contain distinct values.") data = self.data.astype(dtype) # pylint: disable=E1101 return self._with_data( vmin + (vmax - vmin) * (data - self.data.min()) / (self.data.max() - self.data.min()) # pylint: disable=E1101 # pylint: disable=E1101 ) def interpolate(self, frequency): """ Linearly interpolate intensity at unknown frequency using linear interpolation of its two neighbours. Parameters ---------- frequency : float or int Unknown frequency for which to linearly interpolate the intensities. freq_axis[0] >= frequency >= self_freq_axis[-1] """ lfreq, lvalue = None, None for freq, value in zip(self.freq_axis, self.data[:, :]): if freq < frequency: break lfreq, lvalue = freq, value else: raise ValueError("Frequency not in interpolation range") if lfreq is None: raise ValueError("Frequency not in interpolation range") diff = frequency - freq # pylint: disable=W0631 ldiff = lfreq - frequency return (ldiff * value + diff * lvalue) / (diff + ldiff) # pylint: disable=W0631 def linearize_freqs(self, delta_freq=None): """ Rebin frequencies so that the frequency axis is linear. Parameters ---------- delta_freq : float Difference between consecutive values on the new frequency axis. Defaults to half of smallest delta in current frequency axis. Compare Nyquist-Shannon sampling theorem. """ if delta_freq is None: # Nyquist–Shannon sampling theorem delta_freq = _min_delt(self.freq_axis) / 2.0 nsize = int((self.freq_axis.max() - self.freq_axis.min()) / delta_freq + 1) new = np.zeros((int(nsize), self.shape[1]), dtype=self.data.dtype) freqs = self.freq_axis - self.freq_axis.max() freqs = freqs / delta_freq midpoints = np.round((freqs[:-1] + freqs[1:]) / 2) fillto = np.concatenate([midpoints - 1, np.round([freqs[-1]]) - 1]) fillfrom = np.concatenate([np.round([freqs[0]]), midpoints - 1]) fillto = np.abs(fillto) fillfrom = np.abs(fillfrom) for row, from_, to_ in zip(self, fillfrom, fillto): new[int(from_) : int(to_)] = row vrs = self._get_params() vrs.update({"freq_axis": np.linspace(self.freq_axis.max(), self.freq_axis.min(), nsize)}) return self.__class__(new, **vrs) def freq_overlap(self, other): """ Get frequency range present in both spectrograms. Returns (min, max) tuple. Parameters ---------- other : Spectrogram other spectrogram with which to look for frequency overlap """ lower = max(self.freq_axis[-1], other.freq_axis[-1]) upper = min(self.freq_axis[0], other.freq_axis[0]) if lower > upper: raise ValueError("No overlap.") return lower, upper def time_to_x(self, time): """ Return x-coordinate in spectrogram that corresponds to the passed `~datetime.datetime` value. Parameters ---------- time : `~sunpy.time.parse_time` compatible str `~datetime.datetime` to find the x coordinate for. """ diff = time - self.start diff_s = SECONDS_PER_DAY * diff.days + diff.seconds if self.time_axis[-1] < diff_s < 0: raise ValueError("Out of bounds") for n, elem in enumerate(self.time_axis): if diff_s < elem: return n - 1 # The last element is the searched one. return n def at_freq(self, freq): return self[np.nonzero(self.freq_axis == freq)[0], :] @staticmethod def _mk_format_coord(spec, fmt_coord): def format_coord(x, y): shape = list(map(int, spec.shape)) xint, yint = int(x), int(y) if 0 <= xint < shape[1] and 0 <= yint < shape[0]: pixel = spec[yint][xint] else: pixel = "" return "{!s} z={!s}".format(fmt_coord(x, y), pixel) return format_coord class LinearTimeSpectrogram(Spectrogram): """ Spectrogram evenly sampled in time. Attributes ---------- t_delt : float difference between the items on the time axis """ # pylint: disable=E1002 COPY_PROPERTIES = Spectrogram.COPY_PROPERTIES + [ ("t_delt", REFERENCE), ] def __init__( self, data, time_axis, freq_axis, start, end, t_init=None, t_delt=None, t_label="Time", f_label="Frequency", content="", instruments=None, ): if t_delt is None: t_delt = _min_delt(freq_axis) super(LinearTimeSpectrogram, self).__init__( data, time_axis, freq_axis, start, end, t_init, t_label, f_label, content, instruments ) self.t_delt = t_delt @staticmethod def make_array(shape, dtype=np.dtype("float32")): """ Function to create an array with shape and dtype. Parameters ---------- shape : tuple shape of the array to create dtype : `numpy.dtype` data-type of the array to create """ return np.zeros(shape, dtype=dtype) @staticmethod def memmap(filename): """ Return function that takes shape and dtype and returns a memory mapped array. Parameters ---------- filename : str File to store the memory mapped array in. """ return lambda shape, dtype=np.dtype("float32"): np.memmap(filename, mode="write", shape=shape, dtype=dtype) def resample_time(self, new_delt): """ Rescale image so that the difference in time between pixels is new_delt seconds. Parameters ---------- new_delt : float New delta between consecutive values. """ if self.t_delt == new_delt: return self factor = self.t_delt / float(new_delt) # The last data-point does not change! new_size = floor((self.shape[1] - 1) * factor + 1) # pylint: disable=E1101 data = ndimage.zoom(self.data, (1, new_size / self.shape[1])) # pylint: disable=E1101 params = self._get_params() params.update( { "time_axis": np.linspace( self.time_axis[0], self.time_axis[int((new_size - 1) * new_delt / self.t_delt)], new_size ), "t_delt": new_delt, } ) return self.__class__(data, **params) JOIN_REPEAT = object() @classmethod def join_many(cls, specs, mk_arr=None, nonlinear=False, maxgap=0, fill=JOIN_REPEAT): """ Produce new Spectrogram that contains spectrograms joined together in time. Parameters ---------- specs : list List of spectrograms to join together in time. nonlinear : bool If True, leave out gaps between spectrograms. Else, fill them with the value specified in fill. maxgap : float, int or None Largest gap to allow in second. If None, allow gap of arbitrary size. fill : float or int Value to fill missing values (assuming nonlinear=False) with. Can be LinearTimeSpectrogram.JOIN_REPEAT to repeat the values for the time just before the gap. mk_array: function Function that is called to create the resulting array. Can be set to LinearTimeSpectrogram.memap(filename) to create a memory mapped result array. """ # XXX: Only load header and load contents of files # on demand. mask = None if mk_arr is None: mk_arr = cls.make_array specs = sorted(specs, key=lambda x: x.start) freqs = specs[0].freq_axis if not all(np.array_equal(freqs, sp.freq_axis) for sp in specs): raise ValueError("Frequency channels do not match.") # Smallest time-delta becomes the common time-delta. min_delt = min(sp.t_delt for sp in specs) dtype_ = max(sp.dtype for sp in specs) specs = [sp.resample_time(min_delt) for sp in specs] size = sum(sp.shape[1] for sp in specs) data = specs[0] start_day = data.start xs = [] last = data for elem in specs[1:]: e_init = SECONDS_PER_DAY * (get_day(elem.start) - get_day(start_day)).days + elem.t_init x = int((e_init - last.t_init) / min_delt) xs.append(x) diff = last.shape[1] - x if maxgap is not None and -diff > maxgap / min_delt: raise ValueError("Too large gap.") # If we leave out undefined values, we do not want to # add values here if x > t_res. if nonlinear: size -= max(0, diff) else: size -= diff last = elem # The non existing element after the last one starts after # the last one. Needed to keep implementation below sane. xs.append(specs[-1].shape[1]) # We do that here so the user can pass a memory mapped # array if they'd like to. arr = mk_arr((data.shape[0], size), dtype_) time_axis = np.zeros((size,)) sx = 0 # Amount of pixels left out due to non-linearity. Needs to be # considered for correct time axes. sd = 0 for x, elem in zip(xs, specs): diff = x - elem.shape[1] e_time_axis = elem.time_axis elem = elem.data if x > elem.shape[1]: if nonlinear: x = elem.shape[1] else: # If we want to stay linear, fill up the missing # pixels with placeholder zeros. filler = np.zeros((data.shape[0], diff)) if fill is cls.JOIN_REPEAT: filler[:, :] = elem[:, -1, np.newaxis] else: filler[:] = fill minimum = e_time_axis[-1] e_time_axis = np.concatenate( [e_time_axis, np.linspace(minimum + min_delt, minimum + diff * min_delt, diff)] ) elem = np.concatenate([elem, filler], 1) arr[:, sx : sx + x] = elem[:, :x] if diff > 0: if mask is None: mask = np.zeros((data.shape[0], size), dtype=np.uint8) mask[:, sx + x - diff : sx + x] = 1 time_axis[sx : sx + x] = e_time_axis[:x] + data.t_delt * (sx + sd) if nonlinear: sd += max(0, diff) sx += x params = { "time_axis": time_axis, "freq_axis": data.freq_axis, "start": data.start, "end": specs[-1].end, "t_delt": data.t_delt, "t_init": data.t_init, "t_label": data.t_label, "f_label": data.f_label, "content": data.content, "instruments": _union(spec.instruments for spec in specs), } if mask is not None: arr = ma.array(arr, mask=mask) if nonlinear: del params["t_delt"] return Spectrogram(arr, **params) return common_base(specs)(arr, **params) def time_to_x(self, time): """ Return x-coordinate in spectrogram that corresponds to the passed datetime value. Parameters ---------- time : `~sunpy.time.parse_time` compatible str `datetime.datetime` to find the x coordinate for. """ # This is impossible for frequencies because that mapping # is not injective. if SUNPY_LT_1: time = parse_time(time) else: time = parse_time(time).datetime diff = time - self.start diff_s = SECONDS_PER_DAY * diff.days + diff.seconds result = diff_s // self.t_delt if 0 <= result <= self.shape[1]: # pylint: disable=E1101 return result raise ValueError("Out of range.") @staticmethod def intersect_time(specs): """ Return slice of spectrograms that is present in all of the ones passed. Parameters ---------- specs : list List of spectrograms of which to find the time intersections. """ delt = min(sp.t_delt for sp in specs) start = max(sp.t_init for sp in specs) # XXX: Could do without resampling by using # sp.t_init below, not sure if good idea. specs = [sp.resample_time(delt) for sp in specs] cut = [sp[:, int((start - sp.t_init) / delt) :] for sp in specs] length = min(sp.shape[1] for sp in cut) return [sp[:, :length] for sp in cut] @classmethod def combine_frequencies(cls, specs): """ Return new spectrogram that contains frequencies from all the spectrograms in spec. Only returns time intersection of all of them. Parameters ---------- spec : list List of spectrograms of which to combine the frequencies into one. """ if not specs: raise ValueError("Need at least one spectrogram.") specs = cls.intersect_time(specs) one = specs[0] dtype_ = max(sp.dtype for sp in specs) fsize = sum(sp.shape[0] for sp in specs) new = np.zeros((fsize, one.shape[1]), dtype=dtype_) freq_axis = np.zeros((fsize,)) for n, (data, row) in enumerate( merge([[(sp, n) for n in range(sp.shape[0])] for sp in specs], key=lambda x: x[0].freq_axis[x[1]]) ): new[n, :] = data[row, :] freq_axis[n] = data.freq_axis[row] params = { "time_axis": one.time_axis, # Should be equal "freq_axis": freq_axis, "start": one.start, "end": one.end, "t_delt": one.t_delt, "t_init": one.t_init, "t_label": one.t_label, "f_label": one.f_label, "content": one.content, "instruments": _union(spec.instruments for spec in specs), } return common_base(specs)(new, **params) def check_linearity(self, err=None, err_factor=None): """ Check linearity of time axis. If err is given, tolerate absolute derivation from average delta up to err. If err_factor is given, tolerate up to err_factor * average_delta. If both are given, TypeError is raised. Default to err=0. Parameters ---------- err : float Absolute difference each delta is allowed to diverge from the average. Cannot be used in combination with err_factor. err_factor : float Relative difference each delta is allowed to diverge from the average, i.e. err_factor * average. Cannot be used in combination with err. """ deltas = self.time_axis[:-1] - self.time_axis[1:] avg = np.average(deltas) if err is None and err_factor is None: err = 0 elif err is None: err = abs(err_factor * avg) elif err_factor is not None: raise TypeError("Only supply err or err_factor, not both") return (abs(deltas - avg) <= err).all() def in_interval(self, start=None, end=None): """ Return part of spectrogram that lies in [start, end). Parameters ---------- start : None or `~datetime.datetime` or `~sunpy.time.parse_time` compatible string or time string Start time of the part of the spectrogram that is returned. If the measurement only spans over one day, a colon separated string representing the time can be passed. end : None or `~datetime.datetime` or `~sunpy.time.parse_time` compatible string or time string See start. """ if start is not None: try: if SUNPY_LT_1: start = parse_time(start) else: start = parse_time(start).datetime except ValueError: # XXX: We could do better than that. if get_day(self.start) != get_day(self.end): raise TypeError("Time ambiguous because data spans over more than one day") start = datetime.datetime( self.start.year, self.start.month, self.start.day, *list(map(int, start.split(":"))) ) start = self.time_to_x(start) if end is not None: try: if SUNPY_LT_1: end = parse_time(end) else: end = parse_time(end).datetime except ValueError: if get_day(self.start) != get_day(self.end): raise TypeError("Time ambiguous because data spans over more than one day") end = datetime.datetime( self.start.year, self.start.month, self.start.day, *list(map(int, end.split(":"))) ) end = self.time_to_x(end) if start: start = int(start) if end: end = int(end) return self[:, start:end]
radiospectra/spectrogram.py
codereval_python_data_160
Gaussian centered around 0.2 with a sigma of 0.1. import numpy as np def gaussian(x): """ Gaussian centered around 0.2 with a sigma of 0.1. """ mu = 0.2 sigma = 0.1 return np.exp(-(x-mu)**2/sigma**2) import random import numpy as np from concert.tests import assert_almost_equal, TestCase, slow from concert.quantities import q from concert.devices.monochromators.dummy import\ Monochromator as DummyMonochromator from concert.devices.monochromators import base from concert.devices.monochromators.base import Monochromator from concert.devices.monochromators.dummy import DoubleMonochromator from concert.devices.photodiodes.dummy import PhotoDiode as DummyPhotoDiode class WavelengthMonochromator(Monochromator): """ A monochromator which implements wavelength getter and setter. The conversion needs to be handled in the base class. """ def __init__(self): super(WavelengthMonochromator, self).__init__() self._wavelength = random.random() * 1e-10 * q.m async def _get_wavelength_real(self): return self._wavelength async def _set_wavelength_real(self, wavelength): self._wavelength = wavelength class PhotoDiode(DummyPhotoDiode): """ Photo diode that returns an intensity distribution depending on the bragg_motor2 position. """ def __init__(self, bragg_motor2): self.bragg_motor = bragg_motor2 self.function = None super().__init__() async def _get_intensity(self): x = (await self.bragg_motor.get_position()).to(q.deg).magnitude return self.function(x) * q.V class TestDummyMonochromator(TestCase): def setUp(self): super(TestDummyMonochromator, self).setUp() self.mono = DummyMonochromator() self.wave_mono = WavelengthMonochromator() self.energy = 25 * q.keV self.wavelength = 0.1 * q.nm def test_energy_mono_energy(self): self.mono.energy = self.energy assert_almost_equal(self.mono.energy, self.energy) assert_almost_equal(self.mono.wavelength, base.energy_to_wavelength(self.mono.energy)) def test_energy_mono_wavelength(self): self.mono.wavelength = self.wavelength assert_almost_equal(self.mono.wavelength, self.wavelength) assert_almost_equal(base.wavelength_to_energy(self.wavelength), self.mono.energy) def test_wavelength_mono_energy(self): self.wave_mono.energy = self.energy assert_almost_equal(self.wave_mono.energy, self.energy) assert_almost_equal(self.wave_mono.wavelength, base.energy_to_wavelength(self.wave_mono.energy)) def test_wavelength_mono_wavelength(self): # Wavelength-based monochromator. self.wave_mono.wavelength = self.wavelength assert_almost_equal(self.wave_mono.wavelength, self.wavelength) assert_almost_equal(base.wavelength_to_energy(self.wavelength), self.wave_mono.energy) @slow class TestDummyDoubleMonochromator(TestCase): def setUp(self): super(TestDummyDoubleMonochromator, self).setUp() self.mono = DoubleMonochromator() self.diode = PhotoDiode(self.mono._motor_2) def gaussian(self, x): """ Gaussian centered around 0.2 with a sigma of 0.1. """ mu = 0.2 sigma = 0.1 return np.exp(-(x-mu)**2/sigma**2) def double_gaussian(self, x): """ Double two gaussian functions centered around zero with a sigma of 0.2 each. """ mu_1 = -0.2 mu_2 = 0.2 sigma = 0.2 return np.exp(-(x - mu_1) ** 2 / sigma ** 2) + np.exp(-(x - mu_2) ** 2 / sigma ** 2) async def test_center(self): """ This test configures the diode to return a gaussian profile with the center at 0.2 deg. Then it is checked if the monochromator._motor2 is moved to 0.2 deg after the scan and the select_maximum() function. """ self.diode.function = self.gaussian await self.mono.scan_bragg_angle(diode=self.diode, tune_range=1*q.deg, n_points=100) await self.mono.select_maximum() self.assertAlmostEqual(await self.mono._motor_2.get_position(), 0.2*q.deg, 2) async def test_center_of_mass(self): """ This test configures the diode to return a hat profile with the center at 0.0 deg. Then it is checked if the monochromator._motor2 is moved to 0.0 deg after the scan and the select_center_of_mass() function. """ self.diode.function = self.double_gaussian await self.mono.scan_bragg_angle(diode=self.diode, tune_range=1*q.deg, n_points=100) await self.mono.select_center_of_mass() self.assertAlmostEqual(await self.mono._motor_2.get_position(), 0.0*q.deg, 2)
concert/tests/unit/devices/test_monochromator.py
codereval_python_data_161
Given a sequence of configuration filenames, load and validate each configuration file. Return the results as a tuple of: dict of configuration filename to corresponding parsed configuration, and sequence of logging.LogRecord instances containing any parse errors. import logging def load_configurations(config_filenames, overrides=None, resolve_env=True): ''' Given a sequence of configuration filenames, load and validate each configuration file. Return the results as a tuple of: dict of configuration filename to corresponding parsed configuration, and sequence of logging.LogRecord instances containing any parse errors. ''' # Dict mapping from config filename to corresponding parsed config dict. configs = collections.OrderedDict() logs = [] # Parse and load each configuration file. for config_filename in config_filenames: try: configs[config_filename] = validate.parse_configuration( config_filename, validate.schema_filename(), overrides, resolve_env ) except PermissionError: logs.extend( [ logging.makeLogRecord( dict( levelno=logging.WARNING, levelname='WARNING', msg='{}: Insufficient permissions to read configuration file'.format( config_filename ), ) ), ] ) except (ValueError, OSError, validate.Validation_error) as error: logs.extend( [ logging.makeLogRecord( dict( levelno=logging.CRITICAL, levelname='CRITICAL', msg='{}: Error parsing configuration file'.format(config_filename), ) ), logging.makeLogRecord( dict(levelno=logging.CRITICAL, levelname='CRITICAL', msg=error) ), ] ) return (configs, logs) import collections import copy import json import logging import os import sys import time from queue import Queue from subprocess import CalledProcessError import colorama import pkg_resources import borgmatic.commands.completion from borgmatic.borg import borg as borg_borg from borgmatic.borg import check as borg_check from borgmatic.borg import compact as borg_compact from borgmatic.borg import create as borg_create from borgmatic.borg import environment as borg_environment from borgmatic.borg import export_tar as borg_export_tar from borgmatic.borg import extract as borg_extract from borgmatic.borg import feature as borg_feature from borgmatic.borg import info as borg_info from borgmatic.borg import init as borg_init from borgmatic.borg import list as borg_list from borgmatic.borg import mount as borg_mount from borgmatic.borg import prune as borg_prune from borgmatic.borg import umount as borg_umount from borgmatic.borg import version as borg_version from borgmatic.commands.arguments import parse_arguments from borgmatic.config import checks, collect, convert, validate from borgmatic.hooks import command, dispatch, dump, monitor from borgmatic.logger import configure_logging, should_do_markup from borgmatic.signals import configure_signals from borgmatic.verbosity import verbosity_to_log_level logger = logging.getLogger(__name__) LEGACY_CONFIG_PATH = '/etc/borgmatic/config' def run_configuration(config_filename, config, arguments): ''' Given a config filename, the corresponding parsed config dict, and command-line arguments as a dict from subparser name to a namespace of parsed arguments, execute the defined prune, compact, create, check, and/or other actions. Yield a combination of: * JSON output strings from successfully executing any actions that produce JSON * logging.LogRecord instances containing errors from any actions or backup hooks that fail ''' (location, storage, retention, consistency, hooks) = ( config.get(section_name, {}) for section_name in ('location', 'storage', 'retention', 'consistency', 'hooks') ) global_arguments = arguments['global'] local_path = location.get('local_path', 'borg') remote_path = location.get('remote_path') retries = storage.get('retries', 0) retry_wait = storage.get('retry_wait', 0) borg_environment.initialize(storage) encountered_error = None error_repository = '' using_primary_action = {'prune', 'compact', 'create', 'check'}.intersection(arguments) monitoring_log_level = verbosity_to_log_level(global_arguments.monitoring_verbosity) try: local_borg_version = borg_version.local_borg_version(local_path) except (OSError, CalledProcessError, ValueError) as error: yield from log_error_records( '{}: Error getting local Borg version'.format(config_filename), error ) return try: if using_primary_action: dispatch.call_hooks( 'initialize_monitor', hooks, config_filename, monitor.MONITOR_HOOK_NAMES, monitoring_log_level, global_arguments.dry_run, ) if using_primary_action: dispatch.call_hooks( 'ping_monitor', hooks, config_filename, monitor.MONITOR_HOOK_NAMES, monitor.State.START, monitoring_log_level, global_arguments.dry_run, ) except (OSError, CalledProcessError) as error: if command.considered_soft_failure(config_filename, error): return encountered_error = error yield from log_error_records('{}: Error pinging monitor'.format(config_filename), error) if not encountered_error: repo_queue = Queue() for repo in location['repositories']: repo_queue.put((repo, 0),) while not repo_queue.empty(): repository_path, retry_num = repo_queue.get() timeout = retry_num * retry_wait if timeout: logger.warning(f'{config_filename}: Sleeping {timeout}s before next retry') time.sleep(timeout) try: yield from run_actions( arguments=arguments, config_filename=config_filename, location=location, storage=storage, retention=retention, consistency=consistency, hooks=hooks, local_path=local_path, remote_path=remote_path, local_borg_version=local_borg_version, repository_path=repository_path, ) except (OSError, CalledProcessError, ValueError) as error: if retry_num < retries: repo_queue.put((repository_path, retry_num + 1),) tuple( # Consume the generator so as to trigger logging. log_error_records( '{}: Error running actions for repository'.format(repository_path), error, levelno=logging.WARNING, log_command_error_output=True, ) ) logger.warning( f'{config_filename}: Retrying... attempt {retry_num + 1}/{retries}' ) continue if command.considered_soft_failure(config_filename, error): return yield from log_error_records( '{}: Error running actions for repository'.format(repository_path), error ) encountered_error = error error_repository = repository_path if not encountered_error: try: if using_primary_action: dispatch.call_hooks( 'ping_monitor', hooks, config_filename, monitor.MONITOR_HOOK_NAMES, monitor.State.FINISH, monitoring_log_level, global_arguments.dry_run, ) dispatch.call_hooks( 'destroy_monitor', hooks, config_filename, monitor.MONITOR_HOOK_NAMES, monitoring_log_level, global_arguments.dry_run, ) except (OSError, CalledProcessError) as error: if command.considered_soft_failure(config_filename, error): return encountered_error = error yield from log_error_records('{}: Error pinging monitor'.format(config_filename), error) if encountered_error and using_primary_action: try: command.execute_hook( hooks.get('on_error'), hooks.get('umask'), config_filename, 'on-error', global_arguments.dry_run, repository=error_repository, error=encountered_error, output=getattr(encountered_error, 'output', ''), ) dispatch.call_hooks( 'ping_monitor', hooks, config_filename, monitor.MONITOR_HOOK_NAMES, monitor.State.FAIL, monitoring_log_level, global_arguments.dry_run, ) dispatch.call_hooks( 'destroy_monitor', hooks, config_filename, monitor.MONITOR_HOOK_NAMES, monitoring_log_level, global_arguments.dry_run, ) except (OSError, CalledProcessError) as error: if command.considered_soft_failure(config_filename, error): return yield from log_error_records( '{}: Error running on-error hook'.format(config_filename), error ) def run_actions( *, arguments, config_filename, location, storage, retention, consistency, hooks, local_path, remote_path, local_borg_version, repository_path, ): ''' Given parsed command-line arguments as an argparse.ArgumentParser instance, the configuration filename, several different configuration dicts, local and remote paths to Borg, a local Borg version string, and a repository name, run all actions from the command-line arguments on the given repository. Yield JSON output strings from executing any actions that produce JSON. Raise OSError or subprocess.CalledProcessError if an error occurs running a command for an action or a hook. Raise ValueError if the arguments or configuration passed to action are invalid. ''' repository = os.path.expanduser(repository_path) global_arguments = arguments['global'] dry_run_label = ' (dry run; not making any changes)' if global_arguments.dry_run else '' hook_context = { 'repository': repository_path, # Deprecated: For backwards compatibility with borgmatic < 1.6.0. 'repositories': ','.join(location['repositories']), } if 'init' in arguments: logger.info('{}: Initializing repository'.format(repository)) borg_init.initialize_repository( repository, storage, arguments['init'].encryption_mode, arguments['init'].append_only, arguments['init'].storage_quota, local_path=local_path, remote_path=remote_path, ) if 'prune' in arguments: command.execute_hook( hooks.get('before_prune'), hooks.get('umask'), config_filename, 'pre-prune', global_arguments.dry_run, **hook_context, ) logger.info('{}: Pruning archives{}'.format(repository, dry_run_label)) borg_prune.prune_archives( global_arguments.dry_run, repository, storage, retention, local_path=local_path, remote_path=remote_path, stats=arguments['prune'].stats, files=arguments['prune'].files, ) command.execute_hook( hooks.get('after_prune'), hooks.get('umask'), config_filename, 'post-prune', global_arguments.dry_run, **hook_context, ) if 'compact' in arguments: command.execute_hook( hooks.get('before_compact'), hooks.get('umask'), config_filename, 'pre-compact', global_arguments.dry_run, ) if borg_feature.available(borg_feature.Feature.COMPACT, local_borg_version): logger.info('{}: Compacting segments{}'.format(repository, dry_run_label)) borg_compact.compact_segments( global_arguments.dry_run, repository, storage, local_path=local_path, remote_path=remote_path, progress=arguments['compact'].progress, cleanup_commits=arguments['compact'].cleanup_commits, threshold=arguments['compact'].threshold, ) else: # pragma: nocover logger.info( '{}: Skipping compact (only available/needed in Borg 1.2+)'.format(repository) ) command.execute_hook( hooks.get('after_compact'), hooks.get('umask'), config_filename, 'post-compact', global_arguments.dry_run, ) if 'create' in arguments: command.execute_hook( hooks.get('before_backup'), hooks.get('umask'), config_filename, 'pre-backup', global_arguments.dry_run, **hook_context, ) logger.info('{}: Creating archive{}'.format(repository, dry_run_label)) dispatch.call_hooks( 'remove_database_dumps', hooks, repository, dump.DATABASE_HOOK_NAMES, location, global_arguments.dry_run, ) active_dumps = dispatch.call_hooks( 'dump_databases', hooks, repository, dump.DATABASE_HOOK_NAMES, location, global_arguments.dry_run, ) stream_processes = [process for processes in active_dumps.values() for process in processes] json_output = borg_create.create_archive( global_arguments.dry_run, repository, location, storage, local_borg_version, local_path=local_path, remote_path=remote_path, progress=arguments['create'].progress, stats=arguments['create'].stats, json=arguments['create'].json, files=arguments['create'].files, stream_processes=stream_processes, ) if json_output: # pragma: nocover yield json.loads(json_output) dispatch.call_hooks( 'remove_database_dumps', hooks, config_filename, dump.DATABASE_HOOK_NAMES, location, global_arguments.dry_run, ) command.execute_hook( hooks.get('after_backup'), hooks.get('umask'), config_filename, 'post-backup', global_arguments.dry_run, **hook_context, ) if 'check' in arguments and checks.repository_enabled_for_checks(repository, consistency): command.execute_hook( hooks.get('before_check'), hooks.get('umask'), config_filename, 'pre-check', global_arguments.dry_run, **hook_context, ) logger.info('{}: Running consistency checks'.format(repository)) borg_check.check_archives( repository, location, storage, consistency, local_path=local_path, remote_path=remote_path, progress=arguments['check'].progress, repair=arguments['check'].repair, only_checks=arguments['check'].only, force=arguments['check'].force, ) command.execute_hook( hooks.get('after_check'), hooks.get('umask'), config_filename, 'post-check', global_arguments.dry_run, **hook_context, ) if 'extract' in arguments: command.execute_hook( hooks.get('before_extract'), hooks.get('umask'), config_filename, 'pre-extract', global_arguments.dry_run, **hook_context, ) if arguments['extract'].repository is None or validate.repositories_match( repository, arguments['extract'].repository ): logger.info( '{}: Extracting archive {}'.format(repository, arguments['extract'].archive) ) borg_extract.extract_archive( global_arguments.dry_run, repository, borg_list.resolve_archive_name( repository, arguments['extract'].archive, storage, local_path, remote_path ), arguments['extract'].paths, location, storage, local_borg_version, local_path=local_path, remote_path=remote_path, destination_path=arguments['extract'].destination, strip_components=arguments['extract'].strip_components, progress=arguments['extract'].progress, ) command.execute_hook( hooks.get('after_extract'), hooks.get('umask'), config_filename, 'post-extract', global_arguments.dry_run, **hook_context, ) if 'export-tar' in arguments: if arguments['export-tar'].repository is None or validate.repositories_match( repository, arguments['export-tar'].repository ): logger.info( '{}: Exporting archive {} as tar file'.format( repository, arguments['export-tar'].archive ) ) borg_export_tar.export_tar_archive( global_arguments.dry_run, repository, borg_list.resolve_archive_name( repository, arguments['export-tar'].archive, storage, local_path, remote_path ), arguments['export-tar'].paths, arguments['export-tar'].destination, storage, local_path=local_path, remote_path=remote_path, tar_filter=arguments['export-tar'].tar_filter, files=arguments['export-tar'].files, strip_components=arguments['export-tar'].strip_components, ) if 'mount' in arguments: if arguments['mount'].repository is None or validate.repositories_match( repository, arguments['mount'].repository ): if arguments['mount'].archive: logger.info( '{}: Mounting archive {}'.format(repository, arguments['mount'].archive) ) else: # pragma: nocover logger.info('{}: Mounting repository'.format(repository)) borg_mount.mount_archive( repository, borg_list.resolve_archive_name( repository, arguments['mount'].archive, storage, local_path, remote_path ), arguments['mount'].mount_point, arguments['mount'].paths, arguments['mount'].foreground, arguments['mount'].options, storage, local_path=local_path, remote_path=remote_path, ) if 'restore' in arguments: # pragma: nocover if arguments['restore'].repository is None or validate.repositories_match( repository, arguments['restore'].repository ): logger.info( '{}: Restoring databases from archive {}'.format( repository, arguments['restore'].archive ) ) dispatch.call_hooks( 'remove_database_dumps', hooks, repository, dump.DATABASE_HOOK_NAMES, location, global_arguments.dry_run, ) restore_names = arguments['restore'].databases or [] if 'all' in restore_names: restore_names = [] archive_name = borg_list.resolve_archive_name( repository, arguments['restore'].archive, storage, local_path, remote_path ) found_names = set() for hook_name, per_hook_restore_databases in hooks.items(): if hook_name not in dump.DATABASE_HOOK_NAMES: continue for restore_database in per_hook_restore_databases: database_name = restore_database['name'] if restore_names and database_name not in restore_names: continue found_names.add(database_name) dump_pattern = dispatch.call_hooks( 'make_database_dump_pattern', hooks, repository, dump.DATABASE_HOOK_NAMES, location, database_name, )[hook_name] # Kick off a single database extract to stdout. extract_process = borg_extract.extract_archive( dry_run=global_arguments.dry_run, repository=repository, archive=archive_name, paths=dump.convert_glob_patterns_to_borg_patterns([dump_pattern]), location_config=location, storage_config=storage, local_borg_version=local_borg_version, local_path=local_path, remote_path=remote_path, destination_path='/', # A directory format dump isn't a single file, and therefore can't extract # to stdout. In this case, the extract_process return value is None. extract_to_stdout=bool(restore_database.get('format') != 'directory'), ) # Run a single database restore, consuming the extract stdout (if any). dispatch.call_hooks( 'restore_database_dump', {hook_name: [restore_database]}, repository, dump.DATABASE_HOOK_NAMES, location, global_arguments.dry_run, extract_process, ) dispatch.call_hooks( 'remove_database_dumps', hooks, repository, dump.DATABASE_HOOK_NAMES, location, global_arguments.dry_run, ) if not restore_names and not found_names: raise ValueError('No databases were found to restore') missing_names = sorted(set(restore_names) - found_names) if missing_names: raise ValueError( 'Cannot restore database(s) {} missing from borgmatic\'s configuration'.format( ', '.join(missing_names) ) ) if 'list' in arguments: if arguments['list'].repository is None or validate.repositories_match( repository, arguments['list'].repository ): list_arguments = copy.copy(arguments['list']) if not list_arguments.json: # pragma: nocover logger.warning('{}: Listing archives'.format(repository)) list_arguments.archive = borg_list.resolve_archive_name( repository, list_arguments.archive, storage, local_path, remote_path ) json_output = borg_list.list_archives( repository, storage, list_arguments=list_arguments, local_path=local_path, remote_path=remote_path, ) if json_output: # pragma: nocover yield json.loads(json_output) if 'info' in arguments: if arguments['info'].repository is None or validate.repositories_match( repository, arguments['info'].repository ): info_arguments = copy.copy(arguments['info']) if not info_arguments.json: # pragma: nocover logger.warning('{}: Displaying summary info for archives'.format(repository)) info_arguments.archive = borg_list.resolve_archive_name( repository, info_arguments.archive, storage, local_path, remote_path ) json_output = borg_info.display_archives_info( repository, storage, info_arguments=info_arguments, local_path=local_path, remote_path=remote_path, ) if json_output: # pragma: nocover yield json.loads(json_output) if 'borg' in arguments: if arguments['borg'].repository is None or validate.repositories_match( repository, arguments['borg'].repository ): logger.warning('{}: Running arbitrary Borg command'.format(repository)) archive_name = borg_list.resolve_archive_name( repository, arguments['borg'].archive, storage, local_path, remote_path ) borg_borg.run_arbitrary_borg( repository, storage, options=arguments['borg'].options, archive=archive_name, local_path=local_path, remote_path=remote_path, ) def load_configurations(config_filenames, overrides=None, resolve_env=True): ''' Given a sequence of configuration filenames, load and validate each configuration file. Return the results as a tuple of: dict of configuration filename to corresponding parsed configuration, and sequence of logging.LogRecord instances containing any parse errors. ''' # Dict mapping from config filename to corresponding parsed config dict. configs = collections.OrderedDict() logs = [] # Parse and load each configuration file. for config_filename in config_filenames: try: configs[config_filename] = validate.parse_configuration( config_filename, validate.schema_filename(), overrides, resolve_env ) except PermissionError: logs.extend( [ logging.makeLogRecord( dict( levelno=logging.WARNING, levelname='WARNING', msg='{}: Insufficient permissions to read configuration file'.format( config_filename ), ) ), ] ) except (ValueError, OSError, validate.Validation_error) as error: logs.extend( [ logging.makeLogRecord( dict( levelno=logging.CRITICAL, levelname='CRITICAL', msg='{}: Error parsing configuration file'.format(config_filename), ) ), logging.makeLogRecord( dict(levelno=logging.CRITICAL, levelname='CRITICAL', msg=error) ), ] ) return (configs, logs) def log_record(suppress_log=False, **kwargs): ''' Create a log record based on the given makeLogRecord() arguments, one of which must be named "levelno". Log the record (unless suppress log is set) and return it. ''' record = logging.makeLogRecord(kwargs) if suppress_log: return record logger.handle(record) return record def log_error_records( message, error=None, levelno=logging.CRITICAL, log_command_error_output=False ): ''' Given error message text, an optional exception object, an optional log level, and whether to log the error output of a CalledProcessError (if any), log error summary information and also yield it as a series of logging.LogRecord instances. Note that because the logs are yielded as a generator, logs won't get logged unless you consume the generator output. ''' level_name = logging._levelToName[levelno] if not error: yield log_record(levelno=levelno, levelname=level_name, msg=message) return try: raise error except CalledProcessError as error: yield log_record(levelno=levelno, levelname=level_name, msg=message) if error.output: # Suppress these logs for now and save full error output for the log summary at the end. yield log_record( levelno=levelno, levelname=level_name, msg=error.output, suppress_log=not log_command_error_output, ) yield log_record(levelno=levelno, levelname=level_name, msg=error) except (ValueError, OSError) as error: yield log_record(levelno=levelno, levelname=level_name, msg=message) yield log_record(levelno=levelno, levelname=level_name, msg=error) except: # noqa: E722 # Raising above only as a means of determining the error type. Swallow the exception here # because we don't want the exception to propagate out of this function. pass def get_local_path(configs): ''' Arbitrarily return the local path from the first configuration dict. Default to "borg" if not set. ''' return next(iter(configs.values())).get('location', {}).get('local_path', 'borg') def collect_configuration_run_summary_logs(configs, arguments): ''' Given a dict of configuration filename to corresponding parsed configuration, and parsed command-line arguments as a dict from subparser name to a parsed namespace of arguments, run each configuration file and yield a series of logging.LogRecord instances containing summary information about each run. As a side effect of running through these configuration files, output their JSON results, if any, to stdout. ''' # Run cross-file validation checks. if 'extract' in arguments: repository = arguments['extract'].repository elif 'list' in arguments and arguments['list'].archive: repository = arguments['list'].repository elif 'mount' in arguments: repository = arguments['mount'].repository else: repository = None if repository: try: validate.guard_configuration_contains_repository(repository, configs) except ValueError as error: yield from log_error_records(str(error)) return if not configs: yield from log_error_records( '{}: No valid configuration files found'.format( ' '.join(arguments['global'].config_paths) ) ) return if 'create' in arguments: try: for config_filename, config in configs.items(): hooks = config.get('hooks', {}) command.execute_hook( hooks.get('before_everything'), hooks.get('umask'), config_filename, 'pre-everything', arguments['global'].dry_run, ) except (CalledProcessError, ValueError, OSError) as error: yield from log_error_records('Error running pre-everything hook', error) return # Execute the actions corresponding to each configuration file. json_results = [] for config_filename, config in configs.items(): results = list(run_configuration(config_filename, config, arguments)) error_logs = tuple(result for result in results if isinstance(result, logging.LogRecord)) if error_logs: yield from log_error_records( '{}: Error running configuration file'.format(config_filename) ) yield from error_logs else: yield logging.makeLogRecord( dict( levelno=logging.INFO, levelname='INFO', msg='{}: Successfully ran configuration file'.format(config_filename), ) ) if results: json_results.extend(results) if 'umount' in arguments: logger.info('Unmounting mount point {}'.format(arguments['umount'].mount_point)) try: borg_umount.unmount_archive( mount_point=arguments['umount'].mount_point, local_path=get_local_path(configs) ) except (CalledProcessError, OSError) as error: yield from log_error_records('Error unmounting mount point', error) if json_results: sys.stdout.write(json.dumps(json_results)) if 'create' in arguments: try: for config_filename, config in configs.items(): hooks = config.get('hooks', {}) command.execute_hook( hooks.get('after_everything'), hooks.get('umask'), config_filename, 'post-everything', arguments['global'].dry_run, ) except (CalledProcessError, ValueError, OSError) as error: yield from log_error_records('Error running post-everything hook', error) def exit_with_help_link(): # pragma: no cover ''' Display a link to get help and exit with an error code. ''' logger.critical('') logger.critical('Need some help? https://torsion.org/borgmatic/#issues') sys.exit(1) def main(): # pragma: no cover configure_signals() try: arguments = parse_arguments(*sys.argv[1:]) except ValueError as error: configure_logging(logging.CRITICAL) logger.critical(error) exit_with_help_link() except SystemExit as error: if error.code == 0: raise error configure_logging(logging.CRITICAL) logger.critical('Error parsing arguments: {}'.format(' '.join(sys.argv))) exit_with_help_link() global_arguments = arguments['global'] if global_arguments.version: print(pkg_resources.require('borgmatic')[0].version) sys.exit(0) if global_arguments.bash_completion: print(borgmatic.commands.completion.bash_completion()) sys.exit(0) config_filenames = tuple(collect.collect_config_filenames(global_arguments.config_paths)) configs, parse_logs = load_configurations( config_filenames, global_arguments.overrides, global_arguments.resolve_env ) any_json_flags = any( getattr(sub_arguments, 'json', False) for sub_arguments in arguments.values() ) colorama.init( autoreset=True, strip=not should_do_markup(global_arguments.no_color or any_json_flags, configs), ) try: configure_logging( verbosity_to_log_level(global_arguments.verbosity), verbosity_to_log_level(global_arguments.syslog_verbosity), verbosity_to_log_level(global_arguments.log_file_verbosity), verbosity_to_log_level(global_arguments.monitoring_verbosity), global_arguments.log_file, ) except (FileNotFoundError, PermissionError) as error: configure_logging(logging.CRITICAL) logger.critical('Error configuring logging: {}'.format(error)) exit_with_help_link() logger.debug('Ensuring legacy configuration is upgraded') convert.guard_configuration_upgraded(LEGACY_CONFIG_PATH, config_filenames) summary_logs = parse_logs + list(collect_configuration_run_summary_logs(configs, arguments)) summary_logs_max_level = max(log.levelno for log in summary_logs) for message in ('', 'summary:'): log_record( levelno=summary_logs_max_level, levelname=logging.getLevelName(summary_logs_max_level), msg=message, ) for log in summary_logs: logger.handle(log) if summary_logs_max_level >= logging.CRITICAL: exit_with_help_link()
borgmatic/commands/borgmatic.py
codereval_python_data_162
This function returns the bytes object corresponding to ``obj`` in case it is a string using UTF-8. import numpy def force_string(obj): """ This function returns the bytes object corresponding to ``obj`` in case it is a string using UTF-8. """ if isinstance(obj,numpy.bytes_)==True or isinstance(obj,bytes)==True: return obj.decode('utf-8') return obj # ------------------------------------------------------------------- # # Copyright (C) 2006-2022, Andrew W. Steiner # # This file is part of O2sclpy. # # O2sclpy is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # O2sclpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with O2sclpy. If not, see <http://www.gnu.org/licenses/>. # # ------------------------------------------------------------------- # import sys # For os.getenv() import os # For numpy.bytes_ import numpy # To test between Linux/OSX using system() import platform # For CDLL loading import ctypes from ctypes.util import find_library def remove_spaces(string): while len(string)>0 and string[0]==' ': string=string[1:] return string def doc_replacements(s,base_list_new,ter): # Replace commands in base_list_new for i in range(0,len(base_list_new)): s=s.replace('``'+base_list_new[i][0]+'``', ter.cyan_fg()+ter.bold()+base_list_new[i][0]+ ter.default_fg()) # For ``code`` formatting s=s.replace(' ``',' ') s=s.replace('`` ',' ') s=s.replace('``, ',', ') s=s.replace('``. ','. ') # Combine two spaces to one s=s.replace(' ',' ') # For :math:`` equations s=s.replace(' :math:`',' ') s=s.replace('` ',' ') s=s.replace('`.','.') s=s.replace('`',',') return s def reformat_python_docs(cmd,doc_str,base_list_new): reflist=doc_str.split('\n') for i in range(0,len(reflist)): reflist[i]=remove_spaces(reflist[i]) #print(i,'x',reflist[i],'x') if len(reflist)<1: return if reflist[0]=='': if len(reflist)<2: return doc_str2=reflist[1] for i in range(2,len(reflist)): doc_str2=doc_str2+'\n'+reflist[i] else: doc_str2=reflist[0] for i in range(0,len(reflist)): doc_str2=doc_str2+'\n'+reflist[i] reflist2=doc_str2.split('\n\n') if False: for i in range(0,len(reflist2)): print(i,'x',reflist2[i],'x') ter=terminal_py() ncols=os.get_terminal_size().columns short='' parm_desc='' long_help='' # The short description if len(reflist2)>=2: short=reflist2[1] # The parameter description if len(reflist2)>=3: parm_desc=reflist2[2].replace('\n',' ') parm_desc=parm_desc.replace(' ',' ') sx='Command-line arguments: ``' if parm_desc[0:len(sx)]==sx: parm_desc=parm_desc[len(sx):] if parm_desc[-2:]=='``': parm_desc=parm_desc[0:-2] print('Usage: '+ter.cyan_fg()+ter.bold()+cmd+ ter.default_fg()+' '+parm_desc) print('Short description:',short) if len(reflist2)>=4: print('') print('Long description:') for j in range(3,len(reflist2)): if len(reflist2[j])>0: long_help=doc_replacements(reflist2[j].replace('\n',' '), base_list_new,ter) tmplist=wrap_line(long_help,ncols-1) if j!=3: print('') for k in range(0,len(tmplist)): print(tmplist[k]) def string_to_color(str_in): """ Convert a string to a color """ if str_in[0]=='(': temps=str_in[1:len(str_in)-1] temp2=temps.split(',') return (float(temp2[0]),float(temp2[1]),float(temp2[2])) elif str_in[0]=='[': temps=str_in[1:len(str_in)-1] temp2=temps.split(',') return [float(temp2[0]),float(temp2[1]),float(temp2[2]), float(temp2[3])] return str_in def if_yt_then_Agg(backend,argv): # Determine if yt commands are present yt_found=False for i in range(1,len(argv)): if argv[i][0:4]=='-yt-' and yt_found==False: if backend!='' and backend!='agg' and backend!='Agg': print('Backend was not set to Agg but yt commands were found.') yt_found=True backend='Agg' return backend def o2scl_get_type(o2scl,amp): """ Get the type of the current object stored in the acol_manager pointer """ # pointer types char_ptr=ctypes.POINTER(ctypes.c_char) char_ptr_ptr=ctypes.POINTER(char_ptr) int_ptr=ctypes.POINTER(ctypes.c_int) # Set up wrapper for type function type_fn=o2scl.o2scl_acol_get_type type_fn.argtypes=[ctypes.c_void_p,int_ptr,char_ptr_ptr] # Get current type it=ctypes.c_int(0) type_ptr=char_ptr() type_fn(amp,ctypes.byref(it),ctypes.byref(type_ptr)) # Construct the type as a byte string curr_type=b'' for i in range(0,it.value): curr_type=curr_type+type_ptr[i] return curr_type def table3d_get_slice(o2scl,amp,name): """ Return a slice from the current table3d object stored in the acol_manager object 'amp' """ get_fn=o2scl.o2scl_acol_get_slice get_fn.argtypes=[ctypes.c_void_p,ctypes.c_char_p, int_ptr,double_ptr_ptr, int_ptr,double_ptr_ptr,double_ptr_ptr] slice=ctypes.c_char_p(force_bytes(slice_name)) nx=ctypes.c_int(0) ptrx=double_ptr() ny=ctypes.c_int(0) ptry=double_ptr() ptrs=double_ptr() get_fn(amp,slice,ctypes.byref(nx),ctypes.byref(ptrx), ctypes.byref(ny),ctypes.byref(ptry), ctypes.byref(ptrs)) return (nx,ptrx,ny,ptry,ptrs) def table_get_column(o2scl,amp,name,return_pointer=False): """ Return a column from the current table object stored in the acol_manager object 'amp' """ # C types int_ptr=ctypes.POINTER(ctypes.c_int) double_ptr=ctypes.POINTER(ctypes.c_double) double_ptr_ptr=ctypes.POINTER(double_ptr) # Function interface get_fn=o2scl.o2scl_acol_get_column get_fn.argtypes=[ctypes.c_void_p,ctypes.c_char_p, int_ptr,double_ptr_ptr] get_fn.restype=ctypes.c_int # Arguments col=ctypes.c_char_p(force_bytes(name)) size=ctypes.c_int(0) pointer=double_ptr() # Function call get_ret=get_fn(amp,col,ctypes.byref(size),ctypes.byref(pointer)) if get_ret!=0: print('Failed to get column named "'+name+'".') return None if return_pointer: return pointer col=[pointer[i] for i in range(0,size.value)] return col def is_number(s): """ Return true if 's' is likely a number """ try: float(s) return True except ValueError: return False def force_bytes(obj): """ This function returns the bytes object corresponding to ``obj`` in case it is a string using UTF-8. """ if isinstance(obj,numpy.bytes_)==False and isinstance(obj,bytes)==False: return bytes(obj,'utf-8') return obj def force_string(obj): """ This function returns the bytes object corresponding to ``obj`` in case it is a string using UTF-8. """ if isinstance(obj,numpy.bytes_)==True or isinstance(obj,bytes)==True: return obj.decode('utf-8') return obj # This function is probably best replaced by get_str_array() below # # def parse_col_names(dset): # nc=dset['nc'].__getitem__(0) # nw=dset['nw'].__getitem__(0) # counter=dset['counter'] # data=dset['data'] # clist=[] # k=0 # for i in range(0,nw): # column='' # for j in range(0,counter[i]): # column=column+str(unichr(data[k])) # k=k+1 # clist.append(column) # return clist def default_plot(left_margin=0.14,bottom_margin=0.12, right_margin=0.04,top_margin=0.04,fontsize=16, fig_size_x=6.0,fig_size_y=6.0,ticks_in=False, rt_ticks=False,editor=False): import matplotlib.pyplot as plot """ This function sets up the O\ :sub:`2`\ sclpy ``matplotlib`` defaults. It returns a pair of objects, the figure object and axes object. The fontsize argument times 0.8 is used for the size of the font labels. Setting the ``ticks_in`` argument to ``True`` makes the ticks point inwards instead of outwards and setting ``rt_ticks`` to ``True`` puts ticks (but not labels) on the right and top edges of the plot. This function is in ``utils.py``. """ plot.rc('text',usetex=True) plot.rc('font',family='serif') plot.rcParams['lines.linewidth']=0.5 if editor: fig=plot.figure(1,figsize=(fig_size_x*2,fig_size_y)) fig.set_facecolor('white') ax_left_panel=plot.axes([0,0,0.5,1],facecolor=(1,1,1,0), autoscale_on=False) ax_left_panel.margins(x=0,y=0) ax_left_panel.axis('off') ax_right_panel=plot.axes([0.5,0,0.5,1],facecolor=(0.9,0.9,0.9,1), autoscale_on=False) ax_right_panel.margins(x=0,y=0) ax_right_panel.get_xaxis().set_visible(False) ax_right_panel.get_yaxis().set_visible(False) ax=plot.axes([left_margin/2.0,bottom_margin, (1.0-left_margin-right_margin)/2, 1.0-top_margin-bottom_margin]) else: fig=plot.figure(1,figsize=(fig_size_x,fig_size_y)) fig.set_facecolor('white') ax=plot.axes([left_margin,bottom_margin, 1.0-left_margin-right_margin, 1.0-top_margin-bottom_margin]) ax.minorticks_on() # Make the ticks longer than default ax.tick_params('both',length=12,width=1,which='major') ax.tick_params('both',length=5,width=1,which='minor') ax.tick_params(labelsize=fontsize*0.8) plot.grid(False) if editor: return (fig,ax,ax_left_panel,ax_right_panel) return (fig,ax) def get_str_array(dset): """ Extract a string array from O\ :sub:`2`\ scl HDF5 dataset ``dset`` as a python list This function is in ``utils.py``. """ nw=dset['nw'][0] nc=dset['nc'][0] data=dset['data'] counter=dset['counter'] char_counter=1 word_counter=0 list=[] col='' for ix in range(0,nc): # Skip empty strings in the array done=0 while done==0: if word_counter==nw: done=1 elif counter[word_counter]==0: word_counter=word_counter+1 list.append('') else: done=1 col=col+str(chr(data[ix])) if char_counter==counter[word_counter]: list.append(col) col='' word_counter=word_counter+1 char_counter=1 else: char_counter=char_counter+1 # We're done with the characters, but there are some blank # strings left. Add the appropriate blanks at the end. while word_counter<nw: list.append('') word_counter=word_counter+1 return list def get_ic_ptrs_to_list(size,lengths,chars): """ """ tlist=[] count=0 for i in range(0,size.value): strt=b'' for j in range(0,lengths[i]): strt=strt+chars[count] count+=1 tlist.append(strt) return tlist def parse_arguments(argv,verbose=0): """ Old command-line parser (this is currently unused and it's not clear if it will be useful in the future). This function is in ``utils.py``. """ list=[] unproc_list=[] if verbose>1: print('Number of arguments:', len(argv), 'arguments.') print('Argument List:', str(argv)) ix=1 while ix<len(argv): if verbose>1: print('Processing index',ix,'with value',argv[ix],'.') # Find first option, at index ix initial_ix_done=0 while initial_ix_done==0: if ix==len(argv): initial_ix_done=1 elif argv[ix][0]=='-': initial_ix_done=1 else: if verbose>1: print('Adding',argv[ix],' to unprocessed list.') unproc_list.append(argv[ix]) ix=ix+1 # If there is an option, then ix is its index if ix<len(argv): list_one=[] # Strip single and double dashes cmd_name=argv[ix][1:] if cmd_name[0]=='-': cmd_name=cmd_name[1:] # Add command name to list list_one.append(cmd_name) if verbose>1: print('Found option',cmd_name,'at index',ix) # Set ix_next to the next option, or to the end if # there is no next option ix_next=ix+1 ix_next_done=0 while ix_next_done==0: if ix_next==len(argv): ix_next_done=1 elif argv[ix_next][0]=='-': ix_next_done=1 else: if verbose>1: print('Adding '+argv[ix_next]+' with index '+ str(ix_next)+' to list for '+cmd_name) list_one.append(argv[ix_next]) ix_next=ix_next+1 list.append(list_one) ix=ix_next return (list,unproc_list) def string_to_dict(s): """ Convert a string to a dictionary, with extra processing for colors, subdictionaries, and matplotlib keyword arguments which are expected to have integer or floating point values. This function is in ``utils.py``. """ # First split into keyword = value pairs arr=s.split(',') # Create empty dictionary dct={} # If we need to skip arguments skip=0 if len(s)==0: return dct for i in range(0,len(arr)): if skip>0: skip=skip-1 else: # For each pair, split keyword and value. arr2=arr[i].split('=') # Remove preceeding and trailing whitespace from the # keywords (not for the values) while arr2[0][0].isspace(): arr2[0]=arr2[0][1:] while arr2[0][len(arr2[0])-1].isspace(): arr2[0]=arr2[0][:-1] # Remove quotes if necessary if len(arr2)>1 and len(arr2[1])>2: if arr2[1][0]=='\'' and arr2[1][len(arr2[1])-1]=='\'': arr2[1]=arr2[1][1:len(arr2[1])-1] if arr2[1][0]=='"' and arr2[1][len(arr2[1])-1]=='"': arr2[1]=arr2[1][1:len(arr2[1])-1] # If one of the entries is arrowstyle, then combine # it with the head_width, head_length, and tail_width # options if they are present if arr2[0]=='arrowstyle': for j in range(0,len(arr)): if arr[j].split('=')[0]=='head_width': arr2[1]=arr2[1]+',head_width='+arr[j].split('=')[1] if arr[j].split('=')[0]=='head_length': arr2[1]=arr2[1]+',head_length='+arr[j].split('=')[1] if arr[j].split('=')[0]=='tail_width': arr2[1]=arr2[1]+',tail_width='+arr[j].split('=')[1] if arr[j].split('=')[0]=='shrink_factor': arr2[1]=arr2[1]+',shrink_factor='+arr[j].split('=')[1] if arr[j].split('=')[0]=='widthA': arr2[1]=arr2[1]+',widthA='+arr[j].split('=')[1] if arr[j].split('=')[0]=='widthB': arr2[1]=arr2[1]+',widthB='+arr[j].split('=')[1] if arr[j].split('=')[0]=='lengthB': arr2[1]=arr2[1]+',lengthB='+arr[j].split('=')[1] if arr[j].split('=')[0]=='as_angleB': arr2[1]=arr2[1]+',angleB='+arr[j].split('=')[1] print('Found arrowstyle option, reprocessed:',arr2[1]) # If one of the entries is connection style, then process # accordingly if arr2[0]=='connectionstyle': for j in range(0,len(arr)): if arr[j].split('=')[0]=='angleA': arr2[1]=arr2[1]+',angleA='+arr[j].split('=')[1] if arr[j].split('=')[0]=='cs_angleB': arr2[1]=arr2[1]+',angleB='+arr[j].split('=')[1] if arr[j].split('=')[0]=='armA': arr2[1]=arr2[1]+',armA='+arr[j].split('=')[1] if arr[j].split('=')[0]=='armB': arr2[1]=arr2[1]+',armB='+arr[j].split('=')[1] if arr[j].split('=')[0]=='rad': arr2[1]=arr2[1]+',rad='+arr[j].split('=')[1] if arr[j].split('=')[0]=='fraction': arr2[1]=arr2[1]+',fraction='+arr[j].split('=')[1] if arr[j].split('=')[0]=='angle': arr2[1]=arr2[1]+',angle='+arr[j].split('=')[1] print('Found connectionstyle option, reprocessed:',arr2[1]) # convert strings to numbers if necessary if arr2[0]=='zorder': arr2[1]=float(arr2[1]) if arr2[0]=='lw': arr2[1]=float(arr2[1]) if arr2[0]=='linewidth': arr2[1]=float(arr2[1]) if arr2[0]=='elinewidth': arr2[1]=float(arr2[1]) if arr2[0]=='alpha': arr2[1]=float(arr2[1]) if arr2[0]=='shrinkA': arr2[1]=int(arr2[1]) if arr2[0]=='shrinkB': arr2[1]=int(arr2[1]) if arr2[0]=='bins': arr2[1]=int(arr2[1]) if arr2[0]=='fig_size_x': arr2[1]=float(arr2[1]) if arr2[0]=='fig_size_y': arr2[1]=float(arr2[1]) if arr2[0]=='left_margin': arr2[1]=float(arr2[1]) if arr2[0]=='right_margin': arr2[1]=float(arr2[1]) if arr2[0]=='top_margin': arr2[1]=float(arr2[1]) if arr2[0]=='bottom_margin': arr2[1]=float(arr2[1]) if arr2[0]=='left': arr2[1]=float(arr2[1]) if arr2[0]=='right': arr2[1]=float(arr2[1]) if arr2[0]=='top': arr2[1]=float(arr2[1]) if arr2[0]=='bottom': arr2[1]=float(arr2[1]) if arr2[0]=='wspace': arr2[1]=float(arr2[1]) if arr2[0]=='hspace': arr2[1]=float(arr2[1]) if arr2[0]=='fontsize': arr2[1]=float(arr2[1]) if arr2[0]=='font': arr2[1]=float(arr2[1]) if arr2[0]=='scale': arr2[1]=float(arr2[1]) if arr2[0]=='dpi': arr2[1]=float(arr2[1]) if arr2[0]=='pad': arr2[1]=float(arr2[1]) if arr2[0]=='capsize': arr2[1]=float(arr2[1]) if arr2[0]=='capthick': arr2[1]=float(arr2[1]) # Convert strings to bool values if arr2[0]=='sharex': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='lolims': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='uplims': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='xlolims': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='xuplims': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='reorient': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='sharey': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='squeeze': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='fill': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='ticks_in': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='rt_ticks': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False if arr2[0]=='pcm': if arr2[1]=='True': arr2[1]=True else: arr2[1]=False # Process color entries. The challenge here is that # dictionary entries are separated by commas, but there # are also commas inside color specifications. If color # contains a left parenthesis or a left bracket, then we # have to convert the string to an array. However, this # algorithm has a limitation: it can only handle (rgb) or # [rgba], but not [rgb] or (rgba). if (arr2[0]=='color' and arr[i][5]=='=' and arr[i][6]=='('): arr2[1]=arr2[1]+','+arr[i+1]+','+arr[i+2] skip=2 arr2[1]=arr2[1][1:len(arr2[1])-1] arr3=arr2[1].split(',') arr2[1]=(float(arr3[0]),float(arr3[1]),float(arr3[2])) print('Found color:',arr2[1]) elif (arr2[0]=='color' and arr[i][5]=='=' and arr[i][6]=='['): arr2[1]=arr2[1]+','+arr[i+1]+','+arr[i+2]+','+arr[i+3] skip=3 arr2[1]=arr2[1][1:len(arr2[1])-1] arr3=arr2[1].split(',') arr2[1]=[float(arr3[0]),float(arr3[1]),float(arr3[2]), float(arr3[3])] print('Found color:',arr2[1]) elif (arr2[0]=='textcolor' and arr[i][9]=='=' and arr[i][10]=='('): arr2[1]=arr2[1]+','+arr[i+1]+','+arr[i+2] skip=2 arr2[1]=arr2[1][1:len(arr2[1])-1] arr3=arr2[1].split(',') arr2[1]=(float(arr3[0]),float(arr3[1]),float(arr3[2])) print('Found color:',arr2[1]) elif (arr2[0]=='textcolor' and arr[i][9]=='=' and arr[i][10]=='['): arr2[1]=arr2[1]+','+arr[i+1]+','+arr[i+2]+','+arr[i+3] skip=3 arr2[1]=arr2[1][1:len(arr2[1])-1] arr3=arr2[1].split(',') arr2[1]=[float(arr3[0]),float(arr3[1]),float(arr3[2]), float(arr3[3])] print('Found color:',arr2[1]) if ((arr2[0]=='ls' or arr2[0]=='linestyle') and len(arr2)>=2 and len(arr2[1])>1 and arr2[1][0]=='('): lstemp=arr[i] skip=0 while (lstemp[-1]!=')' and lstemp[-2]!=')' and i+1<len(arr)): lstemp=lstemp+','+arr[i+1] skip=skip+1 i=i+1 if lstemp[-2]!=')' or lstemp[-1]!=')': print('Failed to parse line style from',s) quit() arr2[1]=eval(lstemp[3:]) # if (arr2[0]=='color' and (arr2[1].find('(')!=-1 or # arr2[1].find('[')!=-1)): # print('here',arr2[0],arr2[1]) # if arr2[1].find('(')==-1: # loc1=arr2[1].find('[') # loc2=arr2[1].find(']') # else: # loc1=arr2[1].find('(') # loc2=arr2[1].find(')') # print('here2',loc1,loc2) # arr2[1]=arr2[1][loc1:loc2-loc1+1] # print('here3',arr2[1]) # temp=arr2[1].split(',') # if len(temp)==3: # arr2[1]=[float(temp[0]),float(temp[1]), # float(temp[2])] # else: # arr2[1]=[float(temp[0]),float(temp[1]), # float(temp[2]),float(temp[3])] # print('here4',arr2[1]) # assign to dictionary (except for arrowstyle and # connectionstyle options which are handled separately # above) if (arr2[0]!='head_width' and arr2[0]!='head_length' and arr2[0]!='tail_width' and arr2[0]!='rad' and arr2[0]!='angleA' and arr2[0]!='as_angleB' and arr2[0]!='armA' and arr2[0]!='armB' and arr2[0]!='angle' and arr2[0]!='fraction' and arr2[0]!='shrink_factor' and arr2[0]!='widthA' and arr2[0]!='lengthB' and arr2[0]!='widthB' and arr2[0]!='cs_angleB'): if len(arr2)<2: print('Original string:',s) print('Current entry:',arr2) print('Current dictionary:',dct) raise Exception('Failed to parse string "'+s+ '" as dictionary.') dct[arr2[0]]=arr2[1] return dct class terminal_py: """ Handle vt100 formatting sequences """ redirected=False """ If true, then the output is being redirected to a file, so don't use the formatting sequences """ def __init__(self): """ Determine if the output is being redirected or not """ if sys.stdout.isatty()==False: self.redirected=True return def cyan_fg(self): """ Set the foreground color to cyan """ strt='' if self.redirected: return strt strt=strt+chr(27)+'[36m' return strt def red_fg(self): """ Set the foreground color to red """ strt='' if self.redirected: return strt strt=strt+chr(27)+'[31m' return strt def magenta_fg(self): """ Set the foreground color to magenta """ strt='' if self.redirected: return strt strt=strt+chr(27)+'[35m' return strt def green_fg(self): """ Set the foreground color to green """ strt='' if self.redirected: return strt strt=strt+chr(27)+'[32m' return strt def bold(self): """ Set the face to bold """ strt='' if self.redirected: return strt strt=strt+chr(27)+'[1m' return strt def default_fg(self): """ Set the foreground color to the default """ strt='' if self.redirected: return strt strt=strt+chr(27)+'[m' return strt def horiz_line(self): """ Return a string which represents a horizontal line. If possible, vt100-like terminal sequences are used to create a line. Otherwise, dashes are used. """ str_line='' if self.redirected: for jj in range(0,78): str_line+='-' else: str_line=str_line+chr(27)+'(0' for jj in range(0,78): str_line+='q' str_line=str_line+chr(27)+'(B' return str_line def type_str(self,strt): return self.magenta_fg()+self.bold()+strt+self.default_fg() def cmd_str(self,strt): return self.cyan_fg()+self.bold()+strt+self.default_fg() def topic_str(self,strt): return self.green_fg()+self.bold()+strt+self.default_fg() def var_str(self,strt): return self.red_fg()+self.bold()+strt+self.default_fg() def length_without_colors(strt): """ Compute the length of strt, ignoring characters which correspond to VT100 formatting sequences """ count=0 index=0 while index<len(strt): if strt[index]!=chr(27): count=count+1 elif index+2<len(strt) and strt[index+1]=='[' and strt[index+2]=='m': index=index+2 elif index+3<len(strt) and strt[index+1]=='[' and strt[index+3]=='m': index=index+3 elif index+4<len(strt) and strt[index+1]=='[' and strt[index+4]=='m': index=index+4 elif index+2<len(strt) and strt[index+1]=='(' and strt[index+2]=='0': index=index+2 elif index+2<len(strt) and strt[index+1]=='(' and strt[index+2]=='B': index=index+2 index=index+1 return count def wrap_line(line,ncols=79): """ From a string 'line', create a list of strings which adds return characters in order to attempt to ensure each line is less than or equal to ncols characters long. This function also respects explicit carriage returns, ensuring they force a new line independent of the line length. This function uses the 'length_without_colors()' function above, to ensure VT100 formatting sequences aren't included in the count. """ list=[] # First, just split by carriage returns post_list=line.split('\n') for i in range(0,len(post_list)): # If this line is already short enough, then just handle # it directly below if length_without_colors(post_list[i])>ncols: # A temporary string which will hold the current line strt='' # Now split by spaces post_word=post_list[i].split(' ') # Proceed word by word for j in range(0,len(post_word)): # If the current word is longer than ncols, then # clear the temporary string and add it to the list if length_without_colors(post_word[j])>ncols: if length_without_colors(strt)>0: list.append(strt) list.append(post_word[j]) strt='' elif (length_without_colors(strt)+ length_without_colors(post_word[j])+1)>ncols: # Otherwise if the next word will take us over the # limit list.append(strt) strt=post_word[j] elif len(strt)==0: strt=post_word[j] else: strt=strt+' '+post_word[j] # If after the last word we still have anything in the # temporary string, then add it to the list if length_without_colors(strt)>0: list.append(strt) else: # Now if the line was already short enough, add it # to the list list.append(post_list[i]) return list def string_equal_dash(str1,str2): b1=force_bytes(str1) b2=force_bytes(str2) for i in range(0,len(b1)): if b1[i]==b'-': b1[i]=b'-' for i in range(0,len(b2)): if b2[i]==b'-': b2[i]=b'-' if b1==b2: return True return False def screenify_py(tlist,ncols=79): maxlen=0 for i in range(0,len(tlist)): if length_without_colors(tlist[i])>maxlen: maxlen=length_without_colors(tlist[i]) # Add to ensure there is at least one space between columns maxlen=maxlen+1 ncolumns=int(ncols/maxlen) nrows=int(len(tlist)/ncolumns) while nrows*ncolumns<len(tlist): nrows=nrows+1 output_list=[] for i in range(0,nrows): row='' for j in range(0,ncolumns): if i+j*nrows<len(tlist): colt=tlist[i+j*nrows] while length_without_colors(colt)<maxlen: colt=colt+' ' row=row+colt output_list.append(row) return output_list
o2sclpy/utils.py
codereval_python_data_163
Create a time from ticks (nanoseconds since midnight). :param ticks: nanoseconds since midnight :type ticks: int :param tz: optional timezone :type tz: datetime.tzinfo :rtype: Time :raises ValueError: if ticks is out of bounds (0 <= ticks < 86400000000000) @classmethod def from_ticks(cls, ticks, tz=None): """Create a time from ticks (nanoseconds since midnight). :param ticks: nanoseconds since midnight :type ticks: int :param tz: optional timezone :type tz: datetime.tzinfo :rtype: Time :raises ValueError: if ticks is out of bounds (0 <= ticks < 86400000000000) """ if not isinstance(ticks, int): raise TypeError("Ticks must be int") if 0 <= ticks < 86400000000000: second, nanosecond = divmod(ticks, NANO_SECONDS) minute, second = divmod(second, 60) hour, minute = divmod(minute, 60) return cls.__new(ticks, hour, minute, second, nanosecond, tz) raise ValueError("Ticks out of range (0..86400000000000)") # Copyright (c) "Neo4j" # Neo4j Sweden AB [https://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module contains the fundamental types used for temporal accounting as well as a number of utility functions. """ from datetime import ( date, datetime, time, timedelta, timezone, ) from functools import total_ordering from re import compile as re_compile from time import ( gmtime, mktime, struct_time, ) from ._arithmetic import ( nano_add, nano_div, round_half_to_even, symmetric_divmod, ) from ._metaclasses import ( DateTimeType, DateType, TimeType, ) __all__ = [ "MIN_INT64", "MAX_INT64", "MIN_YEAR", "MAX_YEAR", "Duration", "Date", "ZeroDate", "Time", "Midnight", "Midday", "DateTime", "Never", "UnixEpoch", ] MIN_INT64 = -(2 ** 63) MAX_INT64 = (2 ** 63) - 1 #: The smallest year number allowed in a :class:`.Date` or :class:`.DateTime` #: object to be compatible with :class:`datetime.date` and #: :class:`datetime.datetime`. MIN_YEAR = 1 #: The largest year number allowed in a :class:`.Date` or :class:`.DateTime` #: object to be compatible with :class:`datetime.date` and #: :class:`datetime.datetime`. MAX_YEAR = 9999 DATE_ISO_PATTERN = re_compile(r"^(\d{4})-(\d{2})-(\d{2})$") TIME_ISO_PATTERN = re_compile( r"^(\d{2})(:(\d{2})(:((\d{2})" r"(\.\d*)?))?)?(([+-])(\d{2}):(\d{2})(:((\d{2})(\.\d*)?))?)?$" ) DURATION_ISO_PATTERN = re_compile( r"^P((\d+)Y)?((\d+)M)?((\d+)D)?" r"(T((\d+)H)?((\d+)M)?(((\d+)(\.\d+)?)?S)?)?$" ) NANO_SECONDS = 1000000000 AVERAGE_SECONDS_IN_MONTH = 2629746 AVERAGE_SECONDS_IN_DAY = 86400 def _is_leap_year(year): if year % 4 != 0: return False if year % 100 != 0: return True return year % 400 == 0 IS_LEAP_YEAR = {year: _is_leap_year(year) for year in range(MIN_YEAR, MAX_YEAR + 1)} def _days_in_year(year): return 366 if IS_LEAP_YEAR[year] else 365 DAYS_IN_YEAR = {year: _days_in_year(year) for year in range(MIN_YEAR, MAX_YEAR + 1)} def _days_in_month(year, month): if month in (9, 4, 6, 11): return 30 elif month != 2: return 31 else: return 29 if IS_LEAP_YEAR[year] else 28 DAYS_IN_MONTH = {(year, month): _days_in_month(year, month) for year in range(MIN_YEAR, MAX_YEAR + 1) for month in range(1, 13)} def _normalize_day(year, month, day): """ Coerce the day of the month to an internal value that may or may not match the "public" value. With the exception of the last three days of every month, all days are stored as-is. The last three days are instead stored as -1 (the last), -2 (the second to last) and -3 (the third to last). Therefore, for a 28-day month, the last week is as follows: Day | 22 23 24 25 26 27 28 Value | 22 23 24 25 -3 -2 -1 For a 29-day month, the last week is as follows: Day | 23 24 25 26 27 28 29 Value | 23 24 25 26 -3 -2 -1 For a 30-day month, the last week is as follows: Day | 24 25 26 27 28 29 30 Value | 24 25 26 27 -3 -2 -1 For a 31-day month, the last week is as follows: Day | 25 26 27 28 29 30 31 Value | 25 26 27 28 -3 -2 -1 This slightly unintuitive system makes some temporal arithmetic produce a more desirable outcome. :param year: :param month: :param day: :return: """ if year < MIN_YEAR or year > MAX_YEAR: raise ValueError("Year out of range (%d..%d)" % (MIN_YEAR, MAX_YEAR)) if month < 1 or month > 12: raise ValueError("Month out of range (1..12)") days_in_month = DAYS_IN_MONTH[(year, month)] if day in (days_in_month, -1): return year, month, -1 if day in (days_in_month - 1, -2): return year, month, -2 if day in (days_in_month - 2, -3): return year, month, -3 if 1 <= day <= days_in_month - 3: return year, month, int(day) # TODO improve this error message raise ValueError("Day %d out of range (1..%d, -1, -2 ,-3)" % (day, days_in_month)) class ClockTime(tuple): """ A count of `seconds` and `nanoseconds`. This class can be used to mark a particular point in time, relative to an externally-specified epoch. The `seconds` and `nanoseconds` values provided to the constructor can can have any sign but will be normalized internally into a positive or negative `seconds` value along with a positive `nanoseconds` value between `0` and `999,999,999`. Therefore ``ClockTime(-1, -1)`` is normalized to ``ClockTime(-2, 999999999)``. Note that the structure of a :class:`.ClockTime` object is similar to the ``timespec`` struct in C. """ def __new__(cls, seconds=0, nanoseconds=0): seconds, nanoseconds = divmod( int(NANO_SECONDS * seconds) + int(nanoseconds), NANO_SECONDS ) return tuple.__new__(cls, (seconds, nanoseconds)) def __add__(self, other): if isinstance(other, (int, float)): other = ClockTime(other) if isinstance(other, ClockTime): return ClockTime(self.seconds + other.seconds, self.nanoseconds + other.nanoseconds) if isinstance(other, Duration): if other.months or other.days: raise ValueError("Cannot add Duration with months or days") return ClockTime(self.seconds + other.seconds, self.nanoseconds + int(other.nanoseconds)) return NotImplemented def __sub__(self, other): if isinstance(other, (int, float)): other = ClockTime(other) if isinstance(other, ClockTime): return ClockTime(self.seconds - other.seconds, self.nanoseconds - other.nanoseconds) if isinstance(other, Duration): if other.months or other.days: raise ValueError("Cannot subtract Duration with months or days") return ClockTime(self.seconds - other.seconds, self.nanoseconds - int(other.nanoseconds)) return NotImplemented def __repr__(self): return "ClockTime(seconds=%r, nanoseconds=%r)" % self @property def seconds(self): return self[0] @property def nanoseconds(self): return self[1] class Clock: """ Accessor for time values. This class is fulfilled by implementations that subclass :class:`.Clock`. These implementations are contained within the ``neo4j.time.clock_implementations`` module, and are not intended to be accessed directly. Creating a new :class:`.Clock` instance will produce the highest precision clock implementation available. >>> clock = Clock() >>> type(clock) # doctest: +SKIP neo4j.time.clock_implementations.LibCClock >>> clock.local_time() # doctest: +SKIP ClockTime(seconds=1525265942, nanoseconds=506844026) """ __implementations = None def __new__(cls): if cls.__implementations is None: # Find an available clock with the best precision import neo4j.time._clock_implementations cls.__implementations = sorted((clock for clock in Clock.__subclasses__() if clock.available()), key=lambda clock: clock.precision(), reverse=True) if not cls.__implementations: raise RuntimeError("No clock implementations available") instance = object.__new__(cls.__implementations[0]) return instance @classmethod def precision(cls): """ The precision of this clock implementation, represented as a number of decimal places. Therefore, for a nanosecond precision clock, this function returns `9`. """ raise NotImplementedError("No clock implementation selected") @classmethod def available(cls): """ A boolean flag to indicate whether or not this clock implementation is available on this platform. """ raise NotImplementedError("No clock implementation selected") @classmethod def local_offset(cls): """The offset from UTC for local time read from this clock. This may raise OverflowError if not supported, because of platform depending C libraries. :returns: :rtype: :raises OverflowError: """ # Adding and subtracting two days to avoid passing a pre-epoch time to # `mktime`, which can cause a `OverflowError` on some platforms (e.g., # Windows). return ClockTime(-int(mktime(gmtime(172800))) + 172800) def local_time(self): """ Read and return the current local time from this clock, measured relative to the Unix Epoch. This may raise OverflowError if not supported, because of platform depending C libraries. :returns: :rtype: :raises OverflowError: """ return self.utc_time() + self.local_offset() def utc_time(self): """ Read and return the current UTC time from this clock, measured relative to the Unix Epoch. """ raise NotImplementedError("No clock implementation selected") class Duration(tuple): """A difference between two points in time. A :class:`.Duration` represents the difference between two points in time. Duration objects store a composite value of `months`, `days`, `seconds`, and `nanoseconds`. Unlike :class:`datetime.timedelta` however, days, and seconds/nanoseconds are never interchanged. All values except seconds and nanoseconds are applied separately in calculations (element-wise). A :class:`.Duration` stores four primary instance attributes internally: `months`, `days`, `seconds` and `nanoseconds`. These are maintained as individual values and are immutable. Each of these four attributes can carry its own sign, with the exception of `nanoseconds`, which always has the same sign as `seconds`. The constructor will establish this state, should the duration be initialized with conflicting `seconds` and `nanoseconds` signs. This structure allows the modelling of durations such as `3 months minus 2 days`. To determine if a :class:`Duration` `d` is overflowing the accepted values of the database, first, all `nanoseconds` outside the range -999_999_999 and 999_999_999 are transferred into the seconds field. Then, `months`, `days`, and `seconds` are summed up like so: `months * 2629746 + days * 86400 + d.seconds + d.nanoseconds // 1000000000`. (Like the integer division in Python, this one is to be understood as rounding down rather than towards 0.) This value must be between -(2\\ :sup:`63`) and (2\\ :sup:`63` - 1) inclusive. :param years: will be added times 12 to `months` :type years: float :param months: will be truncated to :class:`int` (`int(months)`) :type months: float :param weeks: will be added times 7 to `days` :type weeks: float :param days: will be truncated to :class:`int` (`int(days)`) :type days: float :param hours: will be added times 3,600,000,000,000 to `nanoseconds` :type hours: float :param minutes: will be added times 60,000,000,000 to `nanoseconds` :type minutes: float :param seconds: will be added times 1,000,000,000 to `nanoseconds`` :type seconds: float :param milliseconds: will be added times 1,000,000 to `nanoseconds` :type microseconds: float :param microseconds: will be added times 1,000 to `nanoseconds` :type milliseconds: float :param nanoseconds: will be truncated to :class:`int` (`int(nanoseconds)`) :type nanoseconds: float :raises ValueError: the components exceed the limits as described above. """ # i64: i64:i64: i32 min = None """The lowest duration value possible.""" max = None """The highest duration value possible.""" def __new__(cls, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0, nanoseconds=0): mo = int(12 * years + months) if mo < MIN_INT64 or mo > MAX_INT64: raise ValueError("Months value out of range") d = int(7 * weeks + days) ns = (int(3600000000000 * hours) + int(60000000000 * minutes) + int(1000000000 * seconds) + int(1000000 * milliseconds) + int(1000 * microseconds) + int(nanoseconds)) s, ns = symmetric_divmod(ns, NANO_SECONDS) avg_total_seconds = (mo * AVERAGE_SECONDS_IN_MONTH + d * AVERAGE_SECONDS_IN_DAY + s - (1 if ns < 0 else 0)) if avg_total_seconds < MIN_INT64 or avg_total_seconds > MAX_INT64: raise ValueError("Duration value out of range: %r", cls.__repr__((mo, d, s, ns))) return tuple.__new__(cls, (mo, d, s, ns)) def __bool__(self): """Falsy if all primary instance attributes are.""" return any(map(bool, self)) __nonzero__ = __bool__ def __add__(self, other): """Add a :class:`.Duration` or :class:`datetime.timedelta`. :rtype: Duration """ if isinstance(other, Duration): return Duration( months=self[0] + int(other.months), days=self[1] + int(other.days), seconds=self[2] + int(other.seconds), nanoseconds=self[3] + int(other.nanoseconds) ) if isinstance(other, timedelta): return Duration( months=self[0], days=self[1] + other.days, seconds=self[2] + other.seconds, nanoseconds=self[3] + other.microseconds * 1000 ) return NotImplemented def __sub__(self, other): """Subtract a :class:`.Duration` or :class:`datetime.timedelta`. :rtype: Duration """ if isinstance(other, Duration): return Duration( months=self[0] - int(other.months), days=self[1] - int(other.days), seconds=self[2] - int(other.seconds), nanoseconds=self[3] - int(other.nanoseconds) ) if isinstance(other, timedelta): return Duration( months=self[0], days=self[1] - other.days, seconds=self[2] - other.seconds, nanoseconds=self[3] - other.microseconds * 1000 ) return NotImplemented def __mul__(self, other): """Multiply by an :class:`int` or :class:`float`. The operation is performed element-wise on ``(months, days, nanaoseconds)`` where * years go into months, * weeks go into days, * seconds and all sub-second units go into nanoseconds. Each element will be rounded to the nearest integer (.5 towards even). :rtype: Duration """ if isinstance(other, (int, float)): return Duration( months=round_half_to_even(self[0] * other), days=round_half_to_even(self[1] * other), nanoseconds=round_half_to_even( self[2] * NANO_SECONDS * other + self[3] * other ) ) return NotImplemented def __floordiv__(self, other): """Integer division by an :class:`int`. The operation is performed element-wise on ``(months, days, nanaoseconds)`` where * years go into months, * weeks go into days, * seconds and all sub-second units go into nanoseconds. Each element will be rounded towards -inf. :rtype: Duration """ if isinstance(other, int): return Duration( months=self[0] // other, days=self[1] // other, nanoseconds=(self[2] * NANO_SECONDS + self[3]) // other ) return NotImplemented def __mod__(self, other): """Modulo operation by an :class:`int`. The operation is performed element-wise on ``(months, days, nanaoseconds)`` where * years go into months, * weeks go into days, * seconds and all sub-second units go into nanoseconds. :rtype: Duration """ if isinstance(other, int): return Duration( months=self[0] % other, days=self[1] % other, nanoseconds=(self[2] * NANO_SECONDS + self[3]) % other ) return NotImplemented def __divmod__(self, other): """Division and modulo operation by an :class:`int`. See :meth:`__floordiv__` and :meth:`__mod__`. :rtype: (Duration, Duration) """ if isinstance(other, int): return self.__floordiv__(other), self.__mod__(other) return NotImplemented def __truediv__(self, other): """Division by an :class:`int` or :class:`float`. The operation is performed element-wise on ``(months, days, nanaoseconds)`` where * years go into months, * weeks go into days, * seconds and all sub-second units go into nanoseconds. Each element will be rounded to the nearest integer (.5 towards even). :rtype: Duration """ if isinstance(other, (int, float)): return Duration( months=round_half_to_even(self[0] / other), days=round_half_to_even(self[1] / other), nanoseconds=round_half_to_even( self[2] * NANO_SECONDS / other + self[3] / other ) ) return NotImplemented def __pos__(self): """""" return self def __neg__(self): """""" return Duration(months=-self[0], days=-self[1], seconds=-self[2], nanoseconds=-self[3]) def __abs__(self): """""" return Duration(months=abs(self[0]), days=abs(self[1]), seconds=abs(self[2]), nanoseconds=abs(self[3])) def __repr__(self): """""" return "Duration(months=%r, days=%r, seconds=%r, nanoseconds=%r)" % self def __str__(self): """""" return self.iso_format() def __copy__(self): return self.__new__(self.__class__, months=self[0], days=self[1], seconds=self[2], nanoseconds=self[3]) def __deepcopy__(self, memodict={}): return self.__copy__() @classmethod def from_iso_format(cls, s): """Parse a ISO formatted duration string. Accepted formats (all lowercase letters are placeholders): 'P', a zero length duration 'PyY', y being a number of years 'PmM', m being a number of months 'PdD', d being a number of days Any combination of the above, e.g., 'P25Y1D' for 25 years and 1 day. 'PThH', h being a number of hours 'PTmM', h being a number of minutes 'PTsS', h being a number of seconds 'PTs.sss...S', h being a fractional number of seconds Any combination of the above, e.g. 'PT5H1.2S' for 5 hours and 1.2 seconds. Any combination of all options, e.g. 'P13MT100M' for 13 months and 100 minutes. :param s: String to parse :type s: str :rtype: Duration :raises ValueError: if the string does not match the required format. """ match = DURATION_ISO_PATTERN.match(s) if match: ns = 0 if match.group(15): ns = int(match.group(15)[1:10].ljust(9, "0")) return cls( years=int(match.group(2) or 0), months=int(match.group(4) or 0), days=int(match.group(6) or 0), hours=int(match.group(9) or 0), minutes=int(match.group(11) or 0), seconds=int(match.group(14) or 0), nanoseconds=ns ) raise ValueError("Duration string must be in ISO format") fromisoformat = from_iso_format def iso_format(self, sep="T"): """Return the :class:`Duration` as ISO formatted string. :param sep: the separator before the time components. :type sep: str :rtype: str """ parts = [] hours, minutes, seconds, nanoseconds = \ self.hours_minutes_seconds_nanoseconds if hours: parts.append("%dH" % hours) if minutes: parts.append("%dM" % minutes) if nanoseconds: if seconds >= 0 and nanoseconds >= 0: parts.append("%d.%sS" % (seconds, str(nanoseconds).rjust(9, "0").rstrip("0"))) elif seconds <= 0 and nanoseconds <= 0: parts.append("-%d.%sS" % (abs(seconds), str(abs(nanoseconds)).rjust(9, "0").rstrip("0"))) else: assert False and "Please report this issue" elif seconds: parts.append("%dS" % seconds) if parts: parts.insert(0, sep) years, months, days = self.years_months_days if days: parts.insert(0, "%dD" % days) if months: parts.insert(0, "%dM" % months) if years: parts.insert(0, "%dY" % years) if parts: parts.insert(0, "P") return "".join(parts) else: return "PT0S" @property def months(self): """The months of the :class:`Duration`. :type: int """ return self[0] @property def days(self): """The days of the :class:`Duration`. :type: int """ return self[1] @property def seconds(self): """The seconds of the :class:`Duration`. :type: int """ return self[2] @property def nanoseconds(self): """The nanoseconds of the :class:`Duration`. :type: int """ return self[3] @property def years_months_days(self): """ :return: """ years, months = symmetric_divmod(self[0], 12) return years, months, self[1] @property def hours_minutes_seconds_nanoseconds(self): """ A 4-tuple of (hours, minutes, seconds, nanoseconds). :type: (int, int, int, int) """ minutes, seconds = symmetric_divmod(self[2], 60) hours, minutes = symmetric_divmod(minutes, 60) return hours, minutes, seconds, self[3] Duration.min = Duration(seconds=MIN_INT64, nanoseconds=0) Duration.max = Duration(seconds=MAX_INT64, nanoseconds=999999999) class Date(metaclass=DateType): """Idealized date representation. A :class:`.Date` object represents a date (year, month, and day) in the `proleptic Gregorian Calendar <https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar>`_. Years between `0001` and `9999` are supported, with additional support for the "zero date" used in some contexts. Each date is based on a proleptic Gregorian ordinal, which models 1 Jan 0001 as `day 1` and counts each subsequent day up to, and including, 31 Dec 9999. The standard `year`, `month` and `day` value of each date is also available. Internally, the day of the month is always stored as-is, with the exception of the last three days of that month. These are always stored as -1, -2 and -3 (counting from the last day). This system allows some temporal arithmetic (particularly adding or subtracting months) to produce a more desirable outcome than would otherwise be produced. Externally, the day number is always the same as would be written on a calendar. :param year: the year. Minimum :attr:`.MIN_YEAR` (0001), maximum :attr:`.MAX_YEAR` (9999). :type year: int :param month: the month. Minimum 1, maximum 12. :type month: int :param day: the day. Minimum 1, maximum :attr:`Date.days_in_month(year, month) <Date.days_in_month>`. :type day: int A zero date can also be acquired by passing all zeroes to the :class:`neo4j.time.Date` constructor or by using the :attr:`ZeroDate` constant. """ # CONSTRUCTOR # def __new__(cls, year, month, day): if year == month == day == 0: return ZeroDate year, month, day = _normalize_day(year, month, day) ordinal = cls.__calc_ordinal(year, month, day) return cls.__new(ordinal, year, month, day) @classmethod def __new(cls, ordinal, year, month, day): instance = object.__new__(cls) instance.__ordinal = int(ordinal) instance.__year = int(year) instance.__month = int(month) instance.__day = int(day) return instance def __getattr__(self, name): """ Map standard library attribute names to local attribute names, for compatibility. """ try: return { "isocalendar": self.iso_calendar, "isoformat": self.iso_format, "isoweekday": self.iso_weekday, "strftime": self.__format__, "toordinal": self.to_ordinal, "timetuple": self.time_tuple, }[name] except KeyError: raise AttributeError("Date has no attribute %r" % name) # CLASS METHODS # @classmethod def today(cls, tz=None): """Get the current date. :param tz: timezone or None to get the local :class:`.Date`. :type tz: datetime.tzinfo or None :rtype: Date :raises OverflowError: if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038. """ if tz is None: return cls.from_clock_time(Clock().local_time(), UnixEpoch) else: return ( DateTime.utc_now() .replace(tzinfo=timezone.utc).astimezone(tz) .date() ) @classmethod def utc_today(cls): """Get the current date as UTC local date. :rtype: Date """ return cls.from_clock_time(Clock().utc_time(), UnixEpoch) @classmethod def from_timestamp(cls, timestamp, tz=None): """:class:`.Date` from a time stamp (seconds since unix epoch). :param timestamp: the unix timestamp (seconds since unix epoch). :type timestamp: float :param tz: timezone. Set to None to create a local :class:`.Date`. :type tz: datetime.tzinfo or None :rtype: Date :raises OverflowError: if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038. """ return cls.from_native(datetime.fromtimestamp(timestamp, tz)) @classmethod def utc_from_timestamp(cls, timestamp): """:class:`.Date` from a time stamp (seconds since unix epoch). Returns the `Date` as local date `Date` in UTC. :rtype: Date """ return cls.from_clock_time((timestamp, 0), UnixEpoch) @classmethod def from_ordinal(cls, ordinal): """ The :class:`.Date` that corresponds to the proleptic Gregorian ordinal. `0001-01-01` has ordinal 1 and `9999-12-31` has ordinal 3,652,059. Values outside of this range trigger a :exc:`ValueError`. The corresponding instance method for the reverse date-to-ordinal transformation is :meth:`.to_ordinal`. The ordinal 0 has a special semantic and will return :attr:`ZeroDate`. :rtype: Date :raises ValueError: if the ordinal is outside the range [0, 3652059] (both values included). """ if ordinal == 0: return ZeroDate if ordinal >= 736695: year = 2018 # Project release year month = 1 day = int(ordinal - 736694) elif ordinal >= 719163: year = 1970 # Unix epoch month = 1 day = int(ordinal - 719162) else: year = 1 month = 1 day = int(ordinal) if day < 1 or day > 3652059: # Note: this requires a maximum of 22 bits for storage # Could be transferred in 3 bytes. raise ValueError("Ordinal out of range (1..3652059)") if year < MIN_YEAR or year > MAX_YEAR: raise ValueError("Year out of range (%d..%d)" % (MIN_YEAR, MAX_YEAR)) days_in_year = DAYS_IN_YEAR[year] while day > days_in_year: day -= days_in_year year += 1 days_in_year = DAYS_IN_YEAR[year] days_in_month = DAYS_IN_MONTH[(year, month)] while day > days_in_month: day -= days_in_month month += 1 days_in_month = DAYS_IN_MONTH[(year, month)] year, month, day = _normalize_day(year, month, day) return cls.__new(ordinal, year, month, day) @classmethod def parse(cls, s): """Parse a string to produce a :class:`.Date`. Accepted formats: 'Y-M-D' :param s: the string to be parsed. :type s: str :rtype: Date :raises ValueError: if the string could not be parsed. """ try: numbers = map(int, s.split("-")) except (ValueError, AttributeError): raise ValueError("Date string must be in format YYYY-MM-DD") else: numbers = list(numbers) if len(numbers) == 3: return cls(*numbers) raise ValueError("Date string must be in format YYYY-MM-DD") @classmethod def from_iso_format(cls, s): """Parse a ISO formatted Date string. Accepted formats: 'YYYY-MM-DD' :param s: the string to be parsed. :type s: str :rtype: Date :raises ValueError: if the string could not be parsed. """ m = DATE_ISO_PATTERN.match(s) if m: year = int(m.group(1)) month = int(m.group(2)) day = int(m.group(3)) return cls(year, month, day) raise ValueError("Date string must be in format YYYY-MM-DD") @classmethod def from_native(cls, d): """Convert from a native Python `datetime.date` value. :param d: the date to convert. :type d: datetime.date :rtype: Date """ return Date.from_ordinal(d.toordinal()) @classmethod def from_clock_time(cls, clock_time, epoch): """Convert from a ClockTime relative to a given epoch. :param clock_time: the clock time as :class:`.ClockTime` or as tuple of (seconds, nanoseconds) :type clock_time: ClockTime or (float, int) :param epoch: the epoch to which `clock_time` is relative :type epoch: DateTime :rtype: Date """ try: clock_time = ClockTime(*clock_time) except (TypeError, ValueError): raise ValueError("Clock time must be a 2-tuple of (s, ns)") else: ordinal = clock_time.seconds // 86400 return Date.from_ordinal(ordinal + epoch.date().to_ordinal()) @classmethod def is_leap_year(cls, year): """Indicates whether or not `year` is a leap year. :param year: the year to look up :type year: int :rtype: bool :raises ValueError: if `year` is out of range: :attr:`MIN_YEAR` <= year <= :attr:`MAX_YEAR` """ if year < MIN_YEAR or year > MAX_YEAR: raise ValueError("Year out of range (%d..%d)" % (MIN_YEAR, MAX_YEAR)) return IS_LEAP_YEAR[year] @classmethod def days_in_year(cls, year): """Return the number of days in `year`. :param year: the year to look up :type year: int :rtype: int :raises ValueError: if `year` is out of range: :attr:`MIN_YEAR` <= year <= :attr:`MAX_YEAR` """ if year < MIN_YEAR or year > MAX_YEAR: raise ValueError("Year out of range (%d..%d)" % (MIN_YEAR, MAX_YEAR)) return DAYS_IN_YEAR[year] @classmethod def days_in_month(cls, year, month): """Return the number of days in `month` of `year`. :param year: the year to look up :type year: int :param year: the month to look up :type year: int :rtype: int :raises ValueError: if `year` or `month` is out of range: :attr:`MIN_YEAR` <= year <= :attr:`MAX_YEAR`; 1 <= year <= 12 """ if year < MIN_YEAR or year > MAX_YEAR: raise ValueError("Year out of range (%d..%d)" % (MIN_YEAR, MAX_YEAR)) if month < 1 or month > 12: raise ValueError("Month out of range (1..12)") return DAYS_IN_MONTH[(year, month)] @classmethod def __calc_ordinal(cls, year, month, day): if day < 0: day = cls.days_in_month(year, month) + int(day) + 1 # The built-in date class does this faster than a # long-hand pure Python algorithm could return date(year, month, day).toordinal() # CLASS ATTRIBUTES # min = None """The earliest date value possible.""" max = None """The latest date value possible.""" resolution = None """The minimum resolution supported.""" # INSTANCE ATTRIBUTES # __ordinal = 0 __year = 0 __month = 0 __day = 0 @property def year(self): """The year of the date. :type: int """ return self.__year @property def month(self): """The month of the date. :type: int """ return self.__month @property def day(self): """The day of the date. :type: int """ if self.__day == 0: return 0 if self.__day >= 1: return self.__day return self.days_in_month(self.__year, self.__month) + self.__day + 1 @property def year_month_day(self): """3-tuple of (year, month, day) describing the date. :rtype: (int, int, int) """ return self.year, self.month, self.day @property def year_week_day(self): """3-tuple of (year, week_of_year, day_of_week) describing the date. `day_of_week` will be 1 for Monday and 7 for Sunday. :rtype: (int, int, int) """ ordinal = self.__ordinal year = self.__year def day_of_week(o): return ((o - 1) % 7) + 1 def iso_week_1(y): j4 = Date(y, 1, 4) return j4 + Duration(days=(1 - day_of_week(j4.to_ordinal()))) if ordinal >= Date(year, 12, 29).to_ordinal(): week1 = iso_week_1(year + 1) if ordinal < week1.to_ordinal(): week1 = iso_week_1(year) else: year += 1 else: week1 = iso_week_1(year) if ordinal < week1.to_ordinal(): year -= 1 week1 = iso_week_1(year) return (year, int((ordinal - week1.to_ordinal()) / 7 + 1), day_of_week(ordinal)) @property def year_day(self): """2-tuple of (year, day_of_the_year) describing the date. This is the number of the day relative to the start of the year, with `1 Jan` corresponding to `1`. :rtype: (int, int) """ return (self.__year, self.toordinal() - Date(self.__year, 1, 1).toordinal() + 1) # OPERATIONS # def __hash__(self): """""" return hash(self.toordinal()) def __eq__(self, other): """`==` comparison with :class:`.Date` or :class:`datetime.date`.""" if isinstance(other, (Date, date)): return self.toordinal() == other.toordinal() return False def __ne__(self, other): """`!=` comparison with :class:`.Date` or :class:`datetime.date`.""" return not self.__eq__(other) def __lt__(self, other): """`<` comparison with :class:`.Date` or :class:`datetime.date`.""" if isinstance(other, (Date, date)): return self.toordinal() < other.toordinal() raise TypeError("'<' not supported between instances of 'Date' and %r" % type(other).__name__) def __le__(self, other): """`<=` comparison with :class:`.Date` or :class:`datetime.date`.""" if isinstance(other, (Date, date)): return self.toordinal() <= other.toordinal() raise TypeError("'<=' not supported between instances of 'Date' and %r" % type(other).__name__) def __ge__(self, other): """`>=` comparison with :class:`.Date` or :class:`datetime.date`.""" if isinstance(other, (Date, date)): return self.toordinal() >= other.toordinal() raise TypeError("'>=' not supported between instances of 'Date' and %r" % type(other).__name__) def __gt__(self, other): """`>` comparison with :class:`.Date` or :class:`datetime.date`.""" if isinstance(other, (Date, date)): return self.toordinal() > other.toordinal() raise TypeError("'>' not supported between instances of 'Date' and %r" % type(other).__name__) def __add__(self, other): """Add a :class:`.Duration`. :rtype: Date :raises ValueError: if the added duration has a time component. """ def add_months(d, months): years, months = symmetric_divmod(months, 12) year = d.__year + years month = d.__month + months while month > 12: year += 1 month -= 12 while month < 1: year -= 1 month += 12 d.__year = year d.__month = month def add_days(d, days): assert 1 <= d.__day <= 28 or -28 <= d.__day <= -1 if d.__day >= 1: new_days = d.__day + days if 1 <= new_days <= 27: d.__day = new_days return d0 = Date.from_ordinal(d.__ordinal + days) d.__year, d.__month, d.__day = d0.__year, d0.__month, d0.__day if isinstance(other, Duration): if other.seconds or other.nanoseconds: raise ValueError("Cannot add a Duration with seconds or " "nanoseconds to a Date") if other.months == other.days == 0: return self new_date = self.replace() # Add days before months as the former sometimes # requires the current ordinal to be correct. if other.days: add_days(new_date, other.days) if other.months: add_months(new_date, other.months) new_date.__ordinal = self.__calc_ordinal(new_date.year, new_date.month, new_date.day) return new_date return NotImplemented def __sub__(self, other): """Subtract a :class:`.Date` or :class:`.Duration`. :returns: If a :class:`.Date` is subtracted, the time between the two dates is returned as :class:`.Duration`. If a :class:`.Duration` is subtracted, a new :class:`.Date` is returned. :rtype: Date or Duration :raises ValueError: if the added duration has a time component. """ if isinstance(other, (Date, date)): return Duration(days=(self.toordinal() - other.toordinal())) try: return self.__add__(-other) except TypeError: return NotImplemented def __copy__(self): return self.__new(self.__ordinal, self.__year, self.__month, self.__day) def __deepcopy__(self, *args, **kwargs): return self.__copy__() # INSTANCE METHODS # def replace(self, **kwargs): """Return a :class:`.Date` with one or more components replaced. :Keyword Arguments: * **year** (`int`): overwrite the year - default: `self.year` * **month** (`int`): overwrite the month - default: `self.month` * **day** (`int`): overwrite the day - default: `self.day` """ return Date(kwargs.get("year", self.__year), kwargs.get("month", self.__month), kwargs.get("day", self.__day)) def time_tuple(self): """Convert the date to :class:`time.struct_time`. :rtype: time.struct_time """ _, _, day_of_week = self.year_week_day _, day_of_year = self.year_day return struct_time((self.year, self.month, self.day, 0, 0, 0, day_of_week - 1, day_of_year, -1)) def to_ordinal(self): """The date's proleptic Gregorian ordinal. The corresponding class method for the reverse ordinal-to-date transformation is :meth:`.Date.from_ordinal`. :rtype: int """ return self.__ordinal def to_clock_time(self, epoch): """Convert the date to :class:`ClockTime` relative to `epoch`. :param epoch: the epoch to which the date is relative :type epoch: Date :rtype: ClockTime """ try: return ClockTime(86400 * (self.to_ordinal() - epoch.to_ordinal())) except AttributeError: raise TypeError("Epoch has no ordinal value") def to_native(self): """Convert to a native Python :class:`datetime.date` value. :rtype: datetime.date """ return date.fromordinal(self.to_ordinal()) def weekday(self): """The day of the week where Monday is 0 and Sunday is 6. :rtype: int """ return self.year_week_day[2] - 1 def iso_weekday(self): """The day of the week where Monday is 1 and Sunday is 7. :rtype: int """ return self.year_week_day[2] def iso_calendar(self): """Alias for :attr:`.year_week_day`""" return self.year_week_day def iso_format(self): """Return the :class:`.Date` as ISO formatted string. :rtype: str """ if self.__ordinal == 0: return "0000-00-00" return "%04d-%02d-%02d" % self.year_month_day def __repr__(self): """""" if self.__ordinal == 0: return "neo4j.time.ZeroDate" return "neo4j.time.Date(%r, %r, %r)" % self.year_month_day def __str__(self): """""" return self.iso_format() def __format__(self, format_spec): """""" raise NotImplementedError() Date.min = Date.from_ordinal(1) Date.max = Date.from_ordinal(3652059) Date.resolution = Duration(days=1) #: A :class:`neo4j.time.Date` instance set to `0000-00-00`. #: This has an ordinal value of `0`. ZeroDate = object.__new__(Date) class Time(metaclass=TimeType): """Time of day. The :class:`.Time` class is a nanosecond-precision drop-in replacement for the standard library :class:`datetime.time` class. A high degree of API compatibility with the standard library classes is provided. :class:`neo4j.time.Time` objects introduce the concept of ``ticks``. This is simply a count of the number of nanoseconds since midnight, in many ways analogous to the :class:`neo4j.time.Date` ordinal. `ticks` values are integers, with a minimum value of `0` and a maximum of `86_399_999_999_999`. Local times are represented by :class:`.Time` with no ``tzinfo``. :param hour: the hour of the time. Must be in range 0 <= hour < 24. :type hour: int :param minute: the minute of the time. Must be in range 0 <= minute < 60. :type minute: int :param second: the second of the time. Must be in range 0 <= second < 60. :type second: int :param nanosecond: the nanosecond of the time. Must be in range 0 <= nanosecond < 999999999. :type nanosecond: int :param tzinfo: timezone or None to get a local :class:`.Time`. :type tzinfo: datetime.tzinfo or None :raises ValueError: if one of the parameters is out of range. """ # CONSTRUCTOR # def __new__(cls, hour=0, minute=0, second=0, nanosecond=0, tzinfo=None): hour, minute, second, nanosecond = cls.__normalize_nanosecond( hour, minute, second, nanosecond ) ticks = (3600000000000 * hour + 60000000000 * minute + 1000000000 * second + nanosecond) return cls.__new(ticks, hour, minute, second, nanosecond, tzinfo) @classmethod def __new(cls, ticks, hour, minute, second, nanosecond, tzinfo): instance = object.__new__(cls) instance.__ticks = int(ticks) instance.__hour = int(hour) instance.__minute = int(minute) instance.__second = int(second) instance.__nanosecond = int(nanosecond) instance.__tzinfo = tzinfo return instance def __getattr__(self, name): """Map standard library attribute names to local attribute names, for compatibility. """ try: return { "isoformat": self.iso_format, "utcoffset": self.utc_offset, }[name] except KeyError: raise AttributeError("Date has no attribute %r" % name) # CLASS METHODS # @classmethod def now(cls, tz=None): """Get the current time. :param tz: optional timezone :type tz: datetime.tzinfo :rtype: Time :raises OverflowError: if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038. """ if tz is None: return cls.from_clock_time(Clock().local_time(), UnixEpoch) else: return ( DateTime.utc_now() .replace(tzinfo=timezone.utc).astimezone(tz) .timetz() ) @classmethod def utc_now(cls): """Get the current time as UTC local time. :rtype: Time """ return cls.from_clock_time(Clock().utc_time(), UnixEpoch) @classmethod def from_iso_format(cls, s): """Parse a ISO formatted time string. Accepted formats: Local times: 'hh' 'hh:mm' 'hh:mm:ss' 'hh:mm:ss.ssss...' Times with timezones (UTC offset): '<local time>+hh:mm' '<local time>+hh:mm:ss' '<local time>+hh:mm:ss.ssss....' '<local time>-hh:mm' '<local time>-hh:mm:ss' '<local time>-hh:mm:ss.ssss....' Where the UTC offset will only respect hours and minutes. Seconds and sub-seconds are ignored. :param s: String to parse :type s: str :rtype: Time :raises ValueError: if the string does not match the required format. """ from pytz import FixedOffset m = TIME_ISO_PATTERN.match(s) if m: hour = int(m.group(1)) minute = int(m.group(3) or 0) second = int(m.group(6) or 0) nanosecond = m.group(7) if nanosecond: nanosecond = int(nanosecond[1:10].ljust(9, "0")) else: nanosecond = 0 if m.group(8) is None: return cls(hour, minute, second, nanosecond) else: offset_multiplier = 1 if m.group(9) == "+" else -1 offset_hour = int(m.group(10)) offset_minute = int(m.group(11)) # pytz only supports offsets of minute resolution # so we can ignore this part # offset_second = float(m.group(13) or 0.0) offset = 60 * offset_hour + offset_minute return cls(hour, minute, second, nanosecond, tzinfo=FixedOffset(offset_multiplier * offset)) raise ValueError("Time string is not in ISO format") @classmethod def from_ticks(cls, ticks, tz=None): """Create a time from ticks (nanoseconds since midnight). :param ticks: nanoseconds since midnight :type ticks: int :param tz: optional timezone :type tz: datetime.tzinfo :rtype: Time :raises ValueError: if ticks is out of bounds (0 <= ticks < 86400000000000) """ if not isinstance(ticks, int): raise TypeError("Ticks must be int") if 0 <= ticks < 86400000000000: second, nanosecond = divmod(ticks, NANO_SECONDS) minute, second = divmod(second, 60) hour, minute = divmod(minute, 60) return cls.__new(ticks, hour, minute, second, nanosecond, tz) raise ValueError("Ticks out of range (0..86400000000000)") @classmethod def from_native(cls, t): """Convert from a native Python :class:`datetime.time` value. :param t: time to convert from :type t: datetime.time :rtype: Time """ nanosecond = t.microsecond * 1000 return Time(t.hour, t.minute, t.second, nanosecond, t.tzinfo) @classmethod def from_clock_time(cls, clock_time, epoch): """Convert from a :class:`.ClockTime` relative to a given epoch. This method, in contrast to most others of this package, assumes days of exactly 24 hours. :param clock_time: the clock time as :class:`.ClockTime` or as tuple of (seconds, nanoseconds) :type clock_time: ClockTime or (float, int) :param epoch: the epoch to which `clock_time` is relative :type epoch: DateTime :rtype: Time """ clock_time = ClockTime(*clock_time) ts = clock_time.seconds % 86400 nanoseconds = int(NANO_SECONDS * ts + clock_time.nanoseconds) ticks = (epoch.time().ticks + nanoseconds) % (86400 * NANO_SECONDS) return Time.from_ticks(ticks) @classmethod def __normalize_hour(cls, hour): hour = int(hour) if 0 <= hour < 24: return hour raise ValueError("Hour out of range (0..23)") @classmethod def __normalize_minute(cls, hour, minute): hour = cls.__normalize_hour(hour) minute = int(minute) if 0 <= minute < 60: return hour, minute raise ValueError("Minute out of range (0..59)") @classmethod def __normalize_second(cls, hour, minute, second): hour, minute = cls.__normalize_minute(hour, minute) second = int(second) if 0 <= second < 60: return hour, minute, second raise ValueError("Second out of range (0..59)") @classmethod def __normalize_nanosecond(cls, hour, minute, second, nanosecond): hour, minute, second = cls.__normalize_second(hour, minute, second) if 0 <= nanosecond < NANO_SECONDS: return hour, minute, second, nanosecond raise ValueError("Nanosecond out of range (0..%s)" % (NANO_SECONDS - 1)) # CLASS ATTRIBUTES # min = None """The earliest time value possible.""" max = None """The latest time value possible.""" resolution = None """The minimum resolution supported.""" # INSTANCE ATTRIBUTES # __ticks = 0 __hour = 0 __minute = 0 __second = 0 __nanosecond = 0 __tzinfo = None @property def ticks(self): """The total number of nanoseconds since midnight. :type: int """ return self.__ticks @property def hour(self): """The hours of the time. :type: int """ return self.__hour @property def minute(self): """The minutes of the time. :type: int """ return self.__minute @property def second(self): """The seconds of the time. :type: int """ return self.__second @property def nanosecond(self): """The nanoseconds of the time. :type: int """ return self.__nanosecond @property def hour_minute_second_nanosecond(self): """The time as a tuple of (hour, minute, second, nanosecond). :type: (int, int, int, int)""" return self.__hour, self.__minute, self.__second, self.__nanosecond @property def tzinfo(self): """The timezone of this time. :type: datetime.tzinfo or None""" return self.__tzinfo # OPERATIONS # def _get_both_normalized_ticks(self, other, strict=True): if (isinstance(other, (time, Time)) and ((self.utc_offset() is None) ^ (other.utcoffset() is None))): if strict: raise TypeError("can't compare offset-naive and offset-aware " "times") else: return None, None if isinstance(other, Time): other_ticks = other.__ticks elif isinstance(other, time): other_ticks = int(3600000000000 * other.hour + 60000000000 * other.minute + NANO_SECONDS * other.second + 1000 * other.microsecond) else: return None, None utc_offset = other.utcoffset() if utc_offset is not None: other_ticks -= utc_offset.total_seconds() * NANO_SECONDS self_ticks = self.__ticks utc_offset = self.utc_offset() if utc_offset is not None: self_ticks -= utc_offset.total_seconds() * NANO_SECONDS return self_ticks, other_ticks def __hash__(self): """""" if self.__nanosecond % 1000 == 0: return hash(self.to_native()) self_ticks = self.__ticks if self.utc_offset() is not None: self_ticks -= self.utc_offset().total_seconds() * NANO_SECONDS return hash(self_ticks) def __eq__(self, other): """`==` comparison with :class:`.Time` or :class:`datetime.time`.""" self_ticks, other_ticks = self._get_both_normalized_ticks(other, strict=False) if self_ticks is None: return False return self_ticks == other_ticks def __ne__(self, other): """`!=` comparison with :class:`.Time` or :class:`datetime.time`.""" return not self.__eq__(other) def __lt__(self, other): """`<` comparison with :class:`.Time` or :class:`datetime.time`.""" self_ticks, other_ticks = self._get_both_normalized_ticks(other) if self_ticks is None: return NotImplemented return self_ticks < other_ticks def __le__(self, other): """`<=` comparison with :class:`.Time` or :class:`datetime.time`.""" self_ticks, other_ticks = self._get_both_normalized_ticks(other) if self_ticks is None: return NotImplemented return self_ticks <= other_ticks def __ge__(self, other): """`>=` comparison with :class:`.Time` or :class:`datetime.time`.""" self_ticks, other_ticks = self._get_both_normalized_ticks(other) if self_ticks is None: return NotImplemented return self_ticks >= other_ticks def __gt__(self, other): """`>` comparison with :class:`.Time` or :class:`datetime.time`.""" self_ticks, other_ticks = self._get_both_normalized_ticks(other) if self_ticks is None: return NotImplemented return self_ticks > other_ticks def __copy__(self): return self.__new(self.__ticks, self.__hour, self.__minute, self.__second, self.__nanosecond, self.__tzinfo) def __deepcopy__(self, *args, **kwargs): return self.__copy__() # INSTANCE METHODS # def replace(self, **kwargs): """Return a :class:`.Time` with one or more components replaced. :Keyword Arguments: * **hour** (`int`): overwrite the hour - default: `self.hour` * **minute** (`int`): overwrite the minute - default: `self.minute` * **second** (`int`): overwrite the second - default: `int(self.second)` * **nanosecond** (`int`): overwrite the nanosecond - default: `self.nanosecond` * **tzinfo** (`datetime.tzinfo` or `None`): overwrite the timezone - default: `self.tzinfo` :rtype: Time """ return Time(hour=kwargs.get("hour", self.__hour), minute=kwargs.get("minute", self.__minute), second=kwargs.get("second", self.__second), nanosecond=kwargs.get("nanosecond", self.__nanosecond), tzinfo=kwargs.get("tzinfo", self.__tzinfo)) def _utc_offset(self, dt=None): if self.tzinfo is None: return None try: value = self.tzinfo.utcoffset(dt) except TypeError: # For timezone implementations not compatible with the custom # datetime implementations, we can't do better than this. value = self.tzinfo.utcoffset(dt.to_native()) if value is None: return None if isinstance(value, timedelta): s = value.total_seconds() if not (-86400 < s < 86400): raise ValueError("utcoffset must be less than a day") if s % 60 != 0 or value.microseconds != 0: raise ValueError("utcoffset must be a whole number of minutes") return value raise TypeError("utcoffset must be a timedelta") def utc_offset(self): """Return the UTC offset of this time. :return: None if this is a local time (:attr:`.tzinfo` is None), else returns `self.tzinfo.utcoffset(self)`. :rtype: datetime.timedelta :raises ValueError: if `self.tzinfo.utcoffset(self)` is not None and a :class:`timedelta` with a magnitude greater equal 1 day or that is not a whole number of minutes. :raises TypeError: if `self.tzinfo.utcoffset(self)` does return anything but None or a :class:`datetime.timedelta`. """ return self._utc_offset() def dst(self): """Get the daylight saving time adjustment (DST). :return: None if this is a local time (:attr:`.tzinfo` is None), else returns `self.tzinfo.dst(self)`. :rtype: datetime.timedelta :raises ValueError: if `self.tzinfo.dst(self)` is not None and a :class:`timedelta` with a magnitude greater equal 1 day or that is not a whole number of minutes. :raises TypeError: if `self.tzinfo.dst(self)` does return anything but None or a :class:`datetime.timedelta`. """ if self.tzinfo is None: return None try: value = self.tzinfo.dst(self) except TypeError: # For timezone implementations not compatible with the custom # datetime implementations, we can't do better than this. value = self.tzinfo.dst(self.to_native()) if value is None: return None if isinstance(value, timedelta): if value.days != 0: raise ValueError("dst must be less than a day") if value.seconds % 60 != 0 or value.microseconds != 0: raise ValueError("dst must be a whole number of minutes") return value raise TypeError("dst must be a timedelta") def tzname(self): """Get the name of the :class:`.Time`'s timezone. :returns: None if the time is local (i.e., has no timezone), else return `self.tzinfo.tzname(self)` :rtype: str or None """ if self.tzinfo is None: return None try: return self.tzinfo.tzname(self) except TypeError: # For timezone implementations not compatible with the custom # datetime implementations, we can't do better than this. return self.tzinfo.tzname(self.to_native()) def to_clock_time(self): """Convert to :class:`.ClockTime`. :rtype: ClockTime """ seconds, nanoseconds = divmod(self.ticks, NANO_SECONDS) return ClockTime(seconds, nanoseconds) def to_native(self): """Convert to a native Python `datetime.time` value. This conversion is lossy as the native time implementation only supports a resolution of microseconds instead of nanoseconds. :rtype: datetime.time """ h, m, s, ns = self.hour_minute_second_nanosecond µs = round_half_to_even(ns / 1000) tz = self.tzinfo return time(h, m, s, µs, tz) def iso_format(self): """Return the :class:`.Time` as ISO formatted string. :rtype: str """ s = "%02d:%02d:%02d.%09d" % self.hour_minute_second_nanosecond offset = self.utc_offset() if offset is not None: s += "%+03d:%02d" % divmod(offset.total_seconds() // 60, 60) return s def __repr__(self): """""" if self.tzinfo is None: return "neo4j.time.Time(%r, %r, %r, %r)" % \ self.hour_minute_second_nanosecond else: return "neo4j.time.Time(%r, %r, %r, %r, tzinfo=%r)" % \ (self.hour_minute_second_nanosecond + (self.tzinfo,)) def __str__(self): """""" return self.iso_format() def __format__(self, format_spec): """""" raise NotImplementedError() Time.min = Time(hour=0, minute=0, second=0, nanosecond=0) Time.max = Time(hour=23, minute=59, second=59, nanosecond=999999999) Time.resolution = Duration(nanoseconds=1) #: A :class:`.Time` instance set to `00:00:00`. #: This has a :attr:`.ticks` value of `0`. Midnight = Time.min #: A :class:`.Time` instance set to `12:00:00`. #: This has a :attr:`.ticks` value of `43200000000000`. Midday = Time(hour=12) @total_ordering class DateTime(metaclass=DateTimeType): """A point in time represented as a date and a time. The :class:`.DateTime` class is a nanosecond-precision drop-in replacement for the standard library :class:`datetime.datetime` class. As such, it contains both :class:`.Date` and :class:`.Time` information and draws functionality from those individual classes. A :class:`.DateTime` object is fully compatible with the Python time zone library `pytz <https://pypi.org/project/pytz/>`_. Functions such as `normalize` and `localize` can be used in the same way as they are with the standard library classes. Regular construction of a :class:`.DateTime` object requires at least the `year`, `month` and `day` arguments to be supplied. The optional `hour`, `minute` and `second` arguments default to zero and `tzinfo` defaults to :const:`None`. `year`, `month`, and `day` are passed to the constructor of :class:`.Date`. `hour`, `minute`, `second`, `nanosecond`, and `tzinfo` are passed to the constructor of :class:`.Time`. See their documentation for more details. >>> dt = DateTime(2018, 4, 30, 12, 34, 56, 789123456); dt neo4j.time.DateTime(2018, 4, 30, 12, 34, 56, 789123456) >>> dt.second 56.789123456 """ # CONSTRUCTOR # def __new__(cls, year, month, day, hour=0, minute=0, second=0, nanosecond=0, tzinfo=None): return cls.combine(Date(year, month, day), Time(hour, minute, second, nanosecond, tzinfo)) def __getattr__(self, name): """ Map standard library attribute names to local attribute names, for compatibility. """ try: return { "astimezone": self.as_timezone, "isocalendar": self.iso_calendar, "isoformat": self.iso_format, "isoweekday": self.iso_weekday, "strftime": self.__format__, "toordinal": self.to_ordinal, "timetuple": self.time_tuple, "utcoffset": self.utc_offset, "utctimetuple": self.utc_time_tuple, }[name] except KeyError: raise AttributeError("DateTime has no attribute %r" % name) # CLASS METHODS # @classmethod def now(cls, tz=None): """Get the current date and time. :param tz: timezone. Set to None to create a local :class:`.DateTime`. :type tz: datetime.tzinfo` or None :rtype: DateTime :raises OverflowError: if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038. """ if tz is None: return cls.from_clock_time(Clock().local_time(), UnixEpoch) else: try: return tz.fromutc(cls.from_clock_time( Clock().utc_time(), UnixEpoch ).replace(tzinfo=tz)) except TypeError: # For timezone implementations not compatible with the custom # datetime implementations, we can't do better than this. utc_now = cls.from_clock_time( Clock().utc_time(), UnixEpoch ) utc_now_native = utc_now.to_native() now_native = tz.fromutc(utc_now_native) now = cls.from_native(now_native) return now.replace( nanosecond=(now.nanosecond + utc_now.nanosecond - utc_now_native.microsecond * 1000) ) @classmethod def utc_now(cls): """Get the current date and time in UTC :rtype: DateTime """ return cls.from_clock_time(Clock().utc_time(), UnixEpoch) @classmethod def from_iso_format(cls, s): """Parse a ISO formatted date with time string. :param s: String to parse :type s: str :rtype: Time :raises ValueError: if the string does not match the ISO format. """ try: return cls.combine(Date.from_iso_format(s[0:10]), Time.from_iso_format(s[11:])) except ValueError: raise ValueError("DateTime string is not in ISO format") @classmethod def from_timestamp(cls, timestamp, tz=None): """:class:`.DateTime` from a time stamp (seconds since unix epoch). :param timestamp: the unix timestamp (seconds since unix epoch). :type timestamp: float :param tz: timezone. Set to None to create a local :class:`.DateTime`. :type tz: datetime.tzinfo or None :rtype: DateTime :raises OverflowError: if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038. """ if tz is None: return cls.from_clock_time( ClockTime(timestamp) + Clock().local_offset(), UnixEpoch ) else: return ( cls.utc_from_timestamp(timestamp) .replace(tzinfo=timezone.utc).astimezone(tz) ) @classmethod def utc_from_timestamp(cls, timestamp): """:class:`.DateTime` from a time stamp (seconds since unix epoch). Returns the `DateTime` as local date `DateTime` in UTC. :rtype: DateTime """ return cls.from_clock_time((timestamp, 0), UnixEpoch) @classmethod def from_ordinal(cls, ordinal): """:class:`.DateTime` from an ordinal. For more info about ordinals see :meth:`.Date.from_ordinal`. :rtype: DateTime """ return cls.combine(Date.from_ordinal(ordinal), Midnight) @classmethod def combine(cls, date, time): """Combine a :class:`.Date` and a :class:`.Time` to a :class:`DateTime`. :param date: the date :type date: Date :param time: the time :type time: Time :rtype: DateTime :raises AssertionError: if the parameter types don't match. """ assert isinstance(date, Date) assert isinstance(time, Time) instance = object.__new__(cls) instance.__date = date instance.__time = time return instance @classmethod def parse(cls, date_string, format): raise NotImplementedError() @classmethod def from_native(cls, dt): """Convert from a native Python :class:`datetime.datetime` value. :param dt: the datetime to convert :type dt: datetime.datetime :rtype: DateTime """ return cls.combine(Date.from_native(dt.date()), Time.from_native(dt.timetz())) @classmethod def from_clock_time(cls, clock_time, epoch): """Convert from a :class:`ClockTime` relative to a given epoch. :param clock_time: the clock time as :class:`.ClockTime` or as tuple of (seconds, nanoseconds) :type clock_time: ClockTime or (float, int) :param epoch: the epoch to which `clock_time` is relative :type epoch: DateTime :rtype: DateTime :raises ValueError: if `clock_time` is invalid. """ try: seconds, nanoseconds = ClockTime(*clock_time) except (TypeError, ValueError): raise ValueError("Clock time must be a 2-tuple of (s, ns)") else: ordinal, seconds = divmod(seconds, 86400) ticks = epoch.time().ticks + seconds * NANO_SECONDS + nanoseconds days, ticks = divmod(ticks, 86400 * NANO_SECONDS) ordinal += days date_ = Date.from_ordinal(ordinal + epoch.date().to_ordinal()) time_ = Time.from_ticks(ticks) return cls.combine(date_, time_) # CLASS ATTRIBUTES # min = None """The earliest date time value possible.""" max = None """The latest date time value possible.""" resolution = None """The minimum resolution supported.""" # INSTANCE ATTRIBUTES # @property def year(self): """The year of the :class:`.DateTime`. See :attr:`.Date.year`. """ return self.__date.year @property def month(self): """The year of the :class:`.DateTime`. See :attr:`.Date.year`.""" return self.__date.month @property def day(self): """The day of the :class:`.DateTime`'s date. See :attr:`.Date.day`.""" return self.__date.day @property def year_month_day(self): """The year_month_day of the :class:`.DateTime`'s date. See :attr:`.Date.year_month_day`.""" return self.__date.year_month_day @property def year_week_day(self): """The year_week_day of the :class:`.DateTime`'s date. See :attr:`.Date.year_week_day`.""" return self.__date.year_week_day @property def year_day(self): """The year_day of the :class:`.DateTime`'s date. See :attr:`.Date.year_day`.""" return self.__date.year_day @property def hour(self): """The hour of the :class:`.DateTime`'s time. See :attr:`.Time.hour`.""" return self.__time.hour @property def minute(self): """The minute of the :class:`.DateTime`'s time. See :attr:`.Time.minute`.""" return self.__time.minute @property def second(self): """The second of the :class:`.DateTime`'s time. See :attr:`.Time.second`.""" return self.__time.second @property def nanosecond(self): """The nanosecond of the :class:`.DateTime`'s time. See :attr:`.Time.nanosecond`.""" return self.__time.nanosecond @property def tzinfo(self): """The tzinfo of the :class:`.DateTime`'s time. See :attr:`.Time.tzinfo`.""" return self.__time.tzinfo @property def hour_minute_second_nanosecond(self): """The hour_minute_second_nanosecond of the :class:`.DateTime`'s time. See :attr:`.Time.hour_minute_second_nanosecond`.""" return self.__time.hour_minute_second_nanosecond # OPERATIONS # def _get_both_normalized(self, other, strict=True): if (isinstance(other, (datetime, DateTime)) and ((self.utc_offset() is None) ^ (other.utcoffset() is None))): if strict: raise TypeError("can't compare offset-naive and offset-aware " "datetimes") else: return None, None self_norm = self utc_offset = self.utc_offset() if utc_offset is not None: self_norm -= utc_offset self_norm = self_norm.replace(tzinfo=None) other_norm = other if isinstance(other, (datetime, DateTime)): utc_offset = other.utcoffset() if utc_offset is not None: other_norm -= utc_offset other_norm = other_norm.replace(tzinfo=None) else: return None, None return self_norm, other_norm def __hash__(self): """""" if self.nanosecond % 1000 == 0: return hash(self.to_native()) self_norm = self utc_offset = self.utc_offset() if utc_offset is not None: self_norm -= utc_offset return hash(self_norm.date()) ^ hash(self_norm.time()) def __eq__(self, other): """ `==` comparison with :class:`.DateTime` or :class:`datetime.datetime`. """ if not isinstance(other, (datetime, DateTime)): return NotImplemented if self.utc_offset() == other.utcoffset(): return self.date() == other.date() and self.time() == other.time() self_norm, other_norm = self._get_both_normalized(other, strict=False) if self_norm is None: return False return self_norm == other_norm def __ne__(self, other): """ `!=` comparison with :class:`.DateTime` or :class:`datetime.datetime`. """ return not self.__eq__(other) def __lt__(self, other): """ `<` comparison with :class:`.DateTime` or :class:`datetime.datetime`. """ if not isinstance(other, (datetime, DateTime)): return NotImplemented if self.utc_offset() == other.utcoffset(): if self.date() == other.date(): return self.time() < other.time() return self.date() < other.date() self_norm, other_norm = self._get_both_normalized(other) return (self_norm.date() < other_norm.date() or self_norm.time() < other_norm.time()) def __le__(self, other): """ `<=` comparison with :class:`.DateTime` or :class:`datetime.datetime`. """ if not isinstance(other, (datetime, DateTime)): return NotImplemented if self.utc_offset() == other.utcoffset(): if self.date() == other.date(): return self.time() <= other.time() return self.date() <= other.date() self_norm, other_norm = self._get_both_normalized(other) return self_norm <= other_norm def __ge__(self, other): """ `>=` comparison with :class:`.DateTime` or :class:`datetime.datetime`. """ if not isinstance(other, (datetime, DateTime)): return NotImplemented if self.utc_offset() == other.utcoffset(): if self.date() == other.date(): return self.time() >= other.time() return self.date() >= other.date() self_norm, other_norm = self._get_both_normalized(other) return self_norm >= other_norm def __gt__(self, other): """ `>` comparison with :class:`.DateTime` or :class:`datetime.datetime`. """ if not isinstance(other, (datetime, DateTime)): return NotImplemented if self.utc_offset() == other.utcoffset(): if self.date() == other.date(): return self.time() > other.time() return self.date() > other.date() self_norm, other_norm = self._get_both_normalized(other) return (self_norm.date() > other_norm.date() or self_norm.time() > other_norm.time()) def __add__(self, other): """Add a :class:`datetime.timedelta`. :rtype: DateTime """ if isinstance(other, timedelta): t = (self.to_clock_time() + ClockTime(86400 * other.days + other.seconds, other.microseconds * 1000)) days, seconds = symmetric_divmod(t.seconds, 86400) date_ = Date.from_ordinal(days + 1) time_ = Time.from_ticks(round_half_to_even( seconds * NANO_SECONDS + t.nanoseconds )) return self.combine(date_, time_).replace(tzinfo=self.tzinfo) if isinstance(other, Duration): t = (self.to_clock_time() + ClockTime(other.seconds, other.nanoseconds)) days, seconds = symmetric_divmod(t.seconds, 86400) date_ = self.date() + Duration(months=other.months, days=days + other.days) time_ = Time.from_ticks(seconds * NANO_SECONDS + t.nanoseconds) return self.combine(date_, time_).replace(tzinfo=self.tzinfo) return NotImplemented def __sub__(self, other): """Subtract a datetime or a timedelta. Supported :class:`.DateTime` (returns :class:`.Duration`), :class:`datetime.datetime` (returns :class:`datetime.timedelta`), and :class:`datetime.timedelta` (returns :class:`.DateTime`). :rtype: Duration or datetime.timedelta or DateTime """ if isinstance(other, DateTime): self_month_ordinal = 12 * (self.year - 1) + self.month other_month_ordinal = 12 * (other.year - 1) + other.month months = self_month_ordinal - other_month_ordinal days = self.day - other.day t = self.time().to_clock_time() - other.time().to_clock_time() return Duration(months=months, days=days, seconds=t.seconds, nanoseconds=t.nanoseconds) if isinstance(other, datetime): days = self.to_ordinal() - other.toordinal() t = (self.time().to_clock_time() - ClockTime( 3600 * other.hour + 60 * other.minute + other.second, other.microsecond * 1000 )) return timedelta(days=days, seconds=t.seconds, microseconds=(t.nanoseconds // 1000)) if isinstance(other, Duration): return self.__add__(-other) if isinstance(other, timedelta): return self.__add__(-other) return NotImplemented def __copy__(self): return self.combine(self.__date, self.__time) def __deepcopy__(self, *args, **kwargs): return self.__copy__() # INSTANCE METHODS # def date(self): """The date :rtype: Date """ return self.__date def time(self): """The time without timezone info :rtype: Time """ return self.__time.replace(tzinfo=None) def timetz(self): """The time with timezone info :rtype: Time """ return self.__time def replace(self, **kwargs): """Return a :class:`.DateTime` with one or more components replaced. See :meth:`.Date.replace` and :meth:`.Time.replace` for available arguments. :rtype: DateTime """ date_ = self.__date.replace(**kwargs) time_ = self.__time.replace(**kwargs) return self.combine(date_, time_) def as_timezone(self, tz): """Convert this :class:`.DateTime` to another timezone. :param tz: the new timezone :type tz: datetime.tzinfo or None :return: the same object if `tz` is None. Else, a new :class:`.DateTime` that's the same point in time but in a different timezone. :rtype: DateTime """ if self.tzinfo is None: return self utc = (self - self.utc_offset()).replace(tzinfo=tz) try: return tz.fromutc(utc) except TypeError: # For timezone implementations not compatible with the custom # datetime implementations, we can't do better than this. native_utc = utc.to_native() native_res = tz.fromutc(native_utc) res = self.from_native(native_res) return res.replace( nanosecond=(native_res.microsecond * 1000 + self.nanosecond % 1000) ) def utc_offset(self): """Get the date times utc offset. See :meth:`.Time.utc_offset`. """ return self.__time._utc_offset(self) def dst(self): """Get the daylight saving time adjustment (DST). See :meth:`.Time.dst`. """ return self.__time.dst() def tzname(self): """Get the timezone name. See :meth:`.Time.tzname`. """ return self.__time.tzname() def time_tuple(self): raise NotImplementedError() def utc_time_tuple(self): raise NotImplementedError() def to_ordinal(self): """Get the ordinal of the :class:`.DateTime`'s date. See :meth:`.Date.to_ordinal` """ return self.__date.to_ordinal() def to_clock_time(self): """Convert to :class:`.ClockTime`. :rtype: ClockTime """ total_seconds = 0 for year in range(1, self.year): total_seconds += 86400 * DAYS_IN_YEAR[year] for month in range(1, self.month): total_seconds += 86400 * Date.days_in_month(self.year, month) total_seconds += 86400 * (self.day - 1) seconds, nanoseconds = divmod(self.__time.ticks, NANO_SECONDS) return ClockTime(total_seconds + seconds, nanoseconds) def to_native(self): """Convert to a native Python :class:`datetime.datetime` value. This conversion is lossy as the native time implementation only supports a resolution of microseconds instead of nanoseconds. :rtype: datetime.datetime """ y, mo, d = self.year_month_day h, m, s, ns = self.hour_minute_second_nanosecond ms = int(ns / 1000) tz = self.tzinfo return datetime(y, mo, d, h, m, s, ms, tz) def weekday(self): """Get the weekday. See :meth:`.Date.weekday` """ return self.__date.weekday() def iso_weekday(self): """Get the ISO weekday. See :meth:`.Date.iso_weekday` """ return self.__date.iso_weekday() def iso_calendar(self): """Get date as ISO tuple. See :meth:`.Date.iso_calendar` """ return self.__date.iso_calendar() def iso_format(self, sep="T"): """Return the :class:`.DateTime` as ISO formatted string. This method joins `self.date().iso_format()` (see :meth:`.Date.iso_format`) and `self.timetz().iso_format()` (see :meth:`.Time.iso_format`) with `sep` in between. :param sep: the separator between the formatted date and time. :type sep: str :rtype: str """ s = "%s%s%s" % (self.date().iso_format(), sep, self.timetz().iso_format()) time_tz = self.timetz() offset = time_tz.utc_offset() if offset is not None: # the time component will have taken care of formatting the offset return s offset = self.utc_offset() if offset is not None: s += "%+03d:%02d" % divmod(offset.total_seconds() // 60, 60) return s def __repr__(self): """""" if self.tzinfo is None: fields = (*self.year_month_day, *self.hour_minute_second_nanosecond) return "neo4j.time.DateTime(%r, %r, %r, %r, %r, %r, %r)" % fields else: fields = (*self.year_month_day, *self.hour_minute_second_nanosecond, self.tzinfo) return ("neo4j.time.DateTime(%r, %r, %r, %r, %r, %r, %r, tzinfo=%r)" % fields) def __str__(self): """""" return self.iso_format() def __format__(self, format_spec): """""" raise NotImplementedError() DateTime.min = DateTime.combine(Date.min, Time.min) DateTime.max = DateTime.combine(Date.max, Time.max) DateTime.resolution = Time.resolution #: A :class:`.DateTime` instance set to `0000-00-00T00:00:00`. #: This has a :class:`.Date` component equal to :attr:`ZeroDate` and a Never = DateTime.combine(ZeroDate, Midnight) #: A :class:`.DateTime` instance set to `1970-01-01T00:00:00`. UnixEpoch = DateTime(1970, 1, 1, 0, 0, 0)
neo4j/time/__init__.py
codereval_python_data_164
Return a dictionary of available Bolt protocol handlers, keyed by version tuple. If an explicit protocol version is provided, the dictionary will contain either zero or one items, depending on whether that version is supported. If no protocol version is provided, all available versions will be returned. :param protocol_version: tuple identifying a specific protocol version (e.g. (3, 5)) or None :return: dictionary of version tuple to handler class for all relevant and supported protocol versions :raise TypeError: if protocol version is not passed in a tuple @classmethod def protocol_handlers(cls, protocol_version=None): """ Return a dictionary of available Bolt protocol handlers, keyed by version tuple. If an explicit protocol version is provided, the dictionary will contain either zero or one items, depending on whether that version is supported. If no protocol version is provided, all available versions will be returned. :param protocol_version: tuple identifying a specific protocol version (e.g. (3, 5)) or None :return: dictionary of version tuple to handler class for all relevant and supported protocol versions :raise TypeError: if protocol version is not passed in a tuple """ # Carry out Bolt subclass imports locally to avoid circular dependency issues. from ._bolt3 import AsyncBolt3 from ._bolt4 import ( AsyncBolt4x1, AsyncBolt4x2, AsyncBolt4x3, AsyncBolt4x4, ) from ._bolt5 import AsyncBolt5x0 handlers = { AsyncBolt3.PROTOCOL_VERSION: AsyncBolt3, # 4.0 unsupported because no space left in the handshake AsyncBolt4x1.PROTOCOL_VERSION: AsyncBolt4x1, AsyncBolt4x2.PROTOCOL_VERSION: AsyncBolt4x2, AsyncBolt4x3.PROTOCOL_VERSION: AsyncBolt4x3, AsyncBolt4x4.PROTOCOL_VERSION: AsyncBolt4x4, AsyncBolt5x0.PROTOCOL_VERSION: AsyncBolt5x0, } if protocol_version is None: return handlers if not isinstance(protocol_version, tuple): raise TypeError("Protocol version must be specified as a tuple") if protocol_version in handlers: return {protocol_version: handlers[protocol_version]} return {} # Copyright (c) "Neo4j" # Neo4j Sweden AB [https://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import abc import asyncio from collections import deque from logging import getLogger from time import perf_counter from ..._async_compat.network import AsyncBoltSocket from ..._async_compat.util import AsyncUtil from ..._codec.hydration import v1 as hydration_v1 from ..._codec.packstream import v1 as packstream_v1 from ..._conf import PoolConfig from ..._exceptions import ( BoltError, BoltHandshakeError, SocketDeadlineExceeded, ) from ..._meta import get_user_agent from ...addressing import Address from ...api import ( ServerInfo, Version, ) from ...exceptions import ( AuthError, DriverError, IncompleteCommit, ServiceUnavailable, SessionExpired, ) from ._common import ( AsyncInbox, AsyncOutbox, CommitResponse, ) # Set up logger log = getLogger("neo4j") class AsyncBolt: """ Server connection for Bolt protocol. A :class:`.Bolt` should be constructed following a successful .open() Bolt handshake and takes the socket over which the handshake was carried out. """ # TODO: let packer/unpacker know of hydration (give them hooks?) # TODO: make sure query parameter dehydration gets clear error message. PACKER_CLS = packstream_v1.Packer UNPACKER_CLS = packstream_v1.Unpacker HYDRATION_HANDLER_CLS = hydration_v1.HydrationHandler MAGIC_PREAMBLE = b"\x60\x60\xB0\x17" PROTOCOL_VERSION = None # flag if connection needs RESET to go back to READY state is_reset = False # The socket in_use = False # When the connection was last put back into the pool idle_since = float("-inf") # The socket _closing = False _closed = False # The socket _defunct = False #: The pool of which this connection is a member pool = None # Store the id of the most recent ran query to be able to reduce sent bits by # using the default (-1) to refer to the most recent query when pulling # results for it. most_recent_qid = None def __init__(self, unresolved_address, sock, max_connection_lifetime, *, auth=None, user_agent=None, routing_context=None): self.unresolved_address = unresolved_address self.socket = sock self.local_port = self.socket.getsockname()[1] self.server_info = ServerInfo(Address(sock.getpeername()), self.PROTOCOL_VERSION) # so far `connection.recv_timeout_seconds` is the only available # configuration hint that exists. Therefore, all hints can be stored at # connection level. This might change in the future. self.configuration_hints = {} self.patch = {} self.outbox = AsyncOutbox( self.socket, on_error=self._set_defunct_write, packer_cls=self.PACKER_CLS ) self.inbox = AsyncInbox( self.socket, on_error=self._set_defunct_read, unpacker_cls=self.UNPACKER_CLS ) self.hydration_handler = self.HYDRATION_HANDLER_CLS() self.responses = deque() self._max_connection_lifetime = max_connection_lifetime self._creation_timestamp = perf_counter() self.routing_context = routing_context self.idle_since = perf_counter() # Determine the user agent if user_agent: self.user_agent = user_agent else: self.user_agent = get_user_agent() # Determine auth details if not auth: self.auth_dict = {} elif isinstance(auth, tuple) and 2 <= len(auth) <= 3: from neo4j import Auth self.auth_dict = vars(Auth("basic", *auth)) else: try: self.auth_dict = vars(auth) except (KeyError, TypeError): raise AuthError("Cannot determine auth details from %r" % auth) # Check for missing password try: credentials = self.auth_dict["credentials"] except KeyError: pass else: if credentials is None: raise AuthError("Password cannot be None") def __del__(self): if not asyncio.iscoroutinefunction(self.close): self.close() @property @abc.abstractmethod def supports_multiple_results(self): """ Boolean flag to indicate if the connection version supports multiple queries to be buffered on the server side (True) or if all results need to be eagerly pulled before sending the next RUN (False). """ pass @property @abc.abstractmethod def supports_multiple_databases(self): """ Boolean flag to indicate if the connection version supports multiple databases. """ pass @classmethod def protocol_handlers(cls, protocol_version=None): """ Return a dictionary of available Bolt protocol handlers, keyed by version tuple. If an explicit protocol version is provided, the dictionary will contain either zero or one items, depending on whether that version is supported. If no protocol version is provided, all available versions will be returned. :param protocol_version: tuple identifying a specific protocol version (e.g. (3, 5)) or None :return: dictionary of version tuple to handler class for all relevant and supported protocol versions :raise TypeError: if protocol version is not passed in a tuple """ # Carry out Bolt subclass imports locally to avoid circular dependency issues. from ._bolt3 import AsyncBolt3 from ._bolt4 import ( AsyncBolt4x1, AsyncBolt4x2, AsyncBolt4x3, AsyncBolt4x4, ) from ._bolt5 import AsyncBolt5x0 handlers = { AsyncBolt3.PROTOCOL_VERSION: AsyncBolt3, # 4.0 unsupported because no space left in the handshake AsyncBolt4x1.PROTOCOL_VERSION: AsyncBolt4x1, AsyncBolt4x2.PROTOCOL_VERSION: AsyncBolt4x2, AsyncBolt4x3.PROTOCOL_VERSION: AsyncBolt4x3, AsyncBolt4x4.PROTOCOL_VERSION: AsyncBolt4x4, AsyncBolt5x0.PROTOCOL_VERSION: AsyncBolt5x0, } if protocol_version is None: return handlers if not isinstance(protocol_version, tuple): raise TypeError("Protocol version must be specified as a tuple") if protocol_version in handlers: return {protocol_version: handlers[protocol_version]} return {} @classmethod def version_list(cls, versions, limit=4): """ Return a list of supported protocol versions in order of preference. The number of protocol versions (or ranges) returned is limited to four. """ # In fact, 4.3 is the fist version to support ranges. However, the # range support got backported to 4.2. But even if the server is too # old to have the backport, negotiating BOLT 4.1 is no problem as it's # equivalent to 4.2 first_with_range_support = Version(4, 2) result = [] for version in versions: if (result and version >= first_with_range_support and result[-1][0] == version[0] and result[-1][1][1] == version[1] + 1): # can use range to encompass this version result[-1][1][1] = version[1] continue result.append(Version(version[0], [version[1], version[1]])) if len(result) == 4: break return result @classmethod def get_handshake(cls): """ Return the supported Bolt versions as bytes. The length is 16 bytes as specified in the Bolt version negotiation. :return: bytes """ supported_versions = sorted(cls.protocol_handlers().keys(), reverse=True) offered_versions = cls.version_list(supported_versions) return b"".join(version.to_bytes() for version in offered_versions).ljust(16, b"\x00") @classmethod async def ping(cls, address, *, timeout=None, **config): """ Attempt to establish a Bolt connection, returning the agreed Bolt protocol version if successful. """ config = PoolConfig.consume(config) try: s, protocol_version, handshake, data = \ await AsyncBoltSocket.connect( address, timeout=timeout, custom_resolver=config.resolver, ssl_context=config.get_ssl_context(), keep_alive=config.keep_alive, ) except (ServiceUnavailable, SessionExpired, BoltHandshakeError): return None else: await AsyncBoltSocket.close_socket(s) return protocol_version @classmethod async def open( cls, address, *, auth=None, timeout=None, routing_context=None, **pool_config ): """Open a new Bolt connection to a given server address. :param address: :param auth: :param timeout: the connection timeout in seconds :param routing_context: dict containing routing context :param pool_config: :return: connected AsyncBolt instance :raise BoltHandshakeError: raised if the Bolt Protocol can not negotiate a protocol version. :raise ServiceUnavailable: raised if there was a connection issue. """ def time_remaining(): if timeout is None: return None t = timeout - (perf_counter() - t0) return t if t > 0 else 0 t0 = perf_counter() pool_config = PoolConfig.consume(pool_config) socket_connection_timeout = pool_config.connection_timeout if socket_connection_timeout is None: socket_connection_timeout = time_remaining() elif timeout is not None: socket_connection_timeout = min(pool_config.connection_timeout, time_remaining()) s, pool_config.protocol_version, handshake, data = \ await AsyncBoltSocket.connect( address, timeout=socket_connection_timeout, custom_resolver=pool_config.resolver, ssl_context=pool_config.get_ssl_context(), keep_alive=pool_config.keep_alive, ) # Carry out Bolt subclass imports locally to avoid circular dependency # issues. if pool_config.protocol_version == (3, 0): from ._bolt3 import AsyncBolt3 bolt_cls = AsyncBolt3 # Implementation for 4.0 exists, but there was no space left in the # handshake to offer this version to the server. Hence, the server # should never request us to speak bolt 4.0. # elif pool_config.protocol_version == (4, 0): # from ._bolt4 import AsyncBolt4x0 # bolt_cls = AsyncBolt4x0 elif pool_config.protocol_version == (4, 1): from ._bolt4 import AsyncBolt4x1 bolt_cls = AsyncBolt4x1 elif pool_config.protocol_version == (4, 2): from ._bolt4 import AsyncBolt4x2 bolt_cls = AsyncBolt4x2 elif pool_config.protocol_version == (4, 3): from ._bolt4 import AsyncBolt4x3 bolt_cls = AsyncBolt4x3 elif pool_config.protocol_version == (4, 4): from ._bolt4 import AsyncBolt4x4 bolt_cls = AsyncBolt4x4 elif pool_config.protocol_version == (5, 0): from ._bolt5 import AsyncBolt5x0 bolt_cls = AsyncBolt5x0 else: log.debug("[#%04X] S: <CLOSE>", s.getsockname()[1]) AsyncBoltSocket.close_socket(s) supported_versions = cls.protocol_handlers().keys() raise BoltHandshakeError( "The Neo4J server does not support communication with this " "driver. This driver has support for Bolt protocols " "{}".format(tuple(map(str, supported_versions))), address=address, request_data=handshake, response_data=data ) connection = bolt_cls( address, s, pool_config.max_connection_lifetime, auth=auth, user_agent=pool_config.user_agent, routing_context=routing_context ) try: connection.socket.set_deadline(time_remaining()) try: await connection.hello() finally: connection.socket.set_deadline(None) except Exception: await connection.close_non_blocking() raise return connection @property @abc.abstractmethod def encrypted(self): pass @property @abc.abstractmethod def der_encoded_server_certificate(self): pass @abc.abstractmethod async def hello(self, dehydration_hooks=None, hydration_hooks=None): """ Appends a HELLO message to the outgoing queue, sends it and consumes all remaining messages. """ pass @abc.abstractmethod async def route( self, database=None, imp_user=None, bookmarks=None, dehydration_hooks=None, hydration_hooks=None ): """ Fetch a routing table from the server for the given `database`. For Bolt 4.3 and above, this appends a ROUTE message; for earlier versions, a procedure call is made via the regular Cypher execution mechanism. In all cases, this is sent to the network, and a response is fetched. :param database: database for which to fetch a routing table Requires Bolt 4.0+. :param imp_user: the user to impersonate Requires Bolt 4.4+. :param bookmarks: iterable of bookmark values after which this transaction should begin :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything. """ pass @abc.abstractmethod def run(self, query, parameters=None, mode=None, bookmarks=None, metadata=None, timeout=None, db=None, imp_user=None, dehydration_hooks=None, hydration_hooks=None, **handlers): """ Appends a RUN message to the output queue. :param query: Cypher query string :param parameters: dictionary of Cypher parameters :param mode: access mode for routing - "READ" or "WRITE" (default) :param bookmarks: iterable of bookmark values after which this transaction should begin :param metadata: custom metadata dictionary to attach to the transaction :param timeout: timeout for transaction execution (seconds) :param db: name of the database against which to begin the transaction Requires Bolt 4.0+. :param imp_user: the user to impersonate Requires Bolt 4.4+. :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything. :param handlers: handler functions passed into the returned Response object """ pass @abc.abstractmethod def discard(self, n=-1, qid=-1, dehydration_hooks=None, hydration_hooks=None, **handlers): """ Appends a DISCARD message to the output queue. :param n: number of records to discard, default = -1 (ALL) :param qid: query ID to discard for, default = -1 (last query) :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything. :param handlers: handler functions passed into the returned Response object """ pass @abc.abstractmethod def pull(self, n=-1, qid=-1, dehydration_hooks=None, hydration_hooks=None, **handlers): """ Appends a PULL message to the output queue. :param n: number of records to pull, default = -1 (ALL) :param qid: query ID to pull for, default = -1 (last query) :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything. :param handlers: handler functions passed into the returned Response object """ pass @abc.abstractmethod def begin(self, mode=None, bookmarks=None, metadata=None, timeout=None, db=None, imp_user=None, dehydration_hooks=None, hydration_hooks=None, **handlers): """ Appends a BEGIN message to the output queue. :param mode: access mode for routing - "READ" or "WRITE" (default) :param bookmarks: iterable of bookmark values after which this transaction should begin :param metadata: custom metadata dictionary to attach to the transaction :param timeout: timeout for transaction execution (seconds) :param db: name of the database against which to begin the transaction Requires Bolt 4.0+. :param imp_user: the user to impersonate Requires Bolt 4.4+ :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything. :param handlers: handler functions passed into the returned Response object :return: Response object """ pass @abc.abstractmethod def commit(self, dehydration_hooks=None, hydration_hooks=None, **handlers): """ Appends a COMMIT message to the output queue. :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything. """ pass @abc.abstractmethod def rollback(self, dehydration_hooks=None, hydration_hooks=None, **handlers): """ Appends a ROLLBACK message to the output queue. :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything.""" pass @abc.abstractmethod async def reset(self, dehydration_hooks=None, hydration_hooks=None): """ Appends a RESET message to the outgoing queue, sends it and consumes all remaining messages. :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything. """ pass @abc.abstractmethod def goodbye(self, dehydration_hooks=None, hydration_hooks=None): """Append a GOODBYE message to the outgoing queue. :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. :param hydration_hooks: Hooks to hydrate types (mapping from type (class) to dehydration function). Dehydration functions receive the value of type understood by packstream and are free to return anything. """ pass def new_hydration_scope(self): return self.hydration_handler.new_hydration_scope() def _append(self, signature, fields=(), response=None, dehydration_hooks=None): """ Appends a message to the outgoing queue. :param signature: the signature of the message :param fields: the fields of the message as a tuple :param response: a response object to handle callbacks :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value and returns an object of type understood by packstream. """ self.outbox.append_message(signature, fields, dehydration_hooks) self.responses.append(response) async def _send_all(self): if await self.outbox.flush(): self.idle_since = perf_counter() async def send_all(self): """ Send all queued messages to the server. """ if self.closed(): raise ServiceUnavailable( "Failed to write to closed connection {!r} ({!r})".format( self.unresolved_address, self.server_info.address ) ) if self.defunct(): raise ServiceUnavailable( "Failed to write to defunct connection {!r} ({!r})".format( self.unresolved_address, self.server_info.address ) ) await self._send_all() @abc.abstractmethod async def _process_message(self, tag, fields): """ Receive at most one message from the server, if available. :return: 2-tuple of number of detail messages and number of summary messages fetched """ pass async def fetch_message(self): if self._closed: raise ServiceUnavailable( "Failed to read from closed connection {!r} ({!r})".format( self.unresolved_address, self.server_info.address ) ) if self._defunct: raise ServiceUnavailable( "Failed to read from defunct connection {!r} ({!r})".format( self.unresolved_address, self.server_info.address ) ) if not self.responses: return 0, 0 # Receive exactly one message tag, fields = await self.inbox.pop( hydration_hooks=self.responses[0].hydration_hooks ) res = await self._process_message(tag, fields) self.idle_since = perf_counter() return res async def fetch_all(self): """ Fetch all outstanding messages. :return: 2-tuple of number of detail messages and number of summary messages fetched """ detail_count = summary_count = 0 while self.responses: response = self.responses[0] while not response.complete: detail_delta, summary_delta = await self.fetch_message() detail_count += detail_delta summary_count += summary_delta return detail_count, summary_count async def _set_defunct_read(self, error=None, silent=False): message = "Failed to read from defunct connection {!r} ({!r})".format( self.unresolved_address, self.server_info.address ) await self._set_defunct(message, error=error, silent=silent) async def _set_defunct_write(self, error=None, silent=False): message = "Failed to write data to connection {!r} ({!r})".format( self.unresolved_address, self.server_info.address ) await self._set_defunct(message, error=error, silent=silent) async def _set_defunct(self, message, error=None, silent=False): from ._pool import AsyncBoltPool direct_driver = isinstance(self.pool, AsyncBoltPool) if error: log.debug("[#%04X] %r", self.socket.getsockname()[1], error) log.error(message) # We were attempting to receive data but the connection # has unexpectedly terminated. So, we need to close the # connection from the client side, and remove the address # from the connection pool. self._defunct = True if not self._closing: # If we fail while closing the connection, there is no need to # remove the connection from the pool, nor to try to close the # connection again. await self.close() if self.pool: await self.pool.deactivate(address=self.unresolved_address) # Iterate through the outstanding responses, and if any correspond # to COMMIT requests then raise an error to signal that we are # unable to confirm that the COMMIT completed successfully. if silent: return for response in self.responses: if isinstance(response, CommitResponse): if error: raise IncompleteCommit(message) from error else: raise IncompleteCommit(message) if direct_driver: if error: raise ServiceUnavailable(message) from error else: raise ServiceUnavailable(message) else: if error: raise SessionExpired(message) from error else: raise SessionExpired(message) def stale(self): return (self._stale or (0 <= self._max_connection_lifetime <= perf_counter() - self._creation_timestamp)) _stale = False def set_stale(self): self._stale = True async def close(self): """Close the connection.""" if self._closed or self._closing: return self._closing = True if not self._defunct: self.goodbye() try: await self._send_all() except (OSError, BoltError, DriverError): pass log.debug("[#%04X] C: <CLOSE>", self.local_port) try: await self.socket.close() except OSError: pass finally: self._closed = True async def close_non_blocking(self): """Set the socket to non-blocking and close it. This will try to send the `GOODBYE` message (given the socket is not marked as defunct). However, should the write operation require blocking (e.g., a full network buffer), then the socket will be closed immediately (without `GOODBYE` message). """ if self._closed or self._closing: return self.socket.settimeout(0) await self.close() def closed(self): return self._closed def defunct(self): return self._defunct def is_idle_for(self, timeout): """Check if connection has been idle for at least the given timeout. :param timeout: timeout in seconds :type timeout: float :rtype: bool """ return perf_counter() - self.idle_since > timeout AsyncBoltSocket.Bolt = AsyncBolt
neo4j/_async/io/_bolt.py
codereval_python_data_165
Create a Bookmarks object from a list of raw bookmark string values. You should not need to use this method unless you want to deserialize bookmarks. :param values: ASCII string values (raw bookmarks) :type values: Iterable[str] @classmethod def from_raw_values(cls, values): """Create a Bookmarks object from a list of raw bookmark string values. You should not need to use this method unless you want to deserialize bookmarks. :param values: ASCII string values (raw bookmarks) :type values: Iterable[str] """ obj = cls() bookmarks = [] for value in values: if not isinstance(value, str): raise TypeError("Raw bookmark values must be str. " "Found {}".format(type(value))) try: value.encode("ascii") except UnicodeEncodeError as e: raise ValueError(f"The value {value} is not ASCII") from e bookmarks.append(value) obj._raw_values = frozenset(bookmarks) return obj # Copyright (c) "Neo4j" # Neo4j Sweden AB [https://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Base classes and helpers. """ from urllib.parse import ( parse_qs, urlparse, ) from ._meta import deprecated from .exceptions import ConfigurationError READ_ACCESS = "READ" WRITE_ACCESS = "WRITE" DRIVER_BOLT = "DRIVER_BOLT" DRIVER_NEO4j = "DRIVER_NEO4J" SECURITY_TYPE_NOT_SECURE = "SECURITY_TYPE_NOT_SECURE" SECURITY_TYPE_SELF_SIGNED_CERTIFICATE = "SECURITY_TYPE_SELF_SIGNED_CERTIFICATE" SECURITY_TYPE_SECURE = "SECURITY_TYPE_SECURE" URI_SCHEME_BOLT = "bolt" URI_SCHEME_BOLT_SELF_SIGNED_CERTIFICATE = "bolt+ssc" URI_SCHEME_BOLT_SECURE = "bolt+s" URI_SCHEME_NEO4J = "neo4j" URI_SCHEME_NEO4J_SELF_SIGNED_CERTIFICATE = "neo4j+ssc" URI_SCHEME_NEO4J_SECURE = "neo4j+s" URI_SCHEME_BOLT_ROUTING = "bolt+routing" # TODO: 6.0 - remove TRUST constants TRUST_SYSTEM_CA_SIGNED_CERTIFICATES = "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES" # Default TRUST_ALL_CERTIFICATES = "TRUST_ALL_CERTIFICATES" SYSTEM_DATABASE = "system" DEFAULT_DATABASE = None # Must be a non string hashable value # TODO: This class is not tested class Auth: """Container for auth details. :param scheme: specifies the type of authentication, examples: "basic", "kerberos" :type scheme: str :param principal: specifies who is being authenticated :type principal: str or None :param credentials: authenticates the principal :type credentials: str or None :param realm: specifies the authentication provider :type realm: str or None :param parameters: extra key word parameters passed along to the authentication provider :type parameters: Dict[str, Any] """ def __init__(self, scheme, principal, credentials, realm=None, **parameters): self.scheme = scheme # Neo4j servers pre 4.4 require the principal field to always be # present. Therefore, we transmit it even if it's an empty sting. if principal is not None: self.principal = principal if credentials: self.credentials = credentials if realm: self.realm = realm if parameters: self.parameters = parameters # For backwards compatibility AuthToken = Auth def basic_auth(user, password, realm=None): """Generate a basic auth token for a given user and password. This will set the scheme to "basic" for the auth token. :param user: user name, this will set the :type user: str :param password: current password, this will set the credentials :type password: str :param realm: specifies the authentication provider :type realm: str or None :return: auth token for use with :meth:`GraphDatabase.driver` or :meth:`AsyncGraphDatabase.driver` :rtype: :class:`neo4j.Auth` """ return Auth("basic", user, password, realm) def kerberos_auth(base64_encoded_ticket): """Generate a kerberos auth token with the base64 encoded ticket. This will set the scheme to "kerberos" for the auth token. :param base64_encoded_ticket: a base64 encoded service ticket, this will set the credentials :type base64_encoded_ticket: str :return: auth token for use with :meth:`GraphDatabase.driver` or :meth:`AsyncGraphDatabase.driver` :rtype: :class:`neo4j.Auth` """ return Auth("kerberos", "", base64_encoded_ticket) def bearer_auth(base64_encoded_token): """Generate an auth token for Single-Sign-On providers. This will set the scheme to "bearer" for the auth token. :param base64_encoded_token: a base64 encoded authentication token generated by a Single-Sign-On provider. :type base64_encoded_token: str :return: auth token for use with :meth:`GraphDatabase.driver` or :meth:`AsyncGraphDatabase.driver` :rtype: :class:`neo4j.Auth` """ return Auth("bearer", None, base64_encoded_token) def custom_auth(principal, credentials, realm, scheme, **parameters): """Generate a custom auth token. :param principal: specifies who is being authenticated :type principal: str or None :param credentials: authenticates the principal :type credentials: str or None :param realm: specifies the authentication provider :type realm: str or None :param scheme: specifies the type of authentication :type scheme: str or None :param parameters: extra key word parameters passed along to the authentication provider :type parameters: Dict[str, Any] :return: auth token for use with :meth:`GraphDatabase.driver` or :meth:`AsyncGraphDatabase.driver` :rtype: :class:`neo4j.Auth` """ return Auth(scheme, principal, credentials, realm, **parameters) # TODO 6.0 - remove this class class Bookmark: """A Bookmark object contains an immutable list of bookmark string values. .. deprecated:: 5.0 `Bookmark` will be removed in version 6.0. Use :class:`Bookmarks` instead. :param values: ASCII string values """ @deprecated("Use the `Bookmarks`` class instead.") def __init__(self, *values): if values: bookmarks = [] for ix in values: try: if ix: ix.encode("ascii") bookmarks.append(ix) except UnicodeEncodeError as e: raise ValueError("The value {} is not ASCII".format(ix)) self._values = frozenset(bookmarks) else: self._values = frozenset() def __repr__(self): """ :return: repr string with sorted values """ return "<Bookmark values={{{}}}>".format(", ".join(["'{}'".format(ix) for ix in sorted(self._values)])) def __bool__(self): return bool(self._values) @property def values(self): """ :return: immutable list of bookmark string values :rtype: frozenset """ return self._values class Bookmarks: """Container for an immutable set of bookmark string values. Bookmarks are used to causally chain session. See :meth:`Session.last_bookmarks` or :meth:`AsyncSession.last_bookmarks` for more information. Use addition to combine multiple Bookmarks objects:: bookmarks3 = bookmarks1 + bookmarks2 """ def __init__(self): self._raw_values = frozenset() def __repr__(self): """ :return: repr string with sorted values """ return "<Bookmarks values={{{}}}>".format( ", ".join(map(repr, sorted(self._raw_values))) ) def __bool__(self): return bool(self._raw_values) def __add__(self, other): if isinstance(other, Bookmarks): if not other: return self ret = self.__class__() ret._raw_values = self._raw_values | other._raw_values return ret return NotImplemented @property def raw_values(self): """The raw bookmark values. You should not need to access them unless you want to serialize bookmarks. :return: immutable list of bookmark string values :rtype: frozenset[str] """ return self._raw_values @classmethod def from_raw_values(cls, values): """Create a Bookmarks object from a list of raw bookmark string values. You should not need to use this method unless you want to deserialize bookmarks. :param values: ASCII string values (raw bookmarks) :type values: Iterable[str] """ obj = cls() bookmarks = [] for value in values: if not isinstance(value, str): raise TypeError("Raw bookmark values must be str. " "Found {}".format(type(value))) try: value.encode("ascii") except UnicodeEncodeError as e: raise ValueError(f"The value {value} is not ASCII") from e bookmarks.append(value) obj._raw_values = frozenset(bookmarks) return obj class ServerInfo: """ Represents a package of information relating to a Neo4j server. """ def __init__(self, address, protocol_version): self._address = address self._protocol_version = protocol_version self._metadata = {} @property def address(self): """ Network address of the remote server. """ return self._address @property def protocol_version(self): """ Bolt protocol version with which the remote server communicates. This is returned as a :class:`.Version` object, which itself extends a simple 2-tuple of (major, minor) integers. """ return self._protocol_version @property def agent(self): """ Server agent string by which the remote server identifies itself. """ return self._metadata.get("server") @property @deprecated("The connection id is considered internal information " "and will no longer be exposed in future versions.") def connection_id(self): """ Unique identifier for the remote server connection. """ return self._metadata.get("connection_id") def update(self, metadata): """ Update server information with extra metadata. This is typically drawn from the metadata received after successful connection initialisation. """ self._metadata.update(metadata) class Version(tuple): def __new__(cls, *v): return super().__new__(cls, v) def __repr__(self): return "{}{}".format(self.__class__.__name__, super().__repr__()) def __str__(self): return ".".join(map(str, self)) def to_bytes(self): b = bytearray(4) for i, v in enumerate(self): if not 0 <= i < 2: raise ValueError("Too many version components") if isinstance(v, list): b[-i - 1] = int(v[0] % 0x100) b[-i - 2] = int((v[0] - v[-1]) % 0x100) else: b[-i - 1] = int(v % 0x100) return bytes(b) @classmethod def from_bytes(cls, b): b = bytearray(b) if len(b) != 4: raise ValueError("Byte representation must be exactly four bytes") if b[0] != 0 or b[1] != 0: raise ValueError("First two bytes must contain zero") return Version(b[-1], b[-2]) def parse_neo4j_uri(uri): parsed = urlparse(uri) if parsed.username: raise ConfigurationError("Username is not supported in the URI") if parsed.password: raise ConfigurationError("Password is not supported in the URI") if parsed.scheme == URI_SCHEME_BOLT_ROUTING: raise ConfigurationError("Uri scheme {!r} have been renamed. Use {!r}".format(parsed.scheme, URI_SCHEME_NEO4J)) elif parsed.scheme == URI_SCHEME_BOLT: driver_type = DRIVER_BOLT security_type = SECURITY_TYPE_NOT_SECURE elif parsed.scheme == URI_SCHEME_BOLT_SELF_SIGNED_CERTIFICATE: driver_type = DRIVER_BOLT security_type = SECURITY_TYPE_SELF_SIGNED_CERTIFICATE elif parsed.scheme == URI_SCHEME_BOLT_SECURE: driver_type = DRIVER_BOLT security_type = SECURITY_TYPE_SECURE elif parsed.scheme == URI_SCHEME_NEO4J: driver_type = DRIVER_NEO4j security_type = SECURITY_TYPE_NOT_SECURE elif parsed.scheme == URI_SCHEME_NEO4J_SELF_SIGNED_CERTIFICATE: driver_type = DRIVER_NEO4j security_type = SECURITY_TYPE_SELF_SIGNED_CERTIFICATE elif parsed.scheme == URI_SCHEME_NEO4J_SECURE: driver_type = DRIVER_NEO4j security_type = SECURITY_TYPE_SECURE else: raise ConfigurationError("URI scheme {!r} is not supported. Supported URI schemes are {}. Examples: bolt://host[:port] or neo4j://host[:port][?routing_context]".format( parsed.scheme, [ URI_SCHEME_BOLT, URI_SCHEME_BOLT_SELF_SIGNED_CERTIFICATE, URI_SCHEME_BOLT_SECURE, URI_SCHEME_NEO4J, URI_SCHEME_NEO4J_SELF_SIGNED_CERTIFICATE, URI_SCHEME_NEO4J_SECURE ] )) return driver_type, security_type, parsed def check_access_mode(access_mode): if access_mode is None: return WRITE_ACCESS if access_mode not in (READ_ACCESS, WRITE_ACCESS): msg = "Unsupported access mode {}".format(access_mode) raise ConfigurationError(msg) return access_mode def parse_routing_context(query): """ Parse the query portion of a URI to generate a routing context dictionary. """ if not query: return {} context = {} parameters = parse_qs(query, True) for key in parameters: value_list = parameters[key] if len(value_list) != 1: raise ConfigurationError("Duplicated query parameters with key '%s', value '%s' found in query string '%s'" % (key, value_list, query)) value = value_list[0] if not value: raise ConfigurationError("Invalid parameters:'%s=%s' in query string '%s'." % (key, value, query)) context[key] = value return context
neo4j/api.py
codereval_python_data_166
Return a (sequence, type) pair. Sequence is derived from *seq* (or is *seq*, if that is of a sequence type). def _get_seq_with_type(seq, bufsize=None): """Return a (sequence, type) pair. Sequence is derived from *seq* (or is *seq*, if that is of a sequence type). """ seq_type = "" if isinstance(seq, source.Source): seq_type = "source" elif isinstance(seq, fill_compute_seq.FillComputeSeq): seq_type = "fill_compute" elif isinstance(seq, fill_request_seq.FillRequestSeq): seq_type = "fill_request" elif isinstance(seq, sequence.Sequence): seq_type = "sequence" if seq_type: # append later pass ## If no explicit type is given, check seq's methods elif ct.is_fill_compute_seq(seq): seq_type = "fill_compute" if not ct.is_fill_compute_el(seq): seq = fill_compute_seq.FillComputeSeq(*seq) elif ct.is_fill_request_seq(seq): seq_type = "fill_request" if not ct.is_fill_request_el(seq): seq = fill_request_seq.FillRequestSeq( *seq, bufsize=bufsize, # if we have a FillRequest element inside, # it decides itself when to reset. reset=False, # todo: change the interface, because # no difference with buffer_output: we fill # without a buffer buffer_input=True ) # Source is not checked, # because it must be Source explicitly. else: try: if isinstance(seq, tuple): seq = sequence.Sequence(*seq) else: seq = sequence.Sequence(seq) except exceptions.LenaTypeError: raise exceptions.LenaTypeError( "unknown argument type. Must be a " "FillComputeSeq, FillRequestSeq or Source, " "{} provided".format(seq) ) else: seq_type = "sequence" return (seq, seq_type) """Split data flow and run analysis in parallel.""" import copy import itertools from . import fill_compute_seq from . import check_sequence_type as ct from . import fill_request_seq from . import sequence from . import exceptions from . import source from . import meta def _get_seq_with_type(seq, bufsize=None): """Return a (sequence, type) pair. Sequence is derived from *seq* (or is *seq*, if that is of a sequence type). """ seq_type = "" if isinstance(seq, source.Source): seq_type = "source" elif isinstance(seq, fill_compute_seq.FillComputeSeq): seq_type = "fill_compute" elif isinstance(seq, fill_request_seq.FillRequestSeq): seq_type = "fill_request" elif isinstance(seq, sequence.Sequence): seq_type = "sequence" if seq_type: # append later pass ## If no explicit type is given, check seq's methods elif ct.is_fill_compute_seq(seq): seq_type = "fill_compute" if not ct.is_fill_compute_el(seq): seq = fill_compute_seq.FillComputeSeq(*seq) elif ct.is_fill_request_seq(seq): seq_type = "fill_request" if not ct.is_fill_request_el(seq): seq = fill_request_seq.FillRequestSeq( *seq, bufsize=bufsize, # if we have a FillRequest element inside, # it decides itself when to reset. reset=False, # todo: change the interface, because # no difference with buffer_output: we fill # without a buffer buffer_input=True ) # Source is not checked, # because it must be Source explicitly. else: try: if isinstance(seq, tuple): seq = sequence.Sequence(*seq) else: seq = sequence.Sequence(seq) except exceptions.LenaTypeError: raise exceptions.LenaTypeError( "unknown argument type. Must be a " "FillComputeSeq, FillRequestSeq or Source, " "{} provided".format(seq) ) else: seq_type = "sequence" return (seq, seq_type) class Split(object): """Split data flow and run analysis in parallel.""" def __init__(self, seqs, bufsize=1000, copy_buf=True): """*seqs* must be a list of Sequence, Source, FillComputeSeq or FillRequestSeq sequences. If *seqs* is empty, *Split* acts as an empty *Sequence* and yields all values it receives. *bufsize* is the size of the buffer for the input flow. If *bufsize* is ``None``, whole input flow is materialized in the buffer. *bufsize* must be a natural number or ``None``. *copy_buf* sets whether the buffer should be copied during :meth:`run`. This is important if different sequences can change input data and thus interfere with each other. Common type: If each sequence from *seqs* has a common type, *Split* creates methods corresponding to this type. For example, if each sequence is *FillCompute*, *Split* creates methods *fill* and *compute* and can be used as a *FillCompute* sequence. *fill* fills all its subsequences (with copies if *copy_buf* is True), and *compute* yields values from all sequences in turn (as would also do *request* or *Source.__call__*). In case of wrong initialization arguments, :exc:`.LenaTypeError` or :exc:`.LenaValueError` is raised. """ # todo: copy_buf must be always True. Isn't that? if not isinstance(seqs, list): raise exceptions.LenaTypeError( "seqs must be a list of sequences, " "{} provided".format(seqs) ) seqs = [meta.alter_sequence(seq) for seq in seqs] self._sequences = [] self._seq_types = [] for sequence in seqs: try: seq, seq_type = _get_seq_with_type(sequence, bufsize) except exceptions.LenaTypeError: raise exceptions.LenaTypeError( "unknown argument type. Must be one of " "FillComputeSeq, FillRequestSeq or Source, " "{} provided".format(sequence) ) self._sequences.append(seq) self._seq_types.append(seq_type) different_seq_types = set(self._seq_types) self._n_seq_types = len(different_seq_types) if self._n_seq_types == 1: seq_type = different_seq_types.pop() # todo: probably remove run to avoid duplication? if seq_type == "fill_compute": self.fill = self._fill self.compute = self._compute elif seq_type == "fill_request": self.fill = self._fill self.request = self._request elif seq_type == "source": pass elif self._n_seq_types == 0: self.run = self._empty_run self._copy_buf = bool(copy_buf) if bufsize is not None: if bufsize != int(bufsize) or bufsize < 1: raise exceptions.LenaValueError( "bufsize should be a natural number " "or None, {} provided".format(bufsize) ) self._bufsize = bufsize def __call__(self): """Each initialization sequence generates flow. After its flow is empty, next sequence is called, etc. This method is available only if each self sequence is a :class:`.Source`, otherwise runtime :exc:`.LenaAttributeError` is raised. """ if self._n_seq_types != 1 or not ct.is_source(self._sequences[0]): raise exceptions.LenaAttributeError( "Split has no method '__call__'. It should contain " "only Source sequences to be callable" ) # todo: use itertools.chain and check performance difference for seq in self._sequences: for result in seq(): yield result def _fill(self, val): for seq in self._sequences[:-1]: if self._copy_buf: seq.fill(copy.deepcopy(val)) else: seq.fill(val) self._sequences[-1].fill(val) def _compute(self): for seq in self._sequences: for val in seq.compute(): yield val def _request(self): for seq in self._sequences: for val in seq.request(): yield val def _empty_run(self, flow): """If self sequence is empty, yield all flow unchanged.""" for val in flow: yield val def run(self, flow): """Iterate input *flow* and yield results. The *flow* is divided into subslices of *bufsize*. Each subslice is processed by sequences in the order of their initializer list. If a sequence is a *Source*, it doesn't accept the incoming *flow*, but produces its own complete flow and becomes inactive (is not called any more). A *FillRequestSeq* is filled with the buffer contents. After the buffer is finished, it yields all values from *request()*. A *FillComputeSeq* is filled with values from each buffer, but yields values from *compute* only after the whole *flow* is finished. A *Sequence* is called with *run(buffer)* instead of the whole flow. The results are yielded for each buffer (and also if the *flow* was empty). If the whole flow must be analysed at once, don't use such a sequence in *Split*. If the *flow* was empty, each *call*, *compute*, *request* or *run* is called nevertheless. If *copy_buf* is True, then the buffer for each sequence except the last one is a deep copy of the current buffer. """ active_seqs = self._sequences[:] active_seq_types = self._seq_types[:] n_of_active_seqs = len(active_seqs) ind = 0 flow = iter(flow) flow_was_empty = True while True: ## iterate on flow # If stop is None, then iteration continues # until the iterator is exhausted, if at all # https://docs.python.org/3/library/itertools.html#itertools.islice orig_buf = list(itertools.islice(flow, self._bufsize)) if orig_buf: flow_was_empty = False else: break # iterate on active sequences ind = 0 while ind < n_of_active_seqs: if self._copy_buf and n_of_active_seqs - ind > 1: # last sequence doesn't need a copy of the buffer buf = copy.deepcopy(orig_buf) else: buf = orig_buf seq = active_seqs[ind] seq_type = active_seq_types[ind] if seq_type == "source": for val in seq(): yield val del active_seqs[ind] del active_seq_types[ind] n_of_active_seqs -= 1 continue elif seq_type == "fill_compute": stopped = False for val in buf: try: seq.fill(val) except exceptions.LenaStopFill: stopped = True break if stopped: for result in seq.compute(): yield result # we don't have goto in Python, # so we have to repeat this # each time we break double cycle. del active_seqs[ind] del active_seq_types[ind] n_of_active_seqs -= 1 continue elif seq_type == "fill_request": stopped = False for val in buf: try: seq.fill(val) except exceptions.LenaStopFill: stopped = True break # FillRequest yields each time after buffer is filled for result in seq.request(): yield result if stopped: del active_seqs[ind] del active_seq_types[ind] n_of_active_seqs -= 1 continue elif seq_type == "sequence": # run buf as a whole flow. # this may be very wrong if seq has internal state, # e.g. contains a Cache for res in seq.run(buf): yield res # this is not needed, because can't be tested. # else: # raise exceptions.LenaRuntimeError( # "unknown sequence type {}".format(seq_type) # ) ind += 1 # end internal while on sequences # end while on flow # yield computed data for seq, seq_type in zip(active_seqs, active_seq_types): if seq_type == "source": # otherwise it is a logic error assert flow_was_empty for val in seq(): yield val elif seq_type == "fill_compute": for val in seq.compute(): yield val elif seq_type == "fill_request": # otherwise FillRequest yielded after each buffer if flow_was_empty: for val in seq.request(): yield val elif seq_type == "sequence": if flow_was_empty: for val in seq.run([]): yield val
lena/core/split.py
codereval_python_data_167
Compute or set scale (integral of the histogram). If *other* is ``None``, return scale of this histogram. If its scale was not computed before, it is computed and stored for subsequent use (unless explicitly asked to *recompute*). Note that after changing (filling) the histogram one must explicitly recompute the scale if it was computed before. If a float *other* is provided, rescale self to *other*. Histograms with scale equal to zero can't be rescaled. :exc:`.LenaValueError` is raised if one tries to do that. def scale(self, other=None, recompute=False): """Compute or set scale (integral of the histogram). If *other* is ``None``, return scale of this histogram. If its scale was not computed before, it is computed and stored for subsequent use (unless explicitly asked to *recompute*). Note that after changing (filling) the histogram one must explicitly recompute the scale if it was computed before. If a float *other* is provided, rescale self to *other*. Histograms with scale equal to zero can't be rescaled. :exc:`.LenaValueError` is raised if one tries to do that. """ # see graph.scale comments why this is called simply "scale" # (not set_scale, get_scale, etc.) if other is None: # return scale if self._scale is None or recompute: self._scale = hf.integral( *hf.unify_1_md(self.bins, self.edges) ) return self._scale else: # rescale from other scale = self.scale() if scale == 0: raise lena.core.LenaValueError( "can not rescale histogram with zero scale" ) self.bins = lena.math.md_map(lambda binc: binc*float(other) / scale, self.bins) self._scale = other return None """Histogram structure *histogram* and element *Histogram*.""" import copy import lena.context import lena.core import lena.flow import lena.math from . import hist_functions as hf class histogram(): """A multidimensional histogram. Arbitrary dimension, variable bin size and weights are supported. Lower bin edge is included, upper edge is excluded. Underflow and overflow values are skipped. Bin content can be of arbitrary type, which is defined during initialization. Examples: >>> # a two-dimensional histogram >>> hist = histogram([[0, 1, 2], [0, 1, 2]]) >>> hist.fill([0, 1]) >>> hist.bins [[0, 1], [0, 0]] >>> values = [[0, 0], [1, 0], [1, 1]] >>> # fill the histogram with values >>> for v in values: ... hist.fill(v) >>> hist.bins [[1, 1], [1, 1]] """ # Note the differences from existing packages. # Numpy 1.16 (numpy.histogram): all but the last # (righthand-most) bin is half-open. # This histogram class has bin limits as in ROOT # (but without overflow and underflow). # Numpy: the first element of the range must be less than or equal to the second. # This histogram requires strictly increasing edges. # https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html # https://root.cern.ch/root/htmldoc/guides/users-guide/Histograms.html#bin-numbering def __init__(self, edges, bins=None, initial_value=0): """*edges* is a sequence of one-dimensional arrays, each containing strictly increasing bin edges. Histogram's bins by default are initialized with *initial_value*. It can be any object that supports addition with *weight* during *fill* (but that is not necessary if you don't plan to fill the histogram). If the *initial_value* is compound and requires special copying, create initial bins yourself (see :func:`.init_bins`). A histogram can be created from existing *bins* and *edges*. In this case a simple check of the shape of *bins* is done (raising :exc:`.LenaValueError` if failed). **Attributes** :attr:`edges` is a list of edges on each dimension. Edges mark the borders of the bin. Edges along each dimension are one-dimensional lists, and the multidimensional bin is the result of all intersections of one-dimensional edges. For example, a 3-dimensional histogram has edges of the form *[x_edges, y_edges, z_edges]*, and the 0th bin has borders *((x[0], x[1]), (y[0], y[1]), (z[0], z[1]))*. Index in the edges is a tuple, where a given position corresponds to a dimension, and the content at that position to the bin along that dimension. For example, index *(0, 1, 3)* corresponds to the bin with lower edges *(x[0], y[1], z[3])*. :attr:`bins` is a list of nested lists. Same index as for edges can be used to get bin content: bin at *(0, 1, 3)* can be obtained as *bins[0][1][3]*. Most nested arrays correspond to highest (further from x) coordinates. For example, for a 3-dimensional histogram bins equal to *[[[1, 1], [0, 0]], [[0, 0], [0, 0]]]* mean that the only filled bins are those where x and y indices are 0, and z index is 0 and 1. :attr:`dim` is the dimension of a histogram (length of its *edges* for a multidimensional histogram). If subarrays of *edges* are not increasing or if any of them has length less than 2, :exc:`.LenaValueError` is raised. .. admonition:: Programmer's note one- and multidimensional histograms have different *bins* and *edges* format. To be unified, 1-dimensional edges should be nested in a list (like *[[1, 2, 3]]*). Instead, they are simply the x-edges list, because it is more intuitive and one-dimensional histograms are used more often. To unify the interface for bins and edges in your code, use :func:`.unify_1_md` function. """ # todo: allow creation of *edges* from tuples # (without lena.math.mesh). Allow bin_size in this case. hf.check_edges_increasing(edges) self.edges = edges self._scale = None if hasattr(edges[0], "__iter__"): self.dim = len(edges) else: self.dim = 1 # todo: add a kwarg no_check=False to disable bins testing if bins is None: self.bins = hf.init_bins(self.edges, initial_value) else: self.bins = bins # We can't make scale for an arbitrary histogram, # because it may contain compound values. # self._scale = self.make_scale() wrong_bins_error = lena.core.LenaValueError( "bins of incorrect shape given, {}".format(bins) ) if self.dim == 1: if len(bins) != len(edges) - 1: raise wrong_bins_error else: if len(bins) != len(edges[0]) - 1: raise wrong_bins_error if self.dim > 1: self.ranges = [(axis[0], axis[-1]) for axis in edges] self.nbins = [len(axis) - 1 for axis in edges] else: self.ranges = [(edges[0], edges[-1])] self.nbins = [len(edges)-1] def __eq__(self, other): """Two histograms are equal, if and only if they have equal bins and equal edges. If *other* is not a :class:`.histogram`, return ``False``. Note that floating numbers should be compared approximately (using :func:`math.isclose`). """ if not isinstance(other, histogram): # in Python comparison between different types is allowed return False return self.bins == other.bins and self.edges == other.edges def fill(self, coord, weight=1): """Fill histogram at *coord* with the given *weight*. Coordinates outside the histogram edges are ignored. """ indices = hf.get_bin_on_value(coord, self.edges) subarr = self.bins for ind in indices[:-1]: # underflow if ind < 0: return try: subarr = subarr[ind] # overflow except IndexError: return ind = indices[-1] # underflow if ind < 0: return # fill try: subarr[ind] += weight except IndexError: return def __repr__(self): return "histogram({}, bins={})".format(self.edges, self.bins) def scale(self, other=None, recompute=False): """Compute or set scale (integral of the histogram). If *other* is ``None``, return scale of this histogram. If its scale was not computed before, it is computed and stored for subsequent use (unless explicitly asked to *recompute*). Note that after changing (filling) the histogram one must explicitly recompute the scale if it was computed before. If a float *other* is provided, rescale self to *other*. Histograms with scale equal to zero can't be rescaled. :exc:`.LenaValueError` is raised if one tries to do that. """ # see graph.scale comments why this is called simply "scale" # (not set_scale, get_scale, etc.) if other is None: # return scale if self._scale is None or recompute: self._scale = hf.integral( *hf.unify_1_md(self.bins, self.edges) ) return self._scale else: # rescale from other scale = self.scale() if scale == 0: raise lena.core.LenaValueError( "can not rescale histogram with zero scale" ) self.bins = lena.math.md_map(lambda binc: binc*float(other) / scale, self.bins) self._scale = other return None def _update_context(self, context): """Update *context* with the properties of this histogram. *context.histogram* is updated with "dim", "nbins" and "ranges" with values for this histogram. If this histogram has a computed scale, it is also added to the context. Called on "destruction" of the histogram structure (for example, in :class:`.ToCSV`). See graph._update_context for more details. """ hist_context = { "dim": self.dim, "nbins": self.nbins, "ranges": self.ranges } if self._scale is not None: hist_context["scale"] = self._scale lena.context.update_recursively(context, {"histogram": hist_context}) class Histogram(): """An element to produce histograms.""" def __init__(self, edges, bins=None, make_bins=None, initial_value=0): """*edges*, *bins* and *initial_value* have the same meaning as during creation of a :class:`histogram`. *make_bins* is a function without arguments that creates new bins (it will be called during :meth:`__init__` and :meth:`reset`). *initial_value* in this case is ignored, but bin check is made. If both *bins* and *make_bins* are provided, :exc:`.LenaTypeError` is raised. """ self._hist = histogram(edges, bins) if make_bins is not None and bins is not None: raise lena.core.LenaTypeError( "either initial bins or make_bins must be provided, " "not both: {} and {}".format(bins, make_bins) ) # may be None self._initial_bins = copy.deepcopy(bins) # todo: bins, make_bins, initial_value look redundant # and may be reconsidered when really using reset(). if make_bins: bins = make_bins() self._make_bins = make_bins self._cur_context = {} def fill(self, value): """Fill the histogram with *value*. *value* can be a *(data, context)* pair. Values outside the histogram edges are ignored. """ data, self._cur_context = lena.flow.get_data_context(value) self._hist.fill(data) # filling with weight is only allowed in histogram structure # self._hist.fill(data, weight) def compute(self): """Yield histogram with context.""" yield (self._hist, self._cur_context) def reset(self): """Reset the histogram. Current context is reset to an empty dict. Bins are reinitialized with the *initial_value* or with *make_bins()* (depending on the initialization). """ if self._make_bins is not None: self.bins = self._make_bins() elif self._initial_bins is not None: self.bins = copy.deepcopy(self._initial_bins) else: self.bins = hf.init_bins(self.edges, self._initial_value) self._cur_context = {}
lena/structures/histogram.py
codereval_python_data_168
Get or set the scale of the graph. If *other* is ``None``, return the scale of this graph. If a numeric *other* is provided, rescale to that value. If the graph has unknown or zero scale, rescaling that will raise :exc:`~.LenaValueError`. To get meaningful results, graph's fields are used. Only the last coordinate is rescaled. For example, if the graph has *x* and *y* coordinates, then *y* will be rescaled, and for a 3-dimensional graph *z* will be rescaled. All errors are rescaled together with their coordinate. def scale(self, other=None): """Get or set the scale of the graph. If *other* is ``None``, return the scale of this graph. If a numeric *other* is provided, rescale to that value. If the graph has unknown or zero scale, rescaling that will raise :exc:`~.LenaValueError`. To get meaningful results, graph's fields are used. Only the last coordinate is rescaled. For example, if the graph has *x* and *y* coordinates, then *y* will be rescaled, and for a 3-dimensional graph *z* will be rescaled. All errors are rescaled together with their coordinate. """ # this method is called scale() for uniformity with histograms # And this looks really good: explicit for computations # (not a subtle graph.scale, like a constant field (which is, # however, the case in graph - but not in other structures)) # and easy to remember (set_scale? rescale? change_scale_to?..) # We modify the graph in place, # because that would be redundant (not optimal) # to create a new graph # if we only want to change the scale of the existing one. if other is None: return self._scale if not self._scale: raise lena.core.LenaValueError( "can't rescale a graph with zero or unknown scale" ) last_coord_ind = self.dim - 1 last_coord_name = self.field_names[last_coord_ind] last_coord_indices = ([last_coord_ind] + self._get_err_indices(last_coord_name) ) # In Python 2 3/2 is 1, so we want to be safe; # the downside is that integer-valued graphs # will become floating, but that is doubtfully an issue. # Remove when/if dropping support for Python 2. rescale = float(other) / self._scale mul = operator.mul partial = functools.partial # a version with lambda is about 50% slower: # timeit.timeit('[*map(lambda val: val*2, vals)]', \ # setup='vals = list(range(45)); from operator import mul; \ # from functools import partial') # 3.159 # same setup for # timeit.timeit('[*map(partial(mul, 2), vals)]',...): # 2.075 # # [*map(...)] is very slightly faster than list(map(...)), # but it's unavailable in Python 2 (and anyway less readable). # rescale arrays of values and errors for ind, arr in enumerate(self.coords): if ind in last_coord_indices: # Python lists are faster than arrays, # https://stackoverflow.com/a/62399645/952234 # (because each time taking a value from an array # creates a Python object) self.coords[ind] = list(map(partial(mul, rescale), arr)) self._scale = other # as suggested in PEP 8 return None """A graph is a function at given coordinates.""" import copy import functools import operator import re import warnings import lena.core import lena.context import lena.flow class graph(): """Numeric arrays of equal size.""" def __init__(self, coords, field_names=("x", "y"), scale=None): """This structure generally corresponds to the graph of a function and represents arrays of coordinates and the function values of arbitrary dimensions. *coords* is a list of one-dimensional coordinate and value sequences (usually lists). There is little to no distinction between them, and "values" can also be called "coordinates". *field_names* provide the meaning of these arrays. For example, a 3-dimensional graph could be distinguished from a 2-dimensional graph with errors by its fields ("x", "y", "z") versus ("x", "y", "error_y"). Field names don't affect drawing graphs: for that :class:`~Variable`-s should be used. Default field names, provided for the most used 2-dimensional graphs, are "x" and "y". *field_names* can be a string separated by whitespace and/or commas or a tuple of strings, such as ("x", "y"). *field_names* must have as many elements as *coords* and each field name must be unique. Otherwise field names are arbitrary. Error fields must go after all other coordinates. Name of a coordinate error is "error\\_" appended by coordinate name. Further error details are appended after '_'. They could be arbitrary depending on the problem: "low", "high", "low_90%_cl", etc. Example: ("E", "time", "error_E_low", "error_time"). *scale* of the graph is a kind of its norm. It could be the integral of the function or its other property. A scale of a normalised probability density function would be one. An initialized *scale* is required if one needs to renormalise the graph in :meth:`scale` (for example, to plot it with other graphs). Coordinates of a function graph would usually be arrays of increasing values, which is not required here. Neither is it checked that coordinates indeed contain one-dimensional numeric values. However, non-standard graphs will likely lead to errors during plotting and will require more programmer's work and caution, so use them only if you understand what you are doing. A graph can be iterated yielding tuples of numbers for each point. **Attributes** :attr:`coords` is a list \ of one-dimensional lists of coordinates. :attr:`field_names` :attr:`dim` is the dimension of the graph, that is of all its coordinates without errors. In case of incorrect initialization arguments, :exc:`~.LenaTypeError` or :exc:`~.LenaValueError` is raised. .. versionadded:: 0.5 """ if not coords: raise lena.core.LenaValueError( "coords must be a non-empty sequence " "of coordinate sequences" ) # require coords to be of the same size pt_len = len(coords[0]) for arr in coords[1:]: if len(arr) != pt_len: raise lena.core.LenaValueError( "coords must have subsequences of equal lengths" ) # Unicode (Python 2) field names would be just bad, # so we don't check for it here. if isinstance(field_names, str): # split(', ') won't work. # From https://stackoverflow.com/a/44785447/952234: # \s stands for whitespace. field_names = tuple(re.findall(r'[^,\s]+', field_names)) elif not isinstance(field_names, tuple): # todo: why field_names are a tuple, # while coords are a list? # It might be non-Pythonic to require a tuple # (to prohibit a list), but it's important # for comparisons and uniformity raise lena.core.LenaTypeError( "field_names must be a string or a tuple" ) if len(field_names) != len(coords): raise lena.core.LenaValueError( "field_names must have must have the same size as coords" ) if len(set(field_names)) != len(field_names): raise lena.core.LenaValueError( "field_names contains duplicates" ) self.coords = coords self._scale = scale # field_names are better than fields, # because they are unambigous (as in namedtuple). self.field_names = field_names # decided to use "error_x_low" (like in ROOT). # Other versions were x_error (looked better than x_err), # but x_err_low looked much better than x_error_low). try: parsed_error_names = self._parse_error_names(field_names) except lena.core.LenaValueError as err: raise err # in Python 3 # raise err from None self._parsed_error_names = parsed_error_names dim = len(field_names) - len(parsed_error_names) self._coord_names = field_names[:dim] self.dim = dim # todo: add subsequences of coords as attributes # with field names. # In case if someone wants to create a graph of another function # at the same coordinates. # Should a) work when we rescale the graph # b) not interfere with other fields and methods # Probably we won't add methods __del__(n), __add__(*coords), # since it might change the scale. def __eq__(self, other): """Two graphs are equal, if and only if they have equal coordinates, field names and scales. If *other* is not a :class:`.graph`, return ``False``. Note that floating numbers should be compared approximately (using :func:`math.isclose`). Therefore this comparison may give false negatives. """ if not isinstance(other, graph): # in Python comparison between different types is allowed return False return (self.coords == other.coords and self._scale == other._scale and self.field_names == other.field_names) def _get_err_indices(self, coord_name): """Get error indices corresponding to a coordinate.""" err_indices = [] dim = self.dim for ind, err in enumerate(self._parsed_error_names): if err[1] == coord_name: err_indices.append(ind+dim) return err_indices def __iter__(self): """Iterate graph coords one by one.""" for val in zip(*self.coords): yield val def __repr__(self): return """graph({}, field_names={}, scale={})""".format( self.coords, self.field_names, self._scale ) def scale(self, other=None): """Get or set the scale of the graph. If *other* is ``None``, return the scale of this graph. If a numeric *other* is provided, rescale to that value. If the graph has unknown or zero scale, rescaling that will raise :exc:`~.LenaValueError`. To get meaningful results, graph's fields are used. Only the last coordinate is rescaled. For example, if the graph has *x* and *y* coordinates, then *y* will be rescaled, and for a 3-dimensional graph *z* will be rescaled. All errors are rescaled together with their coordinate. """ # this method is called scale() for uniformity with histograms # And this looks really good: explicit for computations # (not a subtle graph.scale, like a constant field (which is, # however, the case in graph - but not in other structures)) # and easy to remember (set_scale? rescale? change_scale_to?..) # We modify the graph in place, # because that would be redundant (not optimal) # to create a new graph # if we only want to change the scale of the existing one. if other is None: return self._scale if not self._scale: raise lena.core.LenaValueError( "can't rescale a graph with zero or unknown scale" ) last_coord_ind = self.dim - 1 last_coord_name = self.field_names[last_coord_ind] last_coord_indices = ([last_coord_ind] + self._get_err_indices(last_coord_name) ) # In Python 2 3/2 is 1, so we want to be safe; # the downside is that integer-valued graphs # will become floating, but that is doubtfully an issue. # Remove when/if dropping support for Python 2. rescale = float(other) / self._scale mul = operator.mul partial = functools.partial # a version with lambda is about 50% slower: # timeit.timeit('[*map(lambda val: val*2, vals)]', \ # setup='vals = list(range(45)); from operator import mul; \ # from functools import partial') # 3.159 # same setup for # timeit.timeit('[*map(partial(mul, 2), vals)]',...): # 2.075 # # [*map(...)] is very slightly faster than list(map(...)), # but it's unavailable in Python 2 (and anyway less readable). # rescale arrays of values and errors for ind, arr in enumerate(self.coords): if ind in last_coord_indices: # Python lists are faster than arrays, # https://stackoverflow.com/a/62399645/952234 # (because each time taking a value from an array # creates a Python object) self.coords[ind] = list(map(partial(mul, rescale), arr)) self._scale = other # as suggested in PEP 8 return None def _parse_error_names(self, field_names): # field_names is a parameter for easier testing, # usually object's field_names are used. errors = [] # collect all error fields and check that they are # strictly after other fields in_error_fields = False # there is at least one field last_coord_ind = 0 for ind, field in enumerate(field_names): if field.startswith("error_"): in_error_fields = True errors.append((field, ind)) else: last_coord_ind = ind if in_error_fields: raise lena.core.LenaValueError( "errors must go after coordinate fields" ) coords = set(field_names[:last_coord_ind+1]) parsed_errors = [] for err, ind in errors: err_coords = [] for coord in coords: err_main = err[6:] # all after "error_" if err_main == coord or err_main.startswith(coord + "_"): err_coords.append(coord) err_tail = err_main[len(coord)+1:] if not err_coords: raise lena.core.LenaValueError( "no coordinate corresponding to {} given".format(err) ) elif len(err_coords) > 1: raise lena.core.LenaValueError( "ambiguous error " + err +\ " corresponding to several coordinates given" ) # "error" may be redundant, but it is explicit. parsed_errors.append(("error", err_coords[0], err_tail, ind)) return parsed_errors def _update_context(self, context): """Update *context* with the properties of this graph. *context.error* is appended with indices of errors. Example subcontext for a graph with fields "E,t,error_E_low": {"error": {"x_low": {"index": 2}}}. Note that error names are called "x", "y" and "z" (this corresponds to first three coordinates, if they are present), which allows to simplify plotting. Existing values are not removed from *context.value* and its subcontexts. Called on "destruction" of the graph (for example, in :class:`.ToCSV`). By destruction we mean conversion to another structure (like text) in the flow. The graph object is not really destroyed in this process. """ # this method is private, because we encourage users to yield # graphs into the flow and process them with ToCSV element # (not manually). if not self._parsed_error_names: # no error fields present return dim = self.dim xyz_coord_names = self._coord_names[:3] for name, coord_name in zip(["x", "y", "z"], xyz_coord_names): for err in self._parsed_error_names: if err[1] == coord_name: error_ind = err[3] if err[2]: # add error suffix error_name = name + "_" + err[2] else: error_name = name lena.context.update_recursively( context, "error.{}.index".format(error_name), # error can correspond both to variable and # value, so we put it outside value. # "value.error.{}.index".format(error_name), error_ind ) # used in deprecated Graph def _rescale_value(rescale, value): return rescale * lena.flow.get_data(value) class Graph(object): """ .. deprecated:: 0.5 use :class:`graph`. This class may be used in the future, but with a changed interface. Function at given coordinates (arbitraty dimensions). Graph points can be set during the initialization and during :meth:`fill`. It can be rescaled (producing a new :class:`Graph`). A point is a tuple of *(coordinate, value)*, where both *coordinate* and *value* can be tuples of numbers. *Coordinate* corresponds to a point in N-dimensional space, while *value* is some function's value at this point (the function can take a value in M-dimensional space). Coordinate and value dimensions must be the same for all points. One can get graph points as :attr:`Graph.points` attribute. They will be sorted each time before return if *sort* was set to ``True``. An attempt to change points (use :attr:`Graph.points` on the left of '=') will raise Python's :exc:`AttributeError`. """ def __init__(self, points=None, context=None, scale=None, sort=True): """*points* is an array of *(coordinate, value)* tuples. *context* is the same as the most recent context during *fill*. Use it to provide a context when initializing a :class:`Graph` from existing points. *scale* sets the scale of the graph. It is used during plotting if rescaling is needed. Graph coordinates are sorted by default. This is usually needed to plot graphs of functions. If you need to keep the order of insertion, set *sort* to ``False``. By default, sorting is done using standard Python lists and functions. You can disable *sort* and provide your own sorting container for *points*. Some implementations are compared `here <http://www.grantjenks.com/docs/sortedcontainers/performance.html>`_. Note that a rescaled graph uses a default list. Note that :class:`Graph` does not reduce data. All filled values will be stored in it. To reduce data, use histograms. """ warnings.warn("Graph is deprecated since Lena 0.5. Use graph.", DeprecationWarning, stacklevel=2) self._points = points if points is not None else [] # todo: add some sanity checks for points self._scale = scale self._init_context = {"scale": scale} if context is None: self._cur_context = {} elif not isinstance(context, dict): raise lena.core.LenaTypeError( "context must be a dict, {} provided".format(context) ) else: self._cur_context = context self._sort = sort # todo: probably, scale from context is not needed. ## probably this function is not needed. ## it can't be copied, graphs won't be possible to compare. # *rescale_value* is a function, which can be used to scale # complex graph values. # It must accept a rescale parameter and the value at a data point. # By default, it is multiplication of rescale and the value # (which must be a number). # if rescale_value is None: # self._rescale_value = _rescale_value self._rescale_value = _rescale_value self._update() def fill(self, value): """Fill the graph with *value*. *Value* can be a *(data, context)* tuple. *Data* part must be a *(coordinates, value)* pair, where both coordinates and value are also tuples. For example, *value* can contain the principal number and its precision. """ point, self._cur_context = lena.flow.get_data_context(value) # coords, val = point self._points.append(point) def request(self): """Yield graph with context. If *sort* was initialized ``True``, graph points will be sorted. """ # If flow contained *scale* it the context, it is set now. self._update() yield (self, self._context) # compute method shouldn't be in this class, # because it is a pure FillRequest. # def compute(self): # """Yield graph with context (as in :meth:`request`), # and :meth:`reset`.""" # self._update() # yield (self, self._context) # self.reset() @property def points(self): """Get graph points (read only).""" # sort points before giving them self._update() return self._points def reset(self): """Reset points to an empty list and current context to an empty dict. """ self._points = [] self._cur_context = {} def __repr__(self): self._update() return ("Graph(points={}, scale={}, sort={})" .format(self._points, self._scale, self._sort)) def scale(self, other=None): """Get or set the scale. Graph's scale comes from an external source. For example, if the graph was computed from a function, this may be its integral passed via context during :meth:`fill`. Once the scale is set, it is stored in the graph. If one attempts to use scale which was not set, :exc:`.LenaAttributeError` is raised. If *other* is None, return the scale. If a ``float`` *other* is provided, rescale to *other*. A new graph with the scale equal to *other* is returned, the original one remains unchanged. Note that in this case its *points* will be a simple list and new graph *sort* parameter will be ``True``. Graphs with scale equal to zero can't be rescaled. Attempts to do that raise :exc:`.LenaValueError`. """ if other is None: # return scale self._update() if self._scale is None: raise lena.core.LenaAttributeError( "scale must be explicitly set before using that" ) return self._scale else: # rescale from other scale = self.scale() if scale == 0: raise lena.core.LenaValueError( "can't rescale graph with 0 scale" ) # new_init_context = copy.deepcopy(self._init_context) # new_init_context.update({"scale": other}) rescale = float(other) / scale new_points = [] for coord, val in self._points: # probably not needed, because tuples are immutable: # make a deep copy so that new values # are completely independent from old ones. new_points.append((coord, self._rescale_value(rescale, val))) # todo: should it inherit context? # Probably yes, but watch out scale. new_graph = Graph(points=new_points, scale=other, sort=self._sort) return new_graph def to_csv(self, separator=",", header=None): """.. deprecated:: 0.5 in Lena 0.5 to_csv is not used. Iterables are converted to tables. Convert graph's points to CSV. *separator* delimits values, the default is comma. *header*, if not ``None``, is the first string of the output (new line is added automatically). Since a graph can be multidimensional, for each point first its coordinate is converted to string (separated by *separator*), then each part of its value. To convert :class:`Graph` to CSV inside a Lena sequence, use :class:`lena.output.ToCSV`. """ if self._sort: self._update() def unpack_pt(pt): coord = pt[0] value = pt[1] if isinstance(coord, tuple): unpacked = list(coord) else: unpacked = [coord] if isinstance(value, tuple): unpacked += list(value) else: unpacked.append(value) return unpacked def pt_to_str(pt, separ): return separ.join([str(val) for val in unpack_pt(pt)]) if header is not None: # if one needs an empty header line, they may provide "" lines = header + "\n" else: lines = "" lines += "\n".join([pt_to_str(pt, separator) for pt in self.points]) return lines # *context* will be added to graph context. # If it contains "scale", :meth:`scale` method will be available. # Otherwise, if "scale" is contained in the context # during :meth:`fill`, it will be used. # In this case it is assumed that this scale # is same for all values (only the last filled context is checked). # Context from flow takes precedence over the initialized one. def _update(self): """Sort points if needed, update context.""" # todo: probably remove this context_scale? context_scale = self._cur_context.get("scale") if context_scale is not None: # this complex check is fine with rescale, # because that returns a new graph (this scale unchanged). if self._scale is not None and self._scale != context_scale: raise lena.core.LenaRuntimeError( "Initialization and context scale differ, " "{} and {} from context {}" .format(self._scale, context_scale, self._cur_context) ) self._scale = context_scale if self._sort: self._points = sorted(self._points) self._context = copy.deepcopy(self._cur_context) self._context.update(self._init_context) # why this? Not *graph.scale*? self._context.update({"scale": self._scale}) # self._context.update(lena.context.make_context(self, "_scale")) # todo: make this check during fill. Probably initialize self._dim # with kwarg dim. (dim of coordinates or values?) if self._points: # check points correctness points = self._points def coord_dim(coord): if not hasattr(coord, "__len__"): return 1 return len(coord) first_coord = points[0][0] dim = coord_dim(first_coord) same_dim = all(coord_dim(point[0]) == dim for point in points) if not same_dim: raise lena.core.LenaValueError( "coordinates tuples must have same dimension, " "{} given".format(points) ) self.dim = dim self._context["dim"] = self.dim def __eq__(self, other): if not isinstance(other, Graph): return False if self.points != other.points: return False if self._scale is None and other._scale is None: return True try: result = self.scale() == other.scale() except lena.core.LenaAttributeError: # one scale couldn't be computed return False else: return result
lena/structures/graph.py
codereval_python_data_169
Convert a :class:`.histogram` to a :class:`.graph`. *make_value* is a function to set the value of a graph's point. By default it is bin content. *make_value* accepts a single value (bin content) without context. This option could be used to create graph's error bars. For example, to create a graph with errors from a histogram where bins contain a named tuple with fields *mean*, *mean_error* and a context one could use >>> make_value = lambda bin_: (bin_.mean, bin_.mean_error) *get_coordinate* defines what the coordinate of a graph point created from a histogram bin will be. It can be "left" (default), "right" and "middle". *field_names* set field names of the graph. Their number must be the same as the dimension of the result. For a *make_value* above they would be *("x", "y_mean", "y_mean_error")*. *scale* becomes the graph's scale (unknown by default). If it is ``True``, it uses the histogram scale. *hist* must contain only numeric bins (without context) or *make_value* must remove context when creating a numeric graph. Return the resulting graph. def hist_to_graph(hist, make_value=None, get_coordinate="left", field_names=("x", "y"), scale=None): """Convert a :class:`.histogram` to a :class:`.graph`. *make_value* is a function to set the value of a graph's point. By default it is bin content. *make_value* accepts a single value (bin content) without context. This option could be used to create graph's error bars. For example, to create a graph with errors from a histogram where bins contain a named tuple with fields *mean*, *mean_error* and a context one could use >>> make_value = lambda bin_: (bin_.mean, bin_.mean_error) *get_coordinate* defines what the coordinate of a graph point created from a histogram bin will be. It can be "left" (default), "right" and "middle". *field_names* set field names of the graph. Their number must be the same as the dimension of the result. For a *make_value* above they would be *("x", "y_mean", "y_mean_error")*. *scale* becomes the graph's scale (unknown by default). If it is ``True``, it uses the histogram scale. *hist* must contain only numeric bins (without context) or *make_value* must remove context when creating a numeric graph. Return the resulting graph. """ ## Could have allowed get_coordinate to be callable # (for generality), but 1) first find a use case, # 2) histogram bins could be adjusted in the first place. # -- don't understand 2. if get_coordinate == "left": get_coord = lambda edges: tuple(coord[0] for coord in edges) elif get_coordinate == "right": get_coord = lambda edges: tuple(coord[1] for coord in edges) # *middle* between the two edges, not the *center* of the bin # as a whole (because the graph corresponds to a point) elif get_coordinate == "middle": get_coord = lambda edges: tuple(0.5*(coord[0] + coord[1]) for coord in edges) else: raise lena.core.LenaValueError( 'get_coordinate must be one of "left", "right" or "middle"; ' '"{}" provided'.format(get_coordinate) ) # todo: make_value may be bad design. # Maybe allow to change the graph in the sequence. # However, make_value allows not to recreate a graph # or its coordinates (if that is not needed). if isinstance(field_names, str): # copied from graph.__init__ field_names = tuple(re.findall(r'[^,\s]+', field_names)) elif not isinstance(field_names, tuple): raise lena.core.LenaTypeError( "field_names must be a string or a tuple" ) coords = [[] for _ in field_names] chain = itertools.chain if scale is True: scale = hist.scale() for value, edges in iter_bins_with_edges(hist.bins, hist.edges): coord = get_coord(edges) # Since we never use contexts here, it will be optimal # to ignore them completely (remove them elsewhere). # bin_value = lena.flow.get_data(value) bin_value = value if make_value is None: graph_value = bin_value else: graph_value = make_value(bin_value) # for iteration below if not hasattr(graph_value, "__iter__"): graph_value = (graph_value,) # add each coordinate to respective array for arr, coord_ in zip(coords, chain(coord, graph_value)): arr.append(coord_) return _graph(coords, field_names=field_names, scale=scale) """Functions for histograms. These functions are used for low-level work with histograms and their contents. They are not needed for normal usage. """ import collections import copy import itertools import operator import re import sys if sys.version_info.major == 3: from functools import reduce as _reduce else: _reduce = reduce import lena.core from .graph import graph as _graph class HistCell(collections.namedtuple("HistCell", ("edges, bin, index"))): """A namedtuple with fields *edges, bin, index*.""" # from Aaron Hall's answer https://stackoverflow.com/a/28568351/952234 __slots__ = () def cell_to_string( cell_edges, var_context=None, coord_names=None, coord_fmt="{}_lte_{}_lt_{}", coord_join="_", reverse=False): """Transform cell edges into a string. *cell_edges* is a tuple of pairs *(lower bound, upper bound)* for each coordinate. *coord_names* is a list of coordinates names. *coord_fmt* is a string, which defines how to format individual coordinates. *coord_join* is a string, which joins coordinate pairs. If *reverse* is True, coordinates are joined in reverse order. """ # todo: do we really need var_context? # todo: even if so, why isn't that a {}? Is that dangerous? if coord_names is None: if var_context is None: coord_names = [ "coord{}".format(ind) for ind in range(len(cell_edges)) ] else: if "combine" in var_context: coord_names = [var["name"] for var in var_context["combine"]] else: coord_names = [var_context["name"]] if len(cell_edges) != len(coord_names): raise lena.core.LenaValueError( "coord_names must have same length as cell_edges, " "{} and {} given".format(coord_names, cell_edges) ) coord_strings = [coord_fmt.format(edge[0], coord_names[ind], edge[1]) for (ind, edge) in enumerate(cell_edges)] if reverse: coord_strings = reversed(coord_strings) coord_str = coord_join.join(coord_strings) return coord_str def _check_edges_increasing_1d(arr): if len(arr) <= 1: raise lena.core.LenaValueError("size of edges should be more than one," " {} provided".format(arr)) increasing = (tup[0] < tup[1] for tup in zip(arr, arr[1:])) if not all(increasing): raise lena.core.LenaValueError( "expected strictly increasing values, " "{} provided".format(arr) ) def check_edges_increasing(edges): """Assure that multidimensional *edges* are increasing. If length of *edges* or its subarray is less than 2 or if some subarray of *edges* contains not strictly increasing values, :exc:`.LenaValueError` is raised. """ if not len(edges): raise lena.core.LenaValueError("edges must be non-empty") elif not hasattr(edges[0], '__iter__'): _check_edges_increasing_1d(edges) return for arr in edges: if len(arr) <= 1: raise lena.core.LenaValueError( "size of edges should be more than one. " "{} provided".format(arr) ) _check_edges_increasing_1d(arr) def get_bin_edges(index, edges): """Return edges of the bin for the given *edges* of a histogram. In one-dimensional case *index* must be an integer and a tuple of *(x_low_edge, x_high_edge)* for that bin is returned. In a multidimensional case *index* is a container of numeric indices in each dimension. A list of bin edges in each dimension is returned.""" # todo: maybe give up this 1- and multidimensional unification # and write separate functions for each case. if not hasattr(edges[0], '__iter__'): # 1-dimensional edges if hasattr(index, '__iter__'): index = index[0] return (edges[index], edges[index+1]) # multidimensional edges return [(edges[coord][i], edges[coord][i+1]) for coord, i in enumerate(index)] def get_bin_on_index(index, bins): """Return bin corresponding to multidimensional *index*. *index* can be a number or a list/tuple. If *index* length is less than dimension of *bins*, a subarray of *bins* is returned. In case of an index error, :exc:`.LenaIndexError` is raised. Example: >>> from lena.structures import histogram, get_bin_on_index >>> hist = histogram([0, 1], [0]) >>> get_bin_on_index(0, hist.bins) 0 >>> get_bin_on_index((0, 1), [[0, 1], [0, 0]]) 1 >>> get_bin_on_index(0, [[0, 1], [0, 0]]) [0, 1] """ if not isinstance(index, (list, tuple)): index = [index] subarr = bins for ind in index: try: subarr = subarr[ind] except IndexError: raise lena.core.LenaIndexError( "bad index: {}, bins = {}".format(index, bins) ) return subarr def get_bin_on_value_1d(val, arr): """Return index for value in one-dimensional array. *arr* must contain strictly increasing values (not necessarily equidistant), it is not checked. "Linear binary search" is used, that is our array search by default assumes the array to be split on equidistant steps. Example: >>> from lena.structures import get_bin_on_value_1d >>> arr = [0, 1, 4, 5, 7, 10] >>> get_bin_on_value_1d(0, arr) 0 >>> get_bin_on_value_1d(4.5, arr) 2 >>> # upper range is excluded >>> get_bin_on_value_1d(10, arr) 5 >>> # underflow >>> get_bin_on_value_1d(-10, arr) -1 """ # may also use numpy.searchsorted # https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.searchsorted.html ind_min = 0 ind_max = len(arr) - 1 while True: if ind_max - ind_min <= 1: # lower bound is close if val < arr[ind_min]: return ind_min - 1 # upper bound is open elif val >= arr[ind_max]: return ind_max else: return ind_min if val == arr[ind_min]: return ind_min if val < arr[ind_min]: return ind_min - 1 elif val >= arr[ind_max]: return ind_max else: shift = int( (ind_max - ind_min) * ( float(val - arr[ind_min]) / (arr[ind_max] - arr[ind_min]) )) ind_guess = ind_min + shift if ind_min == ind_guess: ind_min += 1 continue # ind_max is always more that ind_guess, # because val < arr[ind_max] (see the formula for shift). # This branch is not needed and can't be tested. # But for the sake of numerical inaccuracies, let us keep this # so that we never get into an infinite loop. elif ind_max == ind_guess: ind_max -= 1 continue if val < arr[ind_guess]: ind_max = ind_guess else: ind_min = ind_guess def get_bin_on_value(arg, edges): """Get the bin index for *arg* in a multidimensional array *edges*. *arg* is a 1-dimensional array of numbers (or a number for 1-dimensional *edges*), and corresponds to a point in N-dimensional space. *edges* is an array of N-1 dimensional arrays (lists or tuples) of numbers. Each 1-dimensional subarray consists of increasing numbers. *arg* and *edges* must have the same length (otherwise :exc:`.LenaValueError` is raised). *arg* and *edges* must be iterable and support *len()*. Return list of indices in *edges* corresponding to *arg*. If any coordinate is out of its corresponding edge range, its index will be ``-1`` for underflow or ``len(edge)-1`` for overflow. Examples: >>> from lena.structures import get_bin_on_value >>> edges = [[1, 2, 3], [1, 3.5]] >>> get_bin_on_value((1.5, 2), edges) [0, 0] >>> get_bin_on_value((1.5, 0), edges) [0, -1] >>> # the upper edge is excluded >>> get_bin_on_value((3, 2), edges) [2, 0] >>> # one-dimensional edges >>> edges = [1, 2, 3] >>> get_bin_on_value(2, edges) [1] """ # arg is a one-dimensional index if not isinstance(arg, (tuple, list)): return [get_bin_on_value_1d(arg, edges)] # arg is a multidimensional index if len(arg) != len(edges): raise lena.core.LenaValueError( "argument should have same dimension as edges. " "arg = {}, edges = {}".format(arg, edges) ) indices = [] for ind, array in enumerate(edges): cur_bin = get_bin_on_value_1d(arg[ind], array) indices.append(cur_bin) return indices def get_example_bin(struct): """Return bin with zero index on each axis of the histogram bins. For example, if the histogram is two-dimensional, return hist[0][0]. *struct* can be a :class:`.histogram` or an array of bins. """ if isinstance(struct, lena.structures.histogram): return lena.structures.get_bin_on_index([0] * struct.dim, struct.bins) else: bins = struct while isinstance(bins, list): bins = bins[0] return bins def hist_to_graph(hist, make_value=None, get_coordinate="left", field_names=("x", "y"), scale=None): """Convert a :class:`.histogram` to a :class:`.graph`. *make_value* is a function to set the value of a graph's point. By default it is bin content. *make_value* accepts a single value (bin content) without context. This option could be used to create graph's error bars. For example, to create a graph with errors from a histogram where bins contain a named tuple with fields *mean*, *mean_error* and a context one could use >>> make_value = lambda bin_: (bin_.mean, bin_.mean_error) *get_coordinate* defines what the coordinate of a graph point created from a histogram bin will be. It can be "left" (default), "right" and "middle". *field_names* set field names of the graph. Their number must be the same as the dimension of the result. For a *make_value* above they would be *("x", "y_mean", "y_mean_error")*. *scale* becomes the graph's scale (unknown by default). If it is ``True``, it uses the histogram scale. *hist* must contain only numeric bins (without context) or *make_value* must remove context when creating a numeric graph. Return the resulting graph. """ ## Could have allowed get_coordinate to be callable # (for generality), but 1) first find a use case, # 2) histogram bins could be adjusted in the first place. # -- don't understand 2. if get_coordinate == "left": get_coord = lambda edges: tuple(coord[0] for coord in edges) elif get_coordinate == "right": get_coord = lambda edges: tuple(coord[1] for coord in edges) # *middle* between the two edges, not the *center* of the bin # as a whole (because the graph corresponds to a point) elif get_coordinate == "middle": get_coord = lambda edges: tuple(0.5*(coord[0] + coord[1]) for coord in edges) else: raise lena.core.LenaValueError( 'get_coordinate must be one of "left", "right" or "middle"; ' '"{}" provided'.format(get_coordinate) ) # todo: make_value may be bad design. # Maybe allow to change the graph in the sequence. # However, make_value allows not to recreate a graph # or its coordinates (if that is not needed). if isinstance(field_names, str): # copied from graph.__init__ field_names = tuple(re.findall(r'[^,\s]+', field_names)) elif not isinstance(field_names, tuple): raise lena.core.LenaTypeError( "field_names must be a string or a tuple" ) coords = [[] for _ in field_names] chain = itertools.chain if scale is True: scale = hist.scale() for value, edges in iter_bins_with_edges(hist.bins, hist.edges): coord = get_coord(edges) # Since we never use contexts here, it will be optimal # to ignore them completely (remove them elsewhere). # bin_value = lena.flow.get_data(value) bin_value = value if make_value is None: graph_value = bin_value else: graph_value = make_value(bin_value) # for iteration below if not hasattr(graph_value, "__iter__"): graph_value = (graph_value,) # add each coordinate to respective array for arr, coord_ in zip(coords, chain(coord, graph_value)): arr.append(coord_) return _graph(coords, field_names=field_names, scale=scale) def init_bins(edges, value=0, deepcopy=False): """Initialize cells of the form *edges* with the given *value*. Return bins filled with copies of *value*. *Value* must be copyable, usual numbers will suit. If the value is mutable, use *deepcopy =* ``True`` (or the content of cells will be identical). Examples: >>> edges = [[0, 1], [0, 1]] >>> # one cell >>> init_bins(edges) [[0]] >>> # no need to use floats, >>> # because integers will automatically be cast to floats >>> # when used together >>> init_bins(edges, 0.0) [[0.0]] >>> init_bins([[0, 1, 2], [0, 1, 2]]) [[0, 0], [0, 0]] >>> init_bins([0, 1, 2]) [0, 0] """ nbins = len(edges) - 1 if not isinstance(edges[0], (list, tuple)): # edges is one-dimensional if deepcopy: return [copy.deepcopy(value) for _ in range(nbins)] else: return [value] * nbins for ind, arr in enumerate(edges): if ind == nbins: if deepcopy: return [copy.deepcopy(value) for _ in range(len(arr)-1)] else: return list([value] * (len(arr)-1)) bins = [] for _ in range(len(arr)-1): bins.append(init_bins(edges[ind+1:], value, deepcopy)) return bins def integral(bins, edges): """Compute integral (scale for a histogram). *bins* contain values, and *edges* form the mesh for the integration. Their format is defined in :class:`.histogram` description. """ total = 0 for ind, bin_content in iter_bins(bins): bin_lengths = [ edges[coord][i+1] - edges[coord][i] for coord, i in enumerate(ind) ] # product vol = _reduce(operator.mul, bin_lengths, 1) cell_integral = vol * bin_content total += cell_integral return total def iter_bins(bins): """Iterate on *bins*. Yield *(index, bin content)*. Edges with higher index are iterated first (that is z, then y, then x for a 3-dimensional histogram). """ # if not isinstance(bins, (list, tuple)): if not hasattr(bins, '__iter__'): # cell yield ((), bins) else: for ind, _ in enumerate(bins): for sub_ind, val in iter_bins(bins[ind]): yield (((ind,) + sub_ind), val) def iter_bins_with_edges(bins, edges): """Generate *(bin content, bin edges)* pairs. Bin edges is a tuple, such that its item at index i is *(lower bound, upper bound)* of the bin at i-th coordinate. Examples: >>> from lena.math import mesh >>> list(iter_bins_with_edges([0, 1, 2], edges=mesh((0, 3), 3))) [(0, ((0, 1.0),)), (1, ((1.0, 2.0),)), (2, ((2.0, 3),))] >>> >>> # 2-dimensional histogram >>> list(iter_bins_with_edges( ... bins=[[2]], edges=mesh(((0, 1), (0, 1)), (1, 1)) ... )) [(2, ((0, 1), (0, 1)))] .. versionadded:: 0.5 made public. """ # todo: only a list or also a tuple, an array? if not isinstance(edges[0], list): edges = [edges] bins_sizes = [len(edge)-1 for edge in edges] indices = [list(range(nbins)) for nbins in bins_sizes] for index in itertools.product(*indices): bin_ = lena.structures.get_bin_on_index(index, bins) edges_low = [] edges_high = [] for var, var_ind in enumerate(index): edges_low.append(edges[var][var_ind]) edges_high.append(edges[var][var_ind+1]) yield (bin_, tuple(zip(edges_low, edges_high))) def iter_cells(hist, ranges=None, coord_ranges=None): """Iterate cells of a histogram *hist*, possibly in a subrange. For each bin, yield a :class:`HistCell` containing *bin edges, bin content* and *bin index*. The order of iteration is the same as for :func:`iter_bins`. *ranges* are the ranges of bin indices to be used for each coordinate (the lower value is included, the upper value is excluded). *coord_ranges* set real coordinate ranges based on histogram edges. Obviously, they can be not exactly bin edges. If one of the ranges for the given coordinate is outside the histogram edges, then only existing histogram edges within the range are selected. If the coordinate range is completely outside histogram edges, nothing is yielded. If a lower or upper *coord_range* falls within a bin, this bin is yielded. Note that if a coordinate range falls on a bin edge, the number of generated bins can be unstable because of limited float precision. *ranges* and *coord_ranges* are tuples of tuples of limits in corresponding dimensions. For one-dimensional histogram it must be a tuple containing a tuple, for example *((None, None),)*. ``None`` as an upper or lower *range* means no limit (*((None, None),)* is equivalent to *((0, len(bins)),)* for a 1-dimensional histogram). If a *range* index is lower than 0 or higher than possible index, :exc:`.LenaValueError` is raised. If both *coord_ranges* and *ranges* are provided, :exc:`.LenaTypeError` is raised. """ # for bin_ind, bin_ in iter_bins(hist.bins): # yield HistCell(get_bin_edges(bin_ind, hist.edges), bin_, bin_ind) # if bins and edges are calculated each time, save the result now bins, edges = hist.bins, hist.edges # todo: hist.edges must be same # for 1- and multidimensional histograms. if hist.dim == 1: edges = (edges,) if coord_ranges is not None: if ranges is not None: raise lena.core.LenaTypeError( "only ranges or coord_ranges can be provided, not both" ) ranges = [] if not isinstance(coord_ranges[0], (tuple, list)): coord_ranges = (coord_ranges, ) for coord, coord_range in enumerate(coord_ranges): # todo: (dis?)allow None as an infinite range. # todo: raise or transpose unordered coordinates? # todo: change the order of function arguments. lower_bin_ind = get_bin_on_value_1d(coord_range[0], edges[coord]) if lower_bin_ind == -1: lower_bin_ind = 0 upper_bin_ind = get_bin_on_value_1d(coord_range[1], edges[coord]) max_ind = len(edges[coord]) if upper_bin_ind == max_ind: upper_bin_ind -= 1 if lower_bin_ind >= max_ind or upper_bin_ind <= 0: # histogram edges are outside the range. return ranges.append((lower_bin_ind, upper_bin_ind)) if not ranges: ranges = ((None, None),) * hist.dim real_ind_ranges = [] for coord, coord_range in enumerate(ranges): low, up = coord_range if low is None: low = 0 else: # negative indices should not be supported if low < 0: raise lena.core.LenaValueError( "low must be not less than 0 if provided" ) max_ind = len(edges[coord]) - 1 if up is None: up = max_ind else: # huge indices should not be supported as well. if up > max_ind: raise lena.core.LenaValueError( "up must not be greater than len(edges)-1, if provided" ) real_ind_ranges.append(list(range(low, up))) indices = list(itertools.product(*real_ind_ranges)) for ind in indices: yield HistCell(get_bin_edges(ind, edges), get_bin_on_index(ind, bins), ind) def make_hist_context(hist, context): """Update a deep copy of *context* with the context of a :class:`.histogram` *hist*. .. deprecated:: 0.5 histogram context is updated automatically during conversion in :class:`~.output.ToCSV`. Use histogram._update_context explicitly if needed. """ # absolutely unnecessary. context = copy.deepcopy(context) hist_context = { "histogram": { "dim": hist.dim, "nbins": hist.nbins, "ranges": hist.ranges } } context.update(hist_context) # just bad. return context def unify_1_md(bins, edges): """Unify 1- and multidimensional bins and edges. Return a tuple of *(bins, edges)*. Bins and multidimensional *edges* return unchanged, while one-dimensional *edges* are inserted into a list. """ if hasattr(edges[0], '__iter__'): # if isinstance(edges[0], (list, tuple)): return (bins, edges) else: return (bins, [edges])
lena/structures/hist_functions.py
codereval_python_data_170
Verify that *candidate* might correctly provide *iface*. This involves: - Making sure the candidate claims that it provides the interface using ``iface.providedBy`` (unless *tentative* is `True`, in which case this step is skipped). This means that the candidate's class declares that it `implements <zope.interface.implementer>` the interface, or the candidate itself declares that it `provides <zope.interface.provider>` the interface - Making sure the candidate defines all the necessary methods - Making sure the methods have the correct signature (to the extent possible) - Making sure the candidate defines all the necessary attributes :return bool: Returns a true value if everything that could be checked passed. :raises zope.interface.Invalid: If any of the previous conditions does not hold. .. versionchanged:: 5.0 If multiple methods or attributes are invalid, all such errors are collected and reported. Previously, only the first error was reported. As a special case, if only one such error is present, it is raised alone, like before. def _verify(iface, candidate, tentative=False, vtype=None): """ Verify that *candidate* might correctly provide *iface*. This involves: - Making sure the candidate claims that it provides the interface using ``iface.providedBy`` (unless *tentative* is `True`, in which case this step is skipped). This means that the candidate's class declares that it `implements <zope.interface.implementer>` the interface, or the candidate itself declares that it `provides <zope.interface.provider>` the interface - Making sure the candidate defines all the necessary methods - Making sure the methods have the correct signature (to the extent possible) - Making sure the candidate defines all the necessary attributes :return bool: Returns a true value if everything that could be checked passed. :raises zope.interface.Invalid: If any of the previous conditions does not hold. .. versionchanged:: 5.0 If multiple methods or attributes are invalid, all such errors are collected and reported. Previously, only the first error was reported. As a special case, if only one such error is present, it is raised alone, like before. """ if vtype == 'c': tester = iface.implementedBy else: tester = iface.providedBy excs = [] if not tentative and not tester(candidate): excs.append(DoesNotImplement(iface, candidate)) for name, desc in iface.namesAndDescriptions(all=True): try: _verify_element(iface, name, desc, candidate, vtype) except Invalid as e: excs.append(e) if excs: if len(excs) == 1: raise excs[0] raise MultipleInvalid(iface, candidate, excs) return True ############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Verify interface implementations """ from __future__ import print_function import inspect import sys from types import FunctionType from types import MethodType from zope.interface._compat import PYPY2 from zope.interface.exceptions import BrokenImplementation from zope.interface.exceptions import BrokenMethodImplementation from zope.interface.exceptions import DoesNotImplement from zope.interface.exceptions import Invalid from zope.interface.exceptions import MultipleInvalid from zope.interface.interface import fromMethod, fromFunction, Method __all__ = [ 'verifyObject', 'verifyClass', ] # This will be monkey-patched when running under Zope 2, so leave this # here: MethodTypes = (MethodType, ) def _verify(iface, candidate, tentative=False, vtype=None): """ Verify that *candidate* might correctly provide *iface*. This involves: - Making sure the candidate claims that it provides the interface using ``iface.providedBy`` (unless *tentative* is `True`, in which case this step is skipped). This means that the candidate's class declares that it `implements <zope.interface.implementer>` the interface, or the candidate itself declares that it `provides <zope.interface.provider>` the interface - Making sure the candidate defines all the necessary methods - Making sure the methods have the correct signature (to the extent possible) - Making sure the candidate defines all the necessary attributes :return bool: Returns a true value if everything that could be checked passed. :raises zope.interface.Invalid: If any of the previous conditions does not hold. .. versionchanged:: 5.0 If multiple methods or attributes are invalid, all such errors are collected and reported. Previously, only the first error was reported. As a special case, if only one such error is present, it is raised alone, like before. """ if vtype == 'c': tester = iface.implementedBy else: tester = iface.providedBy excs = [] if not tentative and not tester(candidate): excs.append(DoesNotImplement(iface, candidate)) for name, desc in iface.namesAndDescriptions(all=True): try: _verify_element(iface, name, desc, candidate, vtype) except Invalid as e: excs.append(e) if excs: if len(excs) == 1: raise excs[0] raise MultipleInvalid(iface, candidate, excs) return True def _verify_element(iface, name, desc, candidate, vtype): # Here the `desc` is either an `Attribute` or `Method` instance try: attr = getattr(candidate, name) except AttributeError: if (not isinstance(desc, Method)) and vtype == 'c': # We can't verify non-methods on classes, since the # class may provide attrs in it's __init__. return # TODO: On Python 3, this should use ``raise...from`` raise BrokenImplementation(iface, desc, candidate) if not isinstance(desc, Method): # If it's not a method, there's nothing else we can test return if inspect.ismethoddescriptor(attr) or inspect.isbuiltin(attr): # The first case is what you get for things like ``dict.pop`` # on CPython (e.g., ``verifyClass(IFullMapping, dict))``). The # second case is what you get for things like ``dict().pop`` on # CPython (e.g., ``verifyObject(IFullMapping, dict()))``. # In neither case can we get a signature, so there's nothing # to verify. Even the inspect module gives up and raises # ValueError: no signature found. The ``__text_signature__`` attribute # isn't typically populated either. # # Note that on PyPy 2 or 3 (up through 7.3 at least), these are # not true for things like ``dict.pop`` (but might be true for C extensions?) return if isinstance(attr, FunctionType): if sys.version_info[0] >= 3 and isinstance(candidate, type) and vtype == 'c': # This is an "unbound method" in Python 3. # Only unwrap this if we're verifying implementedBy; # otherwise we can unwrap @staticmethod on classes that directly # provide an interface. meth = fromFunction(attr, iface, name=name, imlevel=1) else: # Nope, just a normal function meth = fromFunction(attr, iface, name=name) elif (isinstance(attr, MethodTypes) and type(attr.__func__) is FunctionType): meth = fromMethod(attr, iface, name) elif isinstance(attr, property) and vtype == 'c': # Without an instance we cannot be sure it's not a # callable. # TODO: This should probably check inspect.isdatadescriptor(), # a more general form than ``property`` return else: if not callable(attr): raise BrokenMethodImplementation(desc, "implementation is not a method", attr, iface, candidate) # sigh, it's callable, but we don't know how to introspect it, so # we have to give it a pass. return # Make sure that the required and implemented method signatures are # the same. mess = _incompat(desc.getSignatureInfo(), meth.getSignatureInfo()) if mess: if PYPY2 and _pypy2_false_positive(mess, candidate, vtype): return raise BrokenMethodImplementation(desc, mess, attr, iface, candidate) def verifyClass(iface, candidate, tentative=False): """ Verify that the *candidate* might correctly provide *iface*. """ return _verify(iface, candidate, tentative, vtype='c') def verifyObject(iface, candidate, tentative=False): return _verify(iface, candidate, tentative, vtype='o') verifyObject.__doc__ = _verify.__doc__ _MSG_TOO_MANY = 'implementation requires too many arguments' _KNOWN_PYPY2_FALSE_POSITIVES = frozenset(( _MSG_TOO_MANY, )) def _pypy2_false_positive(msg, candidate, vtype): # On PyPy2, builtin methods and functions like # ``dict.pop`` that take pseudo-optional arguments # (those with no default, something you can't express in Python 2 # syntax; CPython uses special internal APIs to implement these methods) # return false failures because PyPy2 doesn't expose any way # to detect this pseudo-optional status. PyPy3 doesn't have this problem # because of __defaults_count__, and CPython never gets here because it # returns true for ``ismethoddescriptor`` or ``isbuiltin``. # # We can't catch all such cases, but we can handle the common ones. # if msg not in _KNOWN_PYPY2_FALSE_POSITIVES: return False known_builtin_types = vars(__builtins__).values() candidate_type = candidate if vtype == 'c' else type(candidate) if candidate_type in known_builtin_types: return True return False def _incompat(required, implemented): #if (required['positional'] != # implemented['positional'][:len(required['positional'])] # and implemented['kwargs'] is None): # return 'imlementation has different argument names' if len(implemented['required']) > len(required['required']): return _MSG_TOO_MANY if ((len(implemented['positional']) < len(required['positional'])) and not implemented['varargs']): return "implementation doesn't allow enough arguments" if required['kwargs'] and not implemented['kwargs']: return "implementation doesn't support keyword arguments" if required['varargs'] and not implemented['varargs']: return "implementation doesn't support variable arguments"
src/zope/interface/verify.py
codereval_python_data_171
Verify that *candidate* might correctly provide *iface*. This involves: - Making sure the candidate claims that it provides the interface using ``iface.providedBy`` (unless *tentative* is `True`, in which case this step is skipped). This means that the candidate's class declares that it `implements <zope.interface.implementer>` the interface, or the candidate itself declares that it `provides <zope.interface.provider>` the interface - Making sure the candidate defines all the necessary methods - Making sure the methods have the correct signature (to the extent possible) - Making sure the candidate defines all the necessary attributes :return bool: Returns a true value if everything that could be checked passed. :raises zope.interface.Invalid: If any of the previous conditions does not hold. .. versionchanged:: 5.0 If multiple methods or attributes are invalid, all such errors are collected and reported. Previously, only the first error was reported. As a special case, if only one such error is present, it is raised alone, like before. def verifyObject(iface, candidate, tentative=False): return _verify(iface, candidate, tentative, vtype='o') ############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Verify interface implementations """ from __future__ import print_function import inspect import sys from types import FunctionType from types import MethodType from zope.interface._compat import PYPY2 from zope.interface.exceptions import BrokenImplementation from zope.interface.exceptions import BrokenMethodImplementation from zope.interface.exceptions import DoesNotImplement from zope.interface.exceptions import Invalid from zope.interface.exceptions import MultipleInvalid from zope.interface.interface import fromMethod, fromFunction, Method __all__ = [ 'verifyObject', 'verifyClass', ] # This will be monkey-patched when running under Zope 2, so leave this # here: MethodTypes = (MethodType, ) def _verify(iface, candidate, tentative=False, vtype=None): """ Verify that *candidate* might correctly provide *iface*. This involves: - Making sure the candidate claims that it provides the interface using ``iface.providedBy`` (unless *tentative* is `True`, in which case this step is skipped). This means that the candidate's class declares that it `implements <zope.interface.implementer>` the interface, or the candidate itself declares that it `provides <zope.interface.provider>` the interface - Making sure the candidate defines all the necessary methods - Making sure the methods have the correct signature (to the extent possible) - Making sure the candidate defines all the necessary attributes :return bool: Returns a true value if everything that could be checked passed. :raises zope.interface.Invalid: If any of the previous conditions does not hold. .. versionchanged:: 5.0 If multiple methods or attributes are invalid, all such errors are collected and reported. Previously, only the first error was reported. As a special case, if only one such error is present, it is raised alone, like before. """ if vtype == 'c': tester = iface.implementedBy else: tester = iface.providedBy excs = [] if not tentative and not tester(candidate): excs.append(DoesNotImplement(iface, candidate)) for name, desc in iface.namesAndDescriptions(all=True): try: _verify_element(iface, name, desc, candidate, vtype) except Invalid as e: excs.append(e) if excs: if len(excs) == 1: raise excs[0] raise MultipleInvalid(iface, candidate, excs) return True def _verify_element(iface, name, desc, candidate, vtype): # Here the `desc` is either an `Attribute` or `Method` instance try: attr = getattr(candidate, name) except AttributeError: if (not isinstance(desc, Method)) and vtype == 'c': # We can't verify non-methods on classes, since the # class may provide attrs in it's __init__. return # TODO: On Python 3, this should use ``raise...from`` raise BrokenImplementation(iface, desc, candidate) if not isinstance(desc, Method): # If it's not a method, there's nothing else we can test return if inspect.ismethoddescriptor(attr) or inspect.isbuiltin(attr): # The first case is what you get for things like ``dict.pop`` # on CPython (e.g., ``verifyClass(IFullMapping, dict))``). The # second case is what you get for things like ``dict().pop`` on # CPython (e.g., ``verifyObject(IFullMapping, dict()))``. # In neither case can we get a signature, so there's nothing # to verify. Even the inspect module gives up and raises # ValueError: no signature found. The ``__text_signature__`` attribute # isn't typically populated either. # # Note that on PyPy 2 or 3 (up through 7.3 at least), these are # not true for things like ``dict.pop`` (but might be true for C extensions?) return if isinstance(attr, FunctionType): if sys.version_info[0] >= 3 and isinstance(candidate, type) and vtype == 'c': # This is an "unbound method" in Python 3. # Only unwrap this if we're verifying implementedBy; # otherwise we can unwrap @staticmethod on classes that directly # provide an interface. meth = fromFunction(attr, iface, name=name, imlevel=1) else: # Nope, just a normal function meth = fromFunction(attr, iface, name=name) elif (isinstance(attr, MethodTypes) and type(attr.__func__) is FunctionType): meth = fromMethod(attr, iface, name) elif isinstance(attr, property) and vtype == 'c': # Without an instance we cannot be sure it's not a # callable. # TODO: This should probably check inspect.isdatadescriptor(), # a more general form than ``property`` return else: if not callable(attr): raise BrokenMethodImplementation(desc, "implementation is not a method", attr, iface, candidate) # sigh, it's callable, but we don't know how to introspect it, so # we have to give it a pass. return # Make sure that the required and implemented method signatures are # the same. mess = _incompat(desc.getSignatureInfo(), meth.getSignatureInfo()) if mess: if PYPY2 and _pypy2_false_positive(mess, candidate, vtype): return raise BrokenMethodImplementation(desc, mess, attr, iface, candidate) def verifyClass(iface, candidate, tentative=False): """ Verify that the *candidate* might correctly provide *iface*. """ return _verify(iface, candidate, tentative, vtype='c') def verifyObject(iface, candidate, tentative=False): return _verify(iface, candidate, tentative, vtype='o') verifyObject.__doc__ = _verify.__doc__ _MSG_TOO_MANY = 'implementation requires too many arguments' _KNOWN_PYPY2_FALSE_POSITIVES = frozenset(( _MSG_TOO_MANY, )) def _pypy2_false_positive(msg, candidate, vtype): # On PyPy2, builtin methods and functions like # ``dict.pop`` that take pseudo-optional arguments # (those with no default, something you can't express in Python 2 # syntax; CPython uses special internal APIs to implement these methods) # return false failures because PyPy2 doesn't expose any way # to detect this pseudo-optional status. PyPy3 doesn't have this problem # because of __defaults_count__, and CPython never gets here because it # returns true for ``ismethoddescriptor`` or ``isbuiltin``. # # We can't catch all such cases, but we can handle the common ones. # if msg not in _KNOWN_PYPY2_FALSE_POSITIVES: return False known_builtin_types = vars(__builtins__).values() candidate_type = candidate if vtype == 'c' else type(candidate) if candidate_type in known_builtin_types: return True return False def _incompat(required, implemented): #if (required['positional'] != # implemented['positional'][:len(required['positional'])] # and implemented['kwargs'] is None): # return 'imlementation has different argument names' if len(implemented['required']) > len(required['required']): return _MSG_TOO_MANY if ((len(implemented['positional']) < len(required['positional'])) and not implemented['varargs']): return "implementation doesn't allow enough arguments" if required['kwargs'] and not implemented['kwargs']: return "implementation doesn't support keyword arguments" if required['varargs'] and not implemented['varargs']: return "implementation doesn't support variable arguments"
src/zope/interface/verify.py
codereval_python_data_172
Verify that the *candidate* might correctly provide *iface*. def verifyClass(iface, candidate, tentative=False): """ Verify that the *candidate* might correctly provide *iface*. """ return _verify(iface, candidate, tentative, vtype='c') ############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Verify interface implementations """ from __future__ import print_function import inspect import sys from types import FunctionType from types import MethodType from zope.interface._compat import PYPY2 from zope.interface.exceptions import BrokenImplementation from zope.interface.exceptions import BrokenMethodImplementation from zope.interface.exceptions import DoesNotImplement from zope.interface.exceptions import Invalid from zope.interface.exceptions import MultipleInvalid from zope.interface.interface import fromMethod, fromFunction, Method __all__ = [ 'verifyObject', 'verifyClass', ] # This will be monkey-patched when running under Zope 2, so leave this # here: MethodTypes = (MethodType, ) def _verify(iface, candidate, tentative=False, vtype=None): """ Verify that *candidate* might correctly provide *iface*. This involves: - Making sure the candidate claims that it provides the interface using ``iface.providedBy`` (unless *tentative* is `True`, in which case this step is skipped). This means that the candidate's class declares that it `implements <zope.interface.implementer>` the interface, or the candidate itself declares that it `provides <zope.interface.provider>` the interface - Making sure the candidate defines all the necessary methods - Making sure the methods have the correct signature (to the extent possible) - Making sure the candidate defines all the necessary attributes :return bool: Returns a true value if everything that could be checked passed. :raises zope.interface.Invalid: If any of the previous conditions does not hold. .. versionchanged:: 5.0 If multiple methods or attributes are invalid, all such errors are collected and reported. Previously, only the first error was reported. As a special case, if only one such error is present, it is raised alone, like before. """ if vtype == 'c': tester = iface.implementedBy else: tester = iface.providedBy excs = [] if not tentative and not tester(candidate): excs.append(DoesNotImplement(iface, candidate)) for name, desc in iface.namesAndDescriptions(all=True): try: _verify_element(iface, name, desc, candidate, vtype) except Invalid as e: excs.append(e) if excs: if len(excs) == 1: raise excs[0] raise MultipleInvalid(iface, candidate, excs) return True def _verify_element(iface, name, desc, candidate, vtype): # Here the `desc` is either an `Attribute` or `Method` instance try: attr = getattr(candidate, name) except AttributeError: if (not isinstance(desc, Method)) and vtype == 'c': # We can't verify non-methods on classes, since the # class may provide attrs in it's __init__. return # TODO: On Python 3, this should use ``raise...from`` raise BrokenImplementation(iface, desc, candidate) if not isinstance(desc, Method): # If it's not a method, there's nothing else we can test return if inspect.ismethoddescriptor(attr) or inspect.isbuiltin(attr): # The first case is what you get for things like ``dict.pop`` # on CPython (e.g., ``verifyClass(IFullMapping, dict))``). The # second case is what you get for things like ``dict().pop`` on # CPython (e.g., ``verifyObject(IFullMapping, dict()))``. # In neither case can we get a signature, so there's nothing # to verify. Even the inspect module gives up and raises # ValueError: no signature found. The ``__text_signature__`` attribute # isn't typically populated either. # # Note that on PyPy 2 or 3 (up through 7.3 at least), these are # not true for things like ``dict.pop`` (but might be true for C extensions?) return if isinstance(attr, FunctionType): if sys.version_info[0] >= 3 and isinstance(candidate, type) and vtype == 'c': # This is an "unbound method" in Python 3. # Only unwrap this if we're verifying implementedBy; # otherwise we can unwrap @staticmethod on classes that directly # provide an interface. meth = fromFunction(attr, iface, name=name, imlevel=1) else: # Nope, just a normal function meth = fromFunction(attr, iface, name=name) elif (isinstance(attr, MethodTypes) and type(attr.__func__) is FunctionType): meth = fromMethod(attr, iface, name) elif isinstance(attr, property) and vtype == 'c': # Without an instance we cannot be sure it's not a # callable. # TODO: This should probably check inspect.isdatadescriptor(), # a more general form than ``property`` return else: if not callable(attr): raise BrokenMethodImplementation(desc, "implementation is not a method", attr, iface, candidate) # sigh, it's callable, but we don't know how to introspect it, so # we have to give it a pass. return # Make sure that the required and implemented method signatures are # the same. mess = _incompat(desc.getSignatureInfo(), meth.getSignatureInfo()) if mess: if PYPY2 and _pypy2_false_positive(mess, candidate, vtype): return raise BrokenMethodImplementation(desc, mess, attr, iface, candidate) def verifyClass(iface, candidate, tentative=False): """ Verify that the *candidate* might correctly provide *iface*. """ return _verify(iface, candidate, tentative, vtype='c') def verifyObject(iface, candidate, tentative=False): return _verify(iface, candidate, tentative, vtype='o') verifyObject.__doc__ = _verify.__doc__ _MSG_TOO_MANY = 'implementation requires too many arguments' _KNOWN_PYPY2_FALSE_POSITIVES = frozenset(( _MSG_TOO_MANY, )) def _pypy2_false_positive(msg, candidate, vtype): # On PyPy2, builtin methods and functions like # ``dict.pop`` that take pseudo-optional arguments # (those with no default, something you can't express in Python 2 # syntax; CPython uses special internal APIs to implement these methods) # return false failures because PyPy2 doesn't expose any way # to detect this pseudo-optional status. PyPy3 doesn't have this problem # because of __defaults_count__, and CPython never gets here because it # returns true for ``ismethoddescriptor`` or ``isbuiltin``. # # We can't catch all such cases, but we can handle the common ones. # if msg not in _KNOWN_PYPY2_FALSE_POSITIVES: return False known_builtin_types = vars(__builtins__).values() candidate_type = candidate if vtype == 'c' else type(candidate) if candidate_type in known_builtin_types: return True return False def _incompat(required, implemented): #if (required['positional'] != # implemented['positional'][:len(required['positional'])] # and implemented['kwargs'] is None): # return 'imlementation has different argument names' if len(implemented['required']) > len(required['required']): return _MSG_TOO_MANY if ((len(implemented['positional']) < len(required['positional'])) and not implemented['varargs']): return "implementation doesn't allow enough arguments" if required['kwargs'] and not implemented['kwargs']: return "implementation doesn't support keyword arguments" if required['varargs'] and not implemented['varargs']: return "implementation doesn't support variable arguments"
src/zope/interface/verify.py
codereval_python_data_173
Determine metaclass from 1+ bases and optional explicit __metaclass__ def determineMetaclass(bases, explicit_mc=None): """Determine metaclass from 1+ bases and optional explicit __metaclass__""" meta = [getattr(b,'__class__',type(b)) for b in bases] if explicit_mc is not None: # The explicit metaclass needs to be verified for compatibility # as well, and allowed to resolve the incompatible bases, if any meta.append(explicit_mc) if len(meta)==1: # easy case return meta[0] candidates = minimalBases(meta) # minimal set of metaclasses if not candidates: # pragma: no cover # they're all "classic" classes assert(not __python3) # This should not happen under Python 3 return ClassType elif len(candidates)>1: # We could auto-combine, but for now we won't... raise TypeError("Incompatible metatypes",bases) # Just one, return it return candidates[0] ############################################################################## # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Class advice. This module was adapted from 'protocols.advice', part of the Python Enterprise Application Kit (PEAK). Please notify the PEAK authors (pje@telecommunity.com and tsarna@sarna.org) if bugs are found or Zope-specific changes are required, so that the PEAK version of this module can be kept in sync. PEAK is a Python application framework that interoperates with (but does not require) Zope 3 and Twisted. It provides tools for manipulating UML models, object-relational persistence, aspect-oriented programming, and more. Visit the PEAK home page at http://peak.telecommunity.com for more information. """ from types import FunctionType try: from types import ClassType except ImportError: __python3 = True else: __python3 = False __all__ = [ 'addClassAdvisor', 'determineMetaclass', 'getFrameInfo', 'isClassAdvisor', 'minimalBases', ] import sys def getFrameInfo(frame): """Return (kind,module,locals,globals) for a frame 'kind' is one of "exec", "module", "class", "function call", or "unknown". """ f_locals = frame.f_locals f_globals = frame.f_globals sameNamespace = f_locals is f_globals hasModule = '__module__' in f_locals hasName = '__name__' in f_globals sameName = hasModule and hasName sameName = sameName and f_globals['__name__']==f_locals['__module__'] module = hasName and sys.modules.get(f_globals['__name__']) or None namespaceIsModule = module and module.__dict__ is f_globals if not namespaceIsModule: # some kind of funky exec kind = "exec" elif sameNamespace and not hasModule: kind = "module" elif sameName and not sameNamespace: kind = "class" elif not sameNamespace: kind = "function call" else: # pragma: no cover # How can you have f_locals is f_globals, and have '__module__' set? # This is probably module-level code, but with a '__module__' variable. kind = "unknown" return kind, module, f_locals, f_globals def addClassAdvisor(callback, depth=2): """Set up 'callback' to be passed the containing class upon creation This function is designed to be called by an "advising" function executed in a class suite. The "advising" function supplies a callback that it wishes to have executed when the containing class is created. The callback will be given one argument: the newly created containing class. The return value of the callback will be used in place of the class, so the callback should return the input if it does not wish to replace the class. The optional 'depth' argument to this function determines the number of frames between this function and the targeted class suite. 'depth' defaults to 2, since this skips this function's frame and one calling function frame. If you use this function from a function called directly in the class suite, the default will be correct, otherwise you will need to determine the correct depth yourself. This function works by installing a special class factory function in place of the '__metaclass__' of the containing class. Therefore, only callbacks *after* the last '__metaclass__' assignment in the containing class will be executed. Be sure that classes using "advising" functions declare any '__metaclass__' *first*, to ensure all callbacks are run.""" # This entire approach is invalid under Py3K. Don't even try to fix # the coverage for this block there. :( if __python3: # pragma: no cover raise TypeError('Class advice impossible in Python3') frame = sys._getframe(depth) kind, module, caller_locals, caller_globals = getFrameInfo(frame) # This causes a problem when zope interfaces are used from doctest. # In these cases, kind == "exec". # #if kind != "class": # raise SyntaxError( # "Advice must be in the body of a class statement" # ) previousMetaclass = caller_locals.get('__metaclass__') if __python3: # pragma: no cover defaultMetaclass = caller_globals.get('__metaclass__', type) else: defaultMetaclass = caller_globals.get('__metaclass__', ClassType) def advise(name, bases, cdict): if '__metaclass__' in cdict: del cdict['__metaclass__'] if previousMetaclass is None: if bases: # find best metaclass or use global __metaclass__ if no bases meta = determineMetaclass(bases) else: meta = defaultMetaclass elif isClassAdvisor(previousMetaclass): # special case: we can't compute the "true" metaclass here, # so we need to invoke the previous metaclass and let it # figure it out for us (and apply its own advice in the process) meta = previousMetaclass else: meta = determineMetaclass(bases, previousMetaclass) newClass = meta(name,bases,cdict) # this lets the callback replace the class completely, if it wants to return callback(newClass) # introspection data only, not used by inner function advise.previousMetaclass = previousMetaclass advise.callback = callback # install the advisor caller_locals['__metaclass__'] = advise def isClassAdvisor(ob): """True if 'ob' is a class advisor function""" return isinstance(ob,FunctionType) and hasattr(ob,'previousMetaclass') def determineMetaclass(bases, explicit_mc=None): """Determine metaclass from 1+ bases and optional explicit __metaclass__""" meta = [getattr(b,'__class__',type(b)) for b in bases] if explicit_mc is not None: # The explicit metaclass needs to be verified for compatibility # as well, and allowed to resolve the incompatible bases, if any meta.append(explicit_mc) if len(meta)==1: # easy case return meta[0] candidates = minimalBases(meta) # minimal set of metaclasses if not candidates: # pragma: no cover # they're all "classic" classes assert(not __python3) # This should not happen under Python 3 return ClassType elif len(candidates)>1: # We could auto-combine, but for now we won't... raise TypeError("Incompatible metatypes",bases) # Just one, return it return candidates[0] def minimalBases(classes): """Reduce a list of base classes to its ordered minimum equivalent""" if not __python3: # pragma: no cover classes = [c for c in classes if c is not ClassType] candidates = [] for m in classes: for n in classes: if issubclass(n,m) and m is not n: break else: # m has no subclasses in 'classes' if m in candidates: candidates.remove(m) # ensure that we're later in the list candidates.append(m) return candidates
src/zope/interface/advice.py
codereval_python_data_174
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. def pop(self, key, default=__marker): if key in self: value = self[key] del self[key] elif default is self.__marker: raise KeyError(key) else: value = default return value from collections.abc import MutableMapping class _DefaultSize(object): __slots__ = () def __getitem__(self, _): return 1 def __setitem__(self, _, value): assert value == 1 def pop(self, _): return 1 class Cache(MutableMapping): """Mutable mapping to serve as a simple cache or cache base class.""" __marker = object() __size = _DefaultSize() def __init__(self, maxsize, getsizeof=None): if getsizeof: self.getsizeof = getsizeof if self.getsizeof is not Cache.getsizeof: self.__size = dict() self.__data = dict() self.__currsize = 0 self.__maxsize = maxsize def __repr__(self): return '%s(%r, maxsize=%r, currsize=%r)' % ( self.__class__.__name__, list(self.__data.items()), self.__maxsize, self.__currsize, ) def __getitem__(self, key): try: return self.__data[key] except KeyError: return self.__missing__(key) def __setitem__(self, key, value): maxsize = self.__maxsize size = self.getsizeof(value) if size > maxsize: raise ValueError('value too large') if key not in self.__data or self.__size[key] < size: while self.__currsize + size > maxsize: self.popitem() if key in self.__data: diffsize = size - self.__size[key] else: diffsize = size self.__data[key] = value self.__size[key] = size self.__currsize += diffsize def __delitem__(self, key): size = self.__size.pop(key) del self.__data[key] self.__currsize -= size def __contains__(self, key): return key in self.__data def __missing__(self, key): raise KeyError(key) def __iter__(self): return iter(self.__data) def __len__(self): return len(self.__data) def get(self, key, default=None): if key in self: return self[key] else: return default def pop(self, key, default=__marker): if key in self: value = self[key] del self[key] elif default is self.__marker: raise KeyError(key) else: value = default return value def setdefault(self, key, default=None): if key in self: value = self[key] else: self[key] = value = default return value @property def maxsize(self): """The maximum size of the cache.""" return self.__maxsize @property def currsize(self): """The current size of the cache.""" return self.__currsize @staticmethod def getsizeof(value): """Return the size of a cache element's value.""" return 1
cachetools/cache.py
codereval_python_data_175
Remove and return the `(key, value)` pair least frequently used. def popitem(self): """Remove and return the `(key, value)` pair least frequently used.""" try: (key, _), = self.__counter.most_common(1) except ValueError: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key)) import collections from .cache import Cache class LFUCache(Cache): """Least Frequently Used (LFU) cache implementation.""" def __init__(self, maxsize, getsizeof=None): Cache.__init__(self, maxsize, getsizeof) self.__counter = collections.Counter() def __getitem__(self, key, cache_getitem=Cache.__getitem__): value = cache_getitem(self, key) if key in self: # __missing__ may not store item self.__counter[key] -= 1 return value def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): cache_setitem(self, key, value) self.__counter[key] -= 1 def __delitem__(self, key, cache_delitem=Cache.__delitem__): cache_delitem(self, key) del self.__counter[key] def popitem(self): """Remove and return the `(key, value)` pair least frequently used.""" try: (key, _), = self.__counter.most_common(1) except ValueError: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key))
cachetools/lfu.py
codereval_python_data_176
Remove and return the `(key, value)` pair least recently used. def popitem(self): """Remove and return the `(key, value)` pair least recently used.""" try: key = next(iter(self.__order)) except StopIteration: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key)) import collections from .cache import Cache class LRUCache(Cache): """Least Recently Used (LRU) cache implementation.""" def __init__(self, maxsize, getsizeof=None): Cache.__init__(self, maxsize, getsizeof) self.__order = collections.OrderedDict() def __getitem__(self, key, cache_getitem=Cache.__getitem__): value = cache_getitem(self, key) if key in self: # __missing__ may not store item self.__update(key) return value def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): cache_setitem(self, key, value) self.__update(key) def __delitem__(self, key, cache_delitem=Cache.__delitem__): cache_delitem(self, key) del self.__order[key] def popitem(self): """Remove and return the `(key, value)` pair least recently used.""" try: key = next(iter(self.__order)) except StopIteration: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key)) def __update(self, key): try: self.__order.move_to_end(key) except KeyError: self.__order[key] = None
cachetools/lru.py
codereval_python_data_177
Remove and return the `(key, value)` pair most recently used. def popitem(self): """Remove and return the `(key, value)` pair most recently used.""" try: key = next(iter(self.__order)) except StopIteration: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key)) import collections from cachetools.cache import Cache class MRUCache(Cache): """Most Recently Used (MRU) cache implementation.""" def __init__(self, maxsize, getsizeof=None): Cache.__init__(self, maxsize, getsizeof) self.__order = collections.OrderedDict() def __getitem__(self, key, cache_getitem=Cache.__getitem__): value = cache_getitem(self, key) if key in self: # __missing__ may not store item self.__update(key) return value def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): cache_setitem(self, key, value) self.__update(key) def __delitem__(self, key, cache_delitem=Cache.__delitem__): cache_delitem(self, key) del self.__order[key] def popitem(self): """Remove and return the `(key, value)` pair most recently used.""" try: key = next(iter(self.__order)) except StopIteration: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key)) def __update(self, key): try: self.__order.move_to_end(key, last=False) except KeyError: self.__order[key] = None
cachetools/mru.py
codereval_python_data_178
Remove and return a random `(key, value)` pair. def popitem(self): """Remove and return a random `(key, value)` pair.""" try: key = self.__choice(list(self)) except IndexError: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key)) import random from .cache import Cache # random.choice cannot be pickled in Python 2.7 def _choice(seq): return random.choice(seq) class RRCache(Cache): """Random Replacement (RR) cache implementation.""" def __init__(self, maxsize, choice=random.choice, getsizeof=None): Cache.__init__(self, maxsize, getsizeof) # TODO: use None as default, assing to self.choice directly? if choice is random.choice: self.__choice = _choice else: self.__choice = choice @property def choice(self): """The `choice` function used by the cache.""" return self.__choice def popitem(self): """Remove and return a random `(key, value)` pair.""" try: key = self.__choice(list(self)) except IndexError: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key))
cachetools/rr.py
codereval_python_data_179
Create the in-style parameter regular expression. Returns the in-style parameter regular expression (:class:`re.Pattern`). def _create_in_regex(self) -> Pattern: """ Create the in-style parameter regular expression. Returns the in-style parameter regular expression (:class:`re.Pattern`). """ regex_parts = [] if self._in_obj.escape_char != "%" and self._out_obj.escape_char == "%": regex_parts.append("(?P<out_percent>%)") if self._escape_char: # Escaping is enabled. escape = self._in_obj.escape_regex.format(char=re.escape(self._escape_char)) regex_parts.append(escape) regex_parts.append(self._in_obj.param_regex) return re.compile("|".join(regex_parts)) """ :mod:`sqlparams` is a utility package for converting between various SQL parameter styles. """ import re from typing import ( Any, AnyStr, Dict, Iterable, List, Optional, Pattern, Sequence, Tuple, Type, Union) from . import _converting from . import _styles from ._util import _is_iterable from ._meta import ( __author__, __copyright__, __credits__, __license__, __version__, ) _BYTES_ENCODING = 'latin1' """ The encoding to use when parsing a byte query string. """ _STYLES = {} """ Maps parameter style by name. """ class SQLParams(object): """ The :class:`.SQLParams` class is used to support named parameters in SQL queries where they are not otherwise supported (e.g., pyodbc). This is done by converting from one parameter style query to another parameter style query. By default, when converting to a numeric or ordinal style any :class:`tuple` parameter will be expanded into "(?,?,...)" to support the widely used "IN {tuple}" SQL expression without leaking any unescaped values. """ def __init__( self, in_style: str, out_style: str, escape_char: Union[str, bool, None] = None, expand_tuples: Optional[bool] = None, ) -> None: """ Instantiates the :class:`.SQLParams` instance. *in_style* (:class:`str`) is the parameter style that will be used in an SQL query before being parsed and converted to :attr:`.SQLParams.out_style`. *out_style* (:class:`str`) is the parameter style that the SQL query will be converted to. *escape_char* (:class:`str`, :class:`bool`, or :data:`None`) is the escape character used to prevent matching a in-style parameter. If :data:`True`, use the default escape character (repeat the initial character to escape it; e.g., "%%"). If :data:`False`, do not use an escape character. Default is :data:`None` for :data:`False`. *expand_tuples* (:class:`bool` or :data:`None`) is whether to expand tuples into a sequence of parameters. Default is :data:`None` to let it be determined by *out_style* (to maintain backward compatibility). If *out_style* is a numeric or ordinal style, expand tuples by default (:data:`True`). If *out_style* is a named style, do not expand tuples by default (:data:`False`). The following parameter styles are supported by both *in_style* and *out_style*: - For all named styles the parameter keys must be valid `Python identifiers`_. They cannot start with a digit. This is to help prevent incorrectly matching common strings such as datetimes. Named styles: - "named" indicates parameters will use the named style:: ... WHERE name = :name - "named_dollar" indicates parameters will use the named dollar sign style:: ... WHERE name = $name .. NOTE:: This is not defined by `PEP 249`_. - "pyformat" indicates parameters will use the named Python extended format style:: ... WHERE name = %(name)s .. NOTE:: Strictly speaking, `PEP 249`_ only specifies "%(name)s" for the "pyformat" parameter style so only that form (without any other conversions or flags) is supported. - All numeric styles start at :data:`1`. When using a :class:`~collections.abc.Sequence` for the parameters, the 1st parameter (e.g., ":1") will correspond to the 1st element of the sequence (i.e., index :data:`0`). When using a :class:`~collections.abc.Mapping` for the parameters, the 1st parameter (e.g., ":1") will correspond to the matching key (i.e., :data:`1` or :data:`"1"`). Numeric styles: - "numeric" indicates parameters will use the numeric style:: ... WHERE name = :1 - "numeric_dollar" indicates parameters will use the numeric dollar sign style (starts at :data:`1`):: ... WHERE name = $1 .. NOTE:: This is not defined by `PEP 249`_. - Ordinal styles: - "format" indicates parameters will use the ordinal Python format style:: ... WHERE name = %s .. NOTE:: Strictly speaking, `PEP 249`_ only specifies "%s" for the "format" parameter styles so only that form (without any other conversions or flags) is supported. - "qmark" indicates parameters will use the ordinal question mark style:: ... WHERE name = ? .. _`PEP 249`: http://www.python.org/dev/peps/pep-0249/ .. _`Python identifiers`: https://docs.python.org/3/reference/lexical_analysis.html#identifiers """ self._converter: _converting._Converter = None """ *_converter* (:class:`._converting._Converter`) is the parameter converter to use. """ self._escape_char: Optional[str] = None """ *_escape_char* (:class:`str` or :data:`None`) is the escape character used to prevent matching a in-style parameter. """ self._expand_tuples: bool = None """ *_expand_tuples* (:class:`bool`) is whether to convert tuples into a sequence of parameters. """ self._in_obj: _styles._Style = None """ *_in_obj* (:class:`._styles._Style`) is the in-style parameter object. """ self._in_regex: Pattern = None """ *_in_regex* (:class:`re.Pattern`) is the regular expression used to extract the in-style parameters. """ self._in_style: str = None """ *_in_style* (:class:`str`) is the parameter style that will be used in an SQL query before being parsed and converted to :attr:`.SQLParams.out_style`. """ self._out_obj: _styles._Style = None """ *_out_obj* (:class:`._styles._Style`) is the out-style parameter object. """ self._out_style: str = None """ *_out_style* (:class:`str`) is the parameter style that the SQL query will be converted to. """ if not isinstance(in_style, str): raise TypeError("in_style:{!r} is not a string.".format(in_style)) if not isinstance(out_style, str): raise TypeError("out_style:{!r} is not a string.".format(out_style)) self._in_style = in_style self._out_style = out_style self._in_obj = _styles._STYLES[self._in_style] self._out_obj = _styles._STYLES[self._out_style] if escape_char is True: use_char = self._in_obj.escape_char elif not escape_char: use_char = None elif isinstance(escape_char, str): use_char = escape_char else: raise TypeError("escape_char:{!r} is not a string or bool.") if expand_tuples is None: expand_tuples = not isinstance(self._out_obj, _styles._NamedStyle) self._escape_char = use_char self._expand_tuples = bool(expand_tuples) self._in_regex = self._create_in_regex() self._converter = self._create_converter() def __repr__(self) -> str: """ Returns the canonical string representation (:class:`str`) of this instance. """ return "{}.{}({!r}, {!r})".format(self.__class__.__module__, self.__class__.__name__, self._in_style, self._out_style) def _create_converter(self) -> _converting._Converter: """ Create the parameter style converter. Returns the parameter style converter (:class:`._converting._Converter`). """ assert self._in_regex is not None, self._in_regex assert self._out_obj is not None, self._out_obj # Determine converter class. converter_class: Type[_converting._Converter] if isinstance(self._in_obj, _styles._NamedStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._NamedToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._NamedToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._NamedToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) elif isinstance(self._in_obj, _styles._NumericStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._NumericToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._NumericToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._NumericToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) elif isinstance(self._in_obj, _styles._OrdinalStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._OrdinalToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._OrdinalToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._OrdinalToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) else: raise TypeError("in_style:{!r} maps to an unexpected type: {!r}".format(self._in_style, self._in_obj)) # Create converter. converter = converter_class( escape_char=self._escape_char, expand_tuples=self._expand_tuples, in_regex=self._in_regex, in_style=self._in_obj, out_style=self._out_obj, ) return converter def _create_in_regex(self) -> Pattern: """ Create the in-style parameter regular expression. Returns the in-style parameter regular expression (:class:`re.Pattern`). """ regex_parts = [] if self._in_obj.escape_char != "%" and self._out_obj.escape_char == "%": regex_parts.append("(?P<out_percent>%)") if self._escape_char: # Escaping is enabled. escape = self._in_obj.escape_regex.format(char=re.escape(self._escape_char)) regex_parts.append(escape) regex_parts.append(self._in_obj.param_regex) return re.compile("|".join(regex_parts)) @property def escape_char(self) -> Optional[str]: """ *escape_char* (:class:`str` or :data:`None`) is the escape character used to prevent matching a in-style parameter. """ return self._escape_char @property def expand_tuples(self) -> bool: """ *expand_tuples* (:class:`bool`) is whether to convert tuples into a sequence of parameters. """ return self._expand_tuples def format( self, sql: AnyStr, params: Union[Dict[Union[str, int], Any], Sequence[Any]], ) -> Tuple[AnyStr, Union[Dict[Union[str, int], Any], Sequence[Any]]]: """ Convert the SQL query to use the out-style parameters instead of the in-style parameters. *sql* (:class:`str` or :class:`bytes`) is the SQL query. *params* (:class:`~collections.abc.Mapping` or :class:`~collections.abc.Sequence`) contains the set of in-style parameters. It maps each parameter (:class:`str` or :class:`int`) to value. If :attr:`.SQLParams.in_style` is a named parameter style. then *params* must be a :class:`~collections.abc.Mapping`. If :attr:`.SQLParams.in_style` is an ordinal parameter style, then *params* must be a :class:`~collections.abc.Sequence`. Returns a :class:`tuple` containing: - The formatted SQL query (:class:`str` or :class:`bytes`). - The set of converted out-style parameters (:class:`dict` or :class:`list`). """ # Normalize query encoding to simplify processing. if isinstance(sql, str): use_sql = sql string_type = str elif isinstance(sql, bytes): use_sql = sql.decode(_BYTES_ENCODING) string_type = bytes else: raise TypeError("sql:{!r} is not a unicode or byte string.".format(sql)) # Replace in-style with out-style parameters. use_sql, out_params = self._converter.convert(use_sql, params) # Make sure the query is returned as the proper string type. if string_type is bytes: out_sql = use_sql.encode(_BYTES_ENCODING) else: out_sql = use_sql # Return converted SQL and out-parameters. return out_sql, out_params def formatmany( self, sql: AnyStr, many_params: Union[Iterable[Dict[Union[str, int], Any]], Iterable[Sequence[Any]]], ) -> Tuple[AnyStr, Union[List[Dict[Union[str, int], Any]], List[Sequence[Any]]]]: """ Convert the SQL query to use the out-style parameters instead of the in-style parameters. *sql* (:class:`str` or :class:`bytes`) is the SQL query. *many_params* (:class:`~collections.abc.Iterable`) contains each set of in-style parameters (*params*). - *params* (:class:`~collections.abc.Mapping` or :class:`~collections.abc.Sequence`) contains the set of in-style parameters. It maps each parameter (:class:`str` or :class:`int`) to value. If :attr:`.SQLParams.in_style` is a named parameter style. then *params* must be a :class:`~collections.abc.Mapping`. If :attr:`.SQLParams.in_style` is an ordinal parameter style. then *params* must be a :class:`~collections.abc.Sequence`. Returns a :class:`tuple` containing: - The formatted SQL query (:class:`str` or :class:`bytes`). - A :class:`list` containing each set of converted out-style parameters (:class:`dict` or :class:`list`). """ # Normalize query encoding to simplify processing. if isinstance(sql, str): use_sql = sql string_type = str elif isinstance(sql, bytes): use_sql = sql.decode(_BYTES_ENCODING) string_type = bytes else: raise TypeError("sql:{!r} is not a unicode or byte string.".format(sql)) if not _is_iterable(many_params): raise TypeError("many_params:{!r} is not iterable.".format(many_params)) # Replace in-style with out-style parameters. use_sql, many_out_params = self._converter.convert_many(use_sql, many_params) # Make sure the query is returned as the proper string type. if string_type is bytes: out_sql = use_sql.encode(_BYTES_ENCODING) else: out_sql = use_sql # Return converted SQL and out-parameters. return out_sql, many_out_params @property def in_style(self) -> str: """ *in_style* (:class:`str`) is the parameter style to expect in an SQL query when being parsed. """ return self._in_style @property def out_style(self) -> str: """ *out_style* (:class:`str`) is the parameter style that the SQL query will be converted to. """ return self._out_style
sqlparams/__init__.py
codereval_python_data_180
Create the parameter style converter. Returns the parameter style converter (:class:`._converting._Converter`). def _create_converter(self) -> _converting._Converter: """ Create the parameter style converter. Returns the parameter style converter (:class:`._converting._Converter`). """ assert self._in_regex is not None, self._in_regex assert self._out_obj is not None, self._out_obj # Determine converter class. converter_class: Type[_converting._Converter] if isinstance(self._in_obj, _styles._NamedStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._NamedToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._NamedToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._NamedToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) elif isinstance(self._in_obj, _styles._NumericStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._NumericToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._NumericToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._NumericToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) elif isinstance(self._in_obj, _styles._OrdinalStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._OrdinalToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._OrdinalToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._OrdinalToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) else: raise TypeError("in_style:{!r} maps to an unexpected type: {!r}".format(self._in_style, self._in_obj)) # Create converter. converter = converter_class( escape_char=self._escape_char, expand_tuples=self._expand_tuples, in_regex=self._in_regex, in_style=self._in_obj, out_style=self._out_obj, ) return converter """ :mod:`sqlparams` is a utility package for converting between various SQL parameter styles. """ import re from typing import ( Any, AnyStr, Dict, Iterable, List, Optional, Pattern, Sequence, Tuple, Type, Union) from . import _converting from . import _styles from ._util import _is_iterable from ._meta import ( __author__, __copyright__, __credits__, __license__, __version__, ) _BYTES_ENCODING = 'latin1' """ The encoding to use when parsing a byte query string. """ _STYLES = {} """ Maps parameter style by name. """ class SQLParams(object): """ The :class:`.SQLParams` class is used to support named parameters in SQL queries where they are not otherwise supported (e.g., pyodbc). This is done by converting from one parameter style query to another parameter style query. By default, when converting to a numeric or ordinal style any :class:`tuple` parameter will be expanded into "(?,?,...)" to support the widely used "IN {tuple}" SQL expression without leaking any unescaped values. """ def __init__( self, in_style: str, out_style: str, escape_char: Union[str, bool, None] = None, expand_tuples: Optional[bool] = None, ) -> None: """ Instantiates the :class:`.SQLParams` instance. *in_style* (:class:`str`) is the parameter style that will be used in an SQL query before being parsed and converted to :attr:`.SQLParams.out_style`. *out_style* (:class:`str`) is the parameter style that the SQL query will be converted to. *escape_char* (:class:`str`, :class:`bool`, or :data:`None`) is the escape character used to prevent matching a in-style parameter. If :data:`True`, use the default escape character (repeat the initial character to escape it; e.g., "%%"). If :data:`False`, do not use an escape character. Default is :data:`None` for :data:`False`. *expand_tuples* (:class:`bool` or :data:`None`) is whether to expand tuples into a sequence of parameters. Default is :data:`None` to let it be determined by *out_style* (to maintain backward compatibility). If *out_style* is a numeric or ordinal style, expand tuples by default (:data:`True`). If *out_style* is a named style, do not expand tuples by default (:data:`False`). The following parameter styles are supported by both *in_style* and *out_style*: - For all named styles the parameter keys must be valid `Python identifiers`_. They cannot start with a digit. This is to help prevent incorrectly matching common strings such as datetimes. Named styles: - "named" indicates parameters will use the named style:: ... WHERE name = :name - "named_dollar" indicates parameters will use the named dollar sign style:: ... WHERE name = $name .. NOTE:: This is not defined by `PEP 249`_. - "pyformat" indicates parameters will use the named Python extended format style:: ... WHERE name = %(name)s .. NOTE:: Strictly speaking, `PEP 249`_ only specifies "%(name)s" for the "pyformat" parameter style so only that form (without any other conversions or flags) is supported. - All numeric styles start at :data:`1`. When using a :class:`~collections.abc.Sequence` for the parameters, the 1st parameter (e.g., ":1") will correspond to the 1st element of the sequence (i.e., index :data:`0`). When using a :class:`~collections.abc.Mapping` for the parameters, the 1st parameter (e.g., ":1") will correspond to the matching key (i.e., :data:`1` or :data:`"1"`). Numeric styles: - "numeric" indicates parameters will use the numeric style:: ... WHERE name = :1 - "numeric_dollar" indicates parameters will use the numeric dollar sign style (starts at :data:`1`):: ... WHERE name = $1 .. NOTE:: This is not defined by `PEP 249`_. - Ordinal styles: - "format" indicates parameters will use the ordinal Python format style:: ... WHERE name = %s .. NOTE:: Strictly speaking, `PEP 249`_ only specifies "%s" for the "format" parameter styles so only that form (without any other conversions or flags) is supported. - "qmark" indicates parameters will use the ordinal question mark style:: ... WHERE name = ? .. _`PEP 249`: http://www.python.org/dev/peps/pep-0249/ .. _`Python identifiers`: https://docs.python.org/3/reference/lexical_analysis.html#identifiers """ self._converter: _converting._Converter = None """ *_converter* (:class:`._converting._Converter`) is the parameter converter to use. """ self._escape_char: Optional[str] = None """ *_escape_char* (:class:`str` or :data:`None`) is the escape character used to prevent matching a in-style parameter. """ self._expand_tuples: bool = None """ *_expand_tuples* (:class:`bool`) is whether to convert tuples into a sequence of parameters. """ self._in_obj: _styles._Style = None """ *_in_obj* (:class:`._styles._Style`) is the in-style parameter object. """ self._in_regex: Pattern = None """ *_in_regex* (:class:`re.Pattern`) is the regular expression used to extract the in-style parameters. """ self._in_style: str = None """ *_in_style* (:class:`str`) is the parameter style that will be used in an SQL query before being parsed and converted to :attr:`.SQLParams.out_style`. """ self._out_obj: _styles._Style = None """ *_out_obj* (:class:`._styles._Style`) is the out-style parameter object. """ self._out_style: str = None """ *_out_style* (:class:`str`) is the parameter style that the SQL query will be converted to. """ if not isinstance(in_style, str): raise TypeError("in_style:{!r} is not a string.".format(in_style)) if not isinstance(out_style, str): raise TypeError("out_style:{!r} is not a string.".format(out_style)) self._in_style = in_style self._out_style = out_style self._in_obj = _styles._STYLES[self._in_style] self._out_obj = _styles._STYLES[self._out_style] if escape_char is True: use_char = self._in_obj.escape_char elif not escape_char: use_char = None elif isinstance(escape_char, str): use_char = escape_char else: raise TypeError("escape_char:{!r} is not a string or bool.") if expand_tuples is None: expand_tuples = not isinstance(self._out_obj, _styles._NamedStyle) self._escape_char = use_char self._expand_tuples = bool(expand_tuples) self._in_regex = self._create_in_regex() self._converter = self._create_converter() def __repr__(self) -> str: """ Returns the canonical string representation (:class:`str`) of this instance. """ return "{}.{}({!r}, {!r})".format(self.__class__.__module__, self.__class__.__name__, self._in_style, self._out_style) def _create_converter(self) -> _converting._Converter: """ Create the parameter style converter. Returns the parameter style converter (:class:`._converting._Converter`). """ assert self._in_regex is not None, self._in_regex assert self._out_obj is not None, self._out_obj # Determine converter class. converter_class: Type[_converting._Converter] if isinstance(self._in_obj, _styles._NamedStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._NamedToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._NamedToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._NamedToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) elif isinstance(self._in_obj, _styles._NumericStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._NumericToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._NumericToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._NumericToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) elif isinstance(self._in_obj, _styles._OrdinalStyle): if isinstance(self._out_obj, _styles._NamedStyle): converter_class = _converting._OrdinalToNamedConverter elif isinstance(self._out_obj, _styles._NumericStyle): converter_class = _converting._OrdinalToNumericConverter elif isinstance(self._out_obj, _styles._OrdinalStyle): converter_class = _converting._OrdinalToOrdinalConverter else: raise TypeError("out_style:{!r} maps to an unexpected type: {!r}".format(self._out_style, self._out_obj)) else: raise TypeError("in_style:{!r} maps to an unexpected type: {!r}".format(self._in_style, self._in_obj)) # Create converter. converter = converter_class( escape_char=self._escape_char, expand_tuples=self._expand_tuples, in_regex=self._in_regex, in_style=self._in_obj, out_style=self._out_obj, ) return converter def _create_in_regex(self) -> Pattern: """ Create the in-style parameter regular expression. Returns the in-style parameter regular expression (:class:`re.Pattern`). """ regex_parts = [] if self._in_obj.escape_char != "%" and self._out_obj.escape_char == "%": regex_parts.append("(?P<out_percent>%)") if self._escape_char: # Escaping is enabled. escape = self._in_obj.escape_regex.format(char=re.escape(self._escape_char)) regex_parts.append(escape) regex_parts.append(self._in_obj.param_regex) return re.compile("|".join(regex_parts)) @property def escape_char(self) -> Optional[str]: """ *escape_char* (:class:`str` or :data:`None`) is the escape character used to prevent matching a in-style parameter. """ return self._escape_char @property def expand_tuples(self) -> bool: """ *expand_tuples* (:class:`bool`) is whether to convert tuples into a sequence of parameters. """ return self._expand_tuples def format( self, sql: AnyStr, params: Union[Dict[Union[str, int], Any], Sequence[Any]], ) -> Tuple[AnyStr, Union[Dict[Union[str, int], Any], Sequence[Any]]]: """ Convert the SQL query to use the out-style parameters instead of the in-style parameters. *sql* (:class:`str` or :class:`bytes`) is the SQL query. *params* (:class:`~collections.abc.Mapping` or :class:`~collections.abc.Sequence`) contains the set of in-style parameters. It maps each parameter (:class:`str` or :class:`int`) to value. If :attr:`.SQLParams.in_style` is a named parameter style. then *params* must be a :class:`~collections.abc.Mapping`. If :attr:`.SQLParams.in_style` is an ordinal parameter style, then *params* must be a :class:`~collections.abc.Sequence`. Returns a :class:`tuple` containing: - The formatted SQL query (:class:`str` or :class:`bytes`). - The set of converted out-style parameters (:class:`dict` or :class:`list`). """ # Normalize query encoding to simplify processing. if isinstance(sql, str): use_sql = sql string_type = str elif isinstance(sql, bytes): use_sql = sql.decode(_BYTES_ENCODING) string_type = bytes else: raise TypeError("sql:{!r} is not a unicode or byte string.".format(sql)) # Replace in-style with out-style parameters. use_sql, out_params = self._converter.convert(use_sql, params) # Make sure the query is returned as the proper string type. if string_type is bytes: out_sql = use_sql.encode(_BYTES_ENCODING) else: out_sql = use_sql # Return converted SQL and out-parameters. return out_sql, out_params def formatmany( self, sql: AnyStr, many_params: Union[Iterable[Dict[Union[str, int], Any]], Iterable[Sequence[Any]]], ) -> Tuple[AnyStr, Union[List[Dict[Union[str, int], Any]], List[Sequence[Any]]]]: """ Convert the SQL query to use the out-style parameters instead of the in-style parameters. *sql* (:class:`str` or :class:`bytes`) is the SQL query. *many_params* (:class:`~collections.abc.Iterable`) contains each set of in-style parameters (*params*). - *params* (:class:`~collections.abc.Mapping` or :class:`~collections.abc.Sequence`) contains the set of in-style parameters. It maps each parameter (:class:`str` or :class:`int`) to value. If :attr:`.SQLParams.in_style` is a named parameter style. then *params* must be a :class:`~collections.abc.Mapping`. If :attr:`.SQLParams.in_style` is an ordinal parameter style. then *params* must be a :class:`~collections.abc.Sequence`. Returns a :class:`tuple` containing: - The formatted SQL query (:class:`str` or :class:`bytes`). - A :class:`list` containing each set of converted out-style parameters (:class:`dict` or :class:`list`). """ # Normalize query encoding to simplify processing. if isinstance(sql, str): use_sql = sql string_type = str elif isinstance(sql, bytes): use_sql = sql.decode(_BYTES_ENCODING) string_type = bytes else: raise TypeError("sql:{!r} is not a unicode or byte string.".format(sql)) if not _is_iterable(many_params): raise TypeError("many_params:{!r} is not iterable.".format(many_params)) # Replace in-style with out-style parameters. use_sql, many_out_params = self._converter.convert_many(use_sql, many_params) # Make sure the query is returned as the proper string type. if string_type is bytes: out_sql = use_sql.encode(_BYTES_ENCODING) else: out_sql = use_sql # Return converted SQL and out-parameters. return out_sql, many_out_params @property def in_style(self) -> str: """ *in_style* (:class:`str`) is the parameter style to expect in an SQL query when being parsed. """ return self._in_style @property def out_style(self) -> str: """ *out_style* (:class:`str`) is the parameter style that the SQL query will be converted to. """ return self._out_style
sqlparams/__init__.py
codereval_python_data_181
Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. An ISO-8601 datetime string consists of a date portion, followed optionally by a time portion - the date and time portions are separated by a single character separator, which is ``T`` in the official standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be combined with a time portion. Supported date formats are: Common: - ``YYYY`` - ``YYYY-MM`` or ``YYYYMM`` - ``YYYY-MM-DD`` or ``YYYYMMDD`` Uncommon: - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day The ISO week and day numbering follows the same logic as :func:`datetime.date.isocalendar`. Supported time formats are: - ``hh`` - ``hh:mm`` or ``hhmm`` - ``hh:mm:ss`` or ``hhmmss`` - ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits) Midnight is a special case for `hh`, as the standard supports both 00:00 and 24:00 as a representation. The decimal separator can be either a dot or a comma. .. caution:: Support for fractional components other than seconds is part of the ISO-8601 standard, but is not currently implemented in this parser. Supported time zone offset formats are: - `Z` (UTC) - `±HH:MM` - `±HHMM` - `±HH` Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, with the exception of UTC, which will be represented as :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. :param dt_str: A string or stream containing only an ISO-8601 datetime string :return: Returns a :class:`datetime.datetime` representing the string. Unspecified components default to their lowest value. .. warning:: As of version 2.7.0, the strictness of the parser should not be considered a stable part of the contract. Any valid ISO-8601 string that parses correctly with the default settings will continue to parse correctly in future versions, but invalid strings that currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not guaranteed to continue failing in future versions if they encode a valid date. .. versionadded:: 2.7.0 @_takes_ascii def isoparse(self, dt_str): """ Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. An ISO-8601 datetime string consists of a date portion, followed optionally by a time portion - the date and time portions are separated by a single character separator, which is ``T`` in the official standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be combined with a time portion. Supported date formats are: Common: - ``YYYY`` - ``YYYY-MM`` or ``YYYYMM`` - ``YYYY-MM-DD`` or ``YYYYMMDD`` Uncommon: - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day The ISO week and day numbering follows the same logic as :func:`datetime.date.isocalendar`. Supported time formats are: - ``hh`` - ``hh:mm`` or ``hhmm`` - ``hh:mm:ss`` or ``hhmmss`` - ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits) Midnight is a special case for `hh`, as the standard supports both 00:00 and 24:00 as a representation. The decimal separator can be either a dot or a comma. .. caution:: Support for fractional components other than seconds is part of the ISO-8601 standard, but is not currently implemented in this parser. Supported time zone offset formats are: - `Z` (UTC) - `±HH:MM` - `±HHMM` - `±HH` Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, with the exception of UTC, which will be represented as :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. :param dt_str: A string or stream containing only an ISO-8601 datetime string :return: Returns a :class:`datetime.datetime` representing the string. Unspecified components default to their lowest value. .. warning:: As of version 2.7.0, the strictness of the parser should not be considered a stable part of the contract. Any valid ISO-8601 string that parses correctly with the default settings will continue to parse correctly in future versions, but invalid strings that currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not guaranteed to continue failing in future versions if they encode a valid date. .. versionadded:: 2.7.0 """ components, pos = self._parse_isodate(dt_str) if len(dt_str) > pos: if self._sep is None or dt_str[pos:pos + 1] == self._sep: components += self._parse_isotime(dt_str[pos + 1:]) else: raise ValueError('String contains unknown ISO components') if len(components) > 3 and components[3] == 24: components[3] = 0 return datetime(*components) + timedelta(days=1) return datetime(*components) # -*- coding: utf-8 -*- """ This module offers a parser for ISO-8601 strings It is intended to support all valid date, time and datetime formats per the ISO-8601 specification. ..versionadded:: 2.7.0 """ from datetime import datetime, timedelta, time, date import calendar from dateutil import tz from functools import wraps import re import six __all__ = ["isoparse", "isoparser"] def _takes_ascii(f): @wraps(f) def func(self, str_in, *args, **kwargs): # If it's a stream, read the whole thing str_in = getattr(str_in, 'read', lambda: str_in)() # If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII if isinstance(str_in, six.text_type): # ASCII is the same in UTF-8 try: str_in = str_in.encode('ascii') except UnicodeEncodeError as e: msg = 'ISO-8601 strings should contain only ASCII characters' six.raise_from(ValueError(msg), e) return f(self, str_in, *args, **kwargs) return func class isoparser(object): def __init__(self, sep=None): """ :param sep: A single character that separates date and time portions. If ``None``, the parser will accept any single character. For strict ISO-8601 adherence, pass ``'T'``. """ if sep is not None: if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'): raise ValueError('Separator must be a single, non-numeric ' + 'ASCII character') sep = sep.encode('ascii') self._sep = sep @_takes_ascii def isoparse(self, dt_str): """ Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. An ISO-8601 datetime string consists of a date portion, followed optionally by a time portion - the date and time portions are separated by a single character separator, which is ``T`` in the official standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be combined with a time portion. Supported date formats are: Common: - ``YYYY`` - ``YYYY-MM`` or ``YYYYMM`` - ``YYYY-MM-DD`` or ``YYYYMMDD`` Uncommon: - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day The ISO week and day numbering follows the same logic as :func:`datetime.date.isocalendar`. Supported time formats are: - ``hh`` - ``hh:mm`` or ``hhmm`` - ``hh:mm:ss`` or ``hhmmss`` - ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits) Midnight is a special case for `hh`, as the standard supports both 00:00 and 24:00 as a representation. The decimal separator can be either a dot or a comma. .. caution:: Support for fractional components other than seconds is part of the ISO-8601 standard, but is not currently implemented in this parser. Supported time zone offset formats are: - `Z` (UTC) - `±HH:MM` - `±HHMM` - `±HH` Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, with the exception of UTC, which will be represented as :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. :param dt_str: A string or stream containing only an ISO-8601 datetime string :return: Returns a :class:`datetime.datetime` representing the string. Unspecified components default to their lowest value. .. warning:: As of version 2.7.0, the strictness of the parser should not be considered a stable part of the contract. Any valid ISO-8601 string that parses correctly with the default settings will continue to parse correctly in future versions, but invalid strings that currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not guaranteed to continue failing in future versions if they encode a valid date. .. versionadded:: 2.7.0 """ components, pos = self._parse_isodate(dt_str) if len(dt_str) > pos: if self._sep is None or dt_str[pos:pos + 1] == self._sep: components += self._parse_isotime(dt_str[pos + 1:]) else: raise ValueError('String contains unknown ISO components') if len(components) > 3 and components[3] == 24: components[3] = 0 return datetime(*components) + timedelta(days=1) return datetime(*components) @_takes_ascii def parse_isodate(self, datestr): """ Parse the date portion of an ISO string. :param datestr: The string portion of an ISO string, without a separator :return: Returns a :class:`datetime.date` object """ components, pos = self._parse_isodate(datestr) if pos < len(datestr): raise ValueError('String contains unknown ISO ' + 'components: {}'.format(datestr)) return date(*components) @_takes_ascii def parse_isotime(self, timestr): """ Parse the time portion of an ISO string. :param timestr: The time portion of an ISO string, without a separator :return: Returns a :class:`datetime.time` object """ components = self._parse_isotime(timestr) if components[0] == 24: components[0] = 0 return time(*components) @_takes_ascii def parse_tzstr(self, tzstr, zero_as_utc=True): """ Parse a valid ISO time zone string. See :func:`isoparser.isoparse` for details on supported formats. :param tzstr: A string representing an ISO time zone offset :param zero_as_utc: Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones :return: Returns :class:`dateutil.tz.tzoffset` for offsets and :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is specified) offsets equivalent to UTC. """ return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) # Constants _DATE_SEP = b'-' _TIME_SEP = b':' _FRACTION_REGEX = re.compile(b'[\\.,]([0-9]+)') def _parse_isodate(self, dt_str): try: return self._parse_isodate_common(dt_str) except ValueError: return self._parse_isodate_uncommon(dt_str) def _parse_isodate_common(self, dt_str): len_str = len(dt_str) components = [1, 1, 1] if len_str < 4: raise ValueError('ISO string too short') # Year components[0] = int(dt_str[0:4]) pos = 4 if pos >= len_str: return components, pos has_sep = dt_str[pos:pos + 1] == self._DATE_SEP if has_sep: pos += 1 # Month if len_str - pos < 2: raise ValueError('Invalid common month') components[1] = int(dt_str[pos:pos + 2]) pos += 2 if pos >= len_str: if has_sep: return components, pos else: raise ValueError('Invalid ISO format') if has_sep: if dt_str[pos:pos + 1] != self._DATE_SEP: raise ValueError('Invalid separator in ISO string') pos += 1 # Day if len_str - pos < 2: raise ValueError('Invalid common day') components[2] = int(dt_str[pos:pos + 2]) return components, pos + 2 def _parse_isodate_uncommon(self, dt_str): if len(dt_str) < 4: raise ValueError('ISO string too short') # All ISO formats start with the year year = int(dt_str[0:4]) has_sep = dt_str[4:5] == self._DATE_SEP pos = 4 + has_sep # Skip '-' if it's there if dt_str[pos:pos + 1] == b'W': # YYYY-?Www-?D? pos += 1 weekno = int(dt_str[pos:pos + 2]) pos += 2 dayno = 1 if len(dt_str) > pos: if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep: raise ValueError('Inconsistent use of dash separator') pos += has_sep dayno = int(dt_str[pos:pos + 1]) pos += 1 base_date = self._calculate_weekdate(year, weekno, dayno) else: # YYYYDDD or YYYY-DDD if len(dt_str) - pos < 3: raise ValueError('Invalid ordinal day') ordinal_day = int(dt_str[pos:pos + 3]) pos += 3 if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)): raise ValueError('Invalid ordinal day' + ' {} for year {}'.format(ordinal_day, year)) base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1) components = [base_date.year, base_date.month, base_date.day] return components, pos def _calculate_weekdate(self, year, week, day): """ Calculate the day of corresponding to the ISO year-week-day calendar. This function is effectively the inverse of :func:`datetime.date.isocalendar`. :param year: The year in the ISO calendar :param week: The week in the ISO calendar - range is [1, 53] :param day: The day in the ISO calendar - range is [1 (MON), 7 (SUN)] :return: Returns a :class:`datetime.date` """ if not 0 < week < 54: raise ValueError('Invalid week: {}'.format(week)) if not 0 < day < 8: # Range is 1-7 raise ValueError('Invalid weekday: {}'.format(day)) # Get week 1 for the specific year: jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1) # Now add the specific number of weeks and days to get what we want week_offset = (week - 1) * 7 + (day - 1) return week_1 + timedelta(days=week_offset) def _parse_isotime(self, timestr): len_str = len(timestr) components = [0, 0, 0, 0, None] pos = 0 comp = -1 if len(timestr) < 2: raise ValueError('ISO time too short') has_sep = len_str >= 3 and timestr[2:3] == self._TIME_SEP while pos < len_str and comp < 5: comp += 1 if timestr[pos:pos + 1] in b'-+Zz': # Detect time zone boundary components[-1] = self._parse_tzstr(timestr[pos:]) pos = len_str break if comp < 3: # Hour, minute, second components[comp] = int(timestr[pos:pos + 2]) pos += 2 if (has_sep and pos < len_str and timestr[pos:pos + 1] == self._TIME_SEP): pos += 1 if comp == 3: # Fraction of a second frac = self._FRACTION_REGEX.match(timestr[pos:]) if not frac: continue us_str = frac.group(1)[:6] # Truncate to microseconds components[comp] = int(us_str) * 10**(6 - len(us_str)) pos += len(frac.group()) if pos < len_str: raise ValueError('Unused components in ISO string') if components[0] == 24: # Standard supports 00:00 and 24:00 as representations of midnight if any(component != 0 for component in components[1:4]): raise ValueError('Hour may only be 24 at 24:00:00.000') return components def _parse_tzstr(self, tzstr, zero_as_utc=True): if tzstr == b'Z' or tzstr == b'z': return tz.UTC if len(tzstr) not in {3, 5, 6}: raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters') if tzstr[0:1] == b'-': mult = -1 elif tzstr[0:1] == b'+': mult = 1 else: raise ValueError('Time zone offset requires sign') hours = int(tzstr[1:3]) if len(tzstr) == 3: minutes = 0 else: minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):]) if zero_as_utc and hours == 0 and minutes == 0: return tz.UTC else: if minutes > 59: raise ValueError('Invalid minutes in time zone offset') if hours > 23: raise ValueError('Invalid hours in time zone offset') return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) DEFAULT_ISOPARSER = isoparser() isoparse = DEFAULT_ISOPARSER.isoparse
dateutil/parser/isoparser.py
codereval_python_data_182
Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime.datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param \*\*kwargs: Keyword arguments as passed to ``_parse()``. :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ParserError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises TypeError: Raised for non-string or character stream input. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs): """ Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime.datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param \\*\\*kwargs: Keyword arguments as passed to ``_parse()``. :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ParserError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises TypeError: Raised for non-string or character stream input. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. """ if default is None: default = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) res, skipped_tokens = self._parse(timestr, **kwargs) if res is None: raise ParserError("Unknown string format: %s", timestr) if len(res) == 0: raise ParserError("String does not contain a date: %s", timestr) try: ret = self._build_naive(res, default) except ValueError as e: six.raise_from(ParserError(e.args[0] + ": %s", timestr), e) if not ignoretz: ret = self._build_tzaware(ret, res, tzinfos) if kwargs.get('fuzzy_with_tokens', False): return ret, skipped_tokens else: return ret # -*- coding: utf-8 -*- """ This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time. This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous. If an element of a date/time stamp is omitted, the following rules are applied: - If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is specified. - If a time zone is omitted, a timezone-naive datetime is returned. If any other elements are missing, they are taken from the :class:`datetime.datetime` object passed to the parameter ``default``. If this results in a day number exceeding the valid number of days per month, the value falls back to the end of the month. Additional resources about date/time string formats can be found below: - `A summary of the international standard date and time notation <http://www.cl.cam.ac.uk/~mgk25/iso-time.html>`_ - `W3C Date and Time Formats <http://www.w3.org/TR/NOTE-datetime>`_ - `Time Formats (Planetary Rings Node) <https://pds-rings.seti.org:443/tools/time_formats.html>`_ - `CPAN ParseDate module <http://search.cpan.org/~muir/Time-modules-2013.0912/lib/Time/ParseDate.pm>`_ - `Java SimpleDateFormat Class <https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html>`_ """ from __future__ import unicode_literals import datetime import re import string import time import warnings from calendar import monthrange from io import StringIO import six from six import integer_types, text_type from decimal import Decimal from warnings import warn from .. import relativedelta from .. import tz __all__ = ["parse", "parserinfo", "ParserError"] # TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth # making public and/or figuring out if there is something we can # take off their plate. class _timelex(object): # Fractional seconds are sometimes split by a comma _split_decimal = re.compile("([.,])") def __init__(self, instream): if six.PY2: # In Python 2, we can't duck type properly because unicode has # a 'decode' function, and we'd be double-decoding if isinstance(instream, (bytes, bytearray)): instream = instream.decode() else: if getattr(instream, 'decode', None) is not None: instream = instream.decode() if isinstance(instream, text_type): instream = StringIO(instream) elif getattr(instream, 'read', None) is None: raise TypeError('Parser must be a string or character stream, not ' '{itype}'.format(itype=instream.__class__.__name__)) self.instream = instream self.charstack = [] self.tokenstack = [] self.eof = False def get_token(self): """ This function breaks the time string into lexical units (tokens), which can be parsed by the parser. Lexical units are demarcated by changes in the character set, so any continuous string of letters is considered one unit, any continuous string of numbers is considered one unit. The main complication arises from the fact that dots ('.') can be used both as separators (e.g. "Sep.20.2009") or decimal points (e.g. "4:30:21.447"). As such, it is necessary to read the full context of any dot-separated strings before breaking it into tokens; as such, this function maintains a "token stack", for when the ambiguous context demands that multiple tokens be parsed at once. """ if self.tokenstack: return self.tokenstack.pop(0) seenletters = False token = None state = None while not self.eof: # We only realize that we've reached the end of a token when we # find a character that's not part of the current token - since # that character may be part of the next token, it's stored in the # charstack. if self.charstack: nextchar = self.charstack.pop(0) else: nextchar = self.instream.read(1) while nextchar == '\x00': nextchar = self.instream.read(1) if not nextchar: self.eof = True break elif not state: # First character of the token - determines if we're starting # to parse a word, a number or something else. token = nextchar if self.isword(nextchar): state = 'a' elif self.isnum(nextchar): state = '0' elif self.isspace(nextchar): token = ' ' break # emit token else: break # emit token elif state == 'a': # If we've already started reading a word, we keep reading # letters until we find something that's not part of a word. seenletters = True if self.isword(nextchar): token += nextchar elif nextchar == '.': token += nextchar state = 'a.' else: self.charstack.append(nextchar) break # emit token elif state == '0': # If we've already started reading a number, we keep reading # numbers until we find something that doesn't fit. if self.isnum(nextchar): token += nextchar elif nextchar == '.' or (nextchar == ',' and len(token) >= 2): token += nextchar state = '0.' else: self.charstack.append(nextchar) break # emit token elif state == 'a.': # If we've seen some letters and a dot separator, continue # parsing, and the tokens will be broken up later. seenletters = True if nextchar == '.' or self.isword(nextchar): token += nextchar elif self.isnum(nextchar) and token[-1] == '.': token += nextchar state = '0.' else: self.charstack.append(nextchar) break # emit token elif state == '0.': # If we've seen at least one dot separator, keep going, we'll # break up the tokens later. if nextchar == '.' or self.isnum(nextchar): token += nextchar elif self.isword(nextchar) and token[-1] == '.': token += nextchar state = 'a.' else: self.charstack.append(nextchar) break # emit token if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or token[-1] in '.,')): l = self._split_decimal.split(token) token = l[0] for tok in l[1:]: if tok: self.tokenstack.append(tok) if state == '0.' and token.count('.') == 0: token = token.replace(',', '.') return token def __iter__(self): return self def __next__(self): token = self.get_token() if token is None: raise StopIteration return token def next(self): return self.__next__() # Python 2.x support @classmethod def split(cls, s): return list(cls(s)) @classmethod def isword(cls, nextchar): """ Whether or not the next character is part of a word """ return nextchar.isalpha() @classmethod def isnum(cls, nextchar): """ Whether the next character is part of a number """ return nextchar.isdigit() @classmethod def isspace(cls, nextchar): """ Whether the next character is whitespace """ return nextchar.isspace() class _resultbase(object): def __init__(self): for attr in self.__slots__: setattr(self, attr, None) def _repr(self, classname): l = [] for attr in self.__slots__: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (classname, ", ".join(l)) def __len__(self): return (sum(getattr(self, attr) is not None for attr in self.__slots__)) def __repr__(self): return self._repr(self.__class__.__name__) class parserinfo(object): """ Class which handles what inputs are accepted. Subclass this to customize the language and acceptable values for each parameter. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. Default is ``False``. :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. Default is ``False``. """ # m from a.m/p.m, t from ISO T separator JUMP = [" ", ".", ",", ";", "-", "/", "'", "at", "on", "and", "ad", "m", "t", "of", "st", "nd", "rd", "th"] WEEKDAYS = [("Mon", "Monday"), ("Tue", "Tuesday"), # TODO: "Tues" ("Wed", "Wednesday"), ("Thu", "Thursday"), # TODO: "Thurs" ("Fri", "Friday"), ("Sat", "Saturday"), ("Sun", "Sunday")] MONTHS = [("Jan", "January"), ("Feb", "February"), # TODO: "Febr" ("Mar", "March"), ("Apr", "April"), ("May", "May"), ("Jun", "June"), ("Jul", "July"), ("Aug", "August"), ("Sep", "Sept", "September"), ("Oct", "October"), ("Nov", "November"), ("Dec", "December")] HMS = [("h", "hour", "hours"), ("m", "minute", "minutes"), ("s", "second", "seconds")] AMPM = [("am", "a"), ("pm", "p")] UTCZONE = ["UTC", "GMT", "Z", "z"] PERTAIN = ["of"] TZOFFSET = {} # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate", # "Anno Domini", "Year of Our Lord"] def __init__(self, dayfirst=False, yearfirst=False): self._jump = self._convert(self.JUMP) self._weekdays = self._convert(self.WEEKDAYS) self._months = self._convert(self.MONTHS) self._hms = self._convert(self.HMS) self._ampm = self._convert(self.AMPM) self._utczone = self._convert(self.UTCZONE) self._pertain = self._convert(self.PERTAIN) self.dayfirst = dayfirst self.yearfirst = yearfirst self._year = time.localtime().tm_year self._century = self._year // 100 * 100 def _convert(self, lst): dct = {} for i, v in enumerate(lst): if isinstance(v, tuple): for v in v: dct[v.lower()] = i else: dct[v.lower()] = i return dct def jump(self, name): return name.lower() in self._jump def weekday(self, name): try: return self._weekdays[name.lower()] except KeyError: pass return None def month(self, name): try: return self._months[name.lower()] + 1 except KeyError: pass return None def hms(self, name): try: return self._hms[name.lower()] except KeyError: return None def ampm(self, name): try: return self._ampm[name.lower()] except KeyError: return None def pertain(self, name): return name.lower() in self._pertain def utczone(self, name): return name.lower() in self._utczone def tzoffset(self, name): if name in self._utczone: return 0 return self.TZOFFSET.get(name) def convertyear(self, year, century_specified=False): """ Converts two-digit years to year within [-50, 49] range of self._year (current local time) """ # Function contract is that the year is always positive assert year >= 0 if year < 100 and not century_specified: # assume current century to start year += self._century if year >= self._year + 50: # if too far in future year -= 100 elif year < self._year - 50: # if too far in past year += 100 return year def validate(self, res): # move to info if res.year is not None: res.year = self.convertyear(res.year, res.century_specified) if ((res.tzoffset == 0 and not res.tzname) or (res.tzname == 'Z' or res.tzname == 'z')): res.tzname = "UTC" res.tzoffset = 0 elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): res.tzoffset = 0 return True class _ymd(list): def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.century_specified = False self.dstridx = None self.mstridx = None self.ystridx = None @property def has_year(self): return self.ystridx is not None @property def has_month(self): return self.mstridx is not None @property def has_day(self): return self.dstridx is not None def could_be_day(self, value): if self.has_day: return False elif not self.has_month: return 1 <= value <= 31 elif not self.has_year: # Be permissive, assume leap year month = self[self.mstridx] return 1 <= value <= monthrange(2000, month)[1] else: month = self[self.mstridx] year = self[self.ystridx] return 1 <= value <= monthrange(year, month)[1] def append(self, val, label=None): if hasattr(val, '__len__'): if val.isdigit() and len(val) > 2: self.century_specified = True if label not in [None, 'Y']: # pragma: no cover raise ValueError(label) label = 'Y' elif val > 100: self.century_specified = True if label not in [None, 'Y']: # pragma: no cover raise ValueError(label) label = 'Y' super(self.__class__, self).append(int(val)) if label == 'M': if self.has_month: raise ValueError('Month is already set') self.mstridx = len(self) - 1 elif label == 'D': if self.has_day: raise ValueError('Day is already set') self.dstridx = len(self) - 1 elif label == 'Y': if self.has_year: raise ValueError('Year is already set') self.ystridx = len(self) - 1 def _resolve_from_stridxs(self, strids): """ Try to resolve the identities of year/month/day elements using ystridx, mstridx, and dstridx, if enough of these are specified. """ if len(self) == 3 and len(strids) == 2: # we can back out the remaining stridx value missing = [x for x in range(3) if x not in strids.values()] key = [x for x in ['y', 'm', 'd'] if x not in strids] assert len(missing) == len(key) == 1 key = key[0] val = missing[0] strids[key] = val assert len(self) == len(strids) # otherwise this should not be called out = {key: self[strids[key]] for key in strids} return (out.get('y'), out.get('m'), out.get('d')) def resolve_ymd(self, yearfirst, dayfirst): len_ymd = len(self) year, month, day = (None, None, None) strids = (('y', self.ystridx), ('m', self.mstridx), ('d', self.dstridx)) strids = {key: val for key, val in strids if val is not None} if (len(self) == len(strids) > 0 or (len(self) == 3 and len(strids) == 2)): return self._resolve_from_stridxs(strids) mstridx = self.mstridx if len_ymd > 3: raise ValueError("More than three YMD values") elif len_ymd == 1 or (mstridx is not None and len_ymd == 2): # One member, or two members with a month string if mstridx is not None: month = self[mstridx] # since mstridx is 0 or 1, self[mstridx-1] always # looks up the other element other = self[mstridx - 1] else: other = self[0] if len_ymd > 1 or mstridx is None: if other > 31: year = other else: day = other elif len_ymd == 2: # Two members with numbers if self[0] > 31: # 99-01 year, month = self elif self[1] > 31: # 01-99 month, year = self elif dayfirst and self[1] <= 12: # 13-01 day, month = self else: # 01-13 month, day = self elif len_ymd == 3: # Three members if mstridx == 0: if self[1] > 31: # Apr-2003-25 month, year, day = self else: month, day, year = self elif mstridx == 1: if self[0] > 31 or (yearfirst and self[2] <= 31): # 99-Jan-01 year, month, day = self else: # 01-Jan-01 # Give precedence to day-first, since # two-digit years is usually hand-written. day, month, year = self elif mstridx == 2: # WTF!? if self[1] > 31: # 01-99-Jan day, year, month = self else: # 99-01-Jan year, day, month = self else: if (self[0] > 31 or self.ystridx == 0 or (yearfirst and self[1] <= 12 and self[2] <= 31)): # 99-01-01 if dayfirst and self[2] <= 12: year, day, month = self else: year, month, day = self elif self[0] > 12 or (dayfirst and self[1] <= 12): # 13-01-01 day, month, year = self else: # 01-13-01 month, day, year = self return year, month, day class parser(object): def __init__(self, info=None): self.info = info or parserinfo() def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs): """ Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime.datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param \\*\\*kwargs: Keyword arguments as passed to ``_parse()``. :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ParserError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises TypeError: Raised for non-string or character stream input. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. """ if default is None: default = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) res, skipped_tokens = self._parse(timestr, **kwargs) if res is None: raise ParserError("Unknown string format: %s", timestr) if len(res) == 0: raise ParserError("String does not contain a date: %s", timestr) try: ret = self._build_naive(res, default) except ValueError as e: six.raise_from(ParserError(e.args[0] + ": %s", timestr), e) if not ignoretz: ret = self._build_tzaware(ret, res, tzinfos) if kwargs.get('fuzzy_with_tokens', False): return ret, skipped_tokens else: return ret class _result(_resultbase): __slots__ = ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond", "tzname", "tzoffset", "ampm","any_unused_tokens"] def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, fuzzy_with_tokens=False): """ Private method which performs the heavy lifting of parsing, called from ``parse()``, which passes on its ``kwargs`` to this function. :param timestr: The string to parse. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. If set to ``None``, this value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to ``None``, the value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param fuzzy: Whether to allow fuzzy parsing, allowing for string like "Today is January 1, 2047 at 8:21:00AM". :param fuzzy_with_tokens: If ``True``, ``fuzzy`` is automatically set to True, and the parser will return a tuple where the first element is the parsed :class:`datetime.datetime` datetimestamp and the second element is a tuple containing the portions of the string which were ignored: .. doctest:: >>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) """ if fuzzy_with_tokens: fuzzy = True info = self.info if dayfirst is None: dayfirst = info.dayfirst if yearfirst is None: yearfirst = info.yearfirst res = self._result() l = _timelex.split(timestr) # Splits the timestr into tokens skipped_idxs = [] # year/month/day list ymd = _ymd() len_l = len(l) i = 0 try: while i < len_l: # Check if it's a number value_repr = l[i] try: value = float(value_repr) except ValueError: value = None if value is not None: # Numeric token i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy) # Check weekday elif info.weekday(l[i]) is not None: value = info.weekday(l[i]) res.weekday = value # Check month name elif info.month(l[i]) is not None: value = info.month(l[i]) ymd.append(value, 'M') if i + 1 < len_l: if l[i + 1] in ('-', '/'): # Jan-01[-99] sep = l[i + 1] ymd.append(l[i + 2]) if i + 3 < len_l and l[i + 3] == sep: # Jan-01-99 ymd.append(l[i + 4]) i += 2 i += 2 elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and info.pertain(l[i + 2])): # Jan of 01 # In this case, 01 is clearly year if l[i + 4].isdigit(): # Convert it here to become unambiguous value = int(l[i + 4]) year = str(info.convertyear(value)) ymd.append(year, 'Y') else: # Wrong guess pass # TODO: not hit in tests i += 4 # Check am/pm elif info.ampm(l[i]) is not None: value = info.ampm(l[i]) val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy) if val_is_ampm: res.hour = self._adjust_ampm(res.hour, value) res.ampm = value elif fuzzy: skipped_idxs.append(i) # Check for a timezone name elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]): res.tzname = l[i] res.tzoffset = info.tzoffset(res.tzname) # Check for something like GMT+3, or BRST+3. Notice # that it doesn't mean "I am 3 hours after GMT", but # "my time +3 is GMT". If found, we reverse the # logic so that timezone parsing code will get it # right. if i + 1 < len_l and l[i + 1] in ('+', '-'): l[i + 1] = ('+', '-')[l[i + 1] == '+'] res.tzoffset = None if info.utczone(res.tzname): # With something like GMT+3, the timezone # is *not* GMT. res.tzname = None # Check for a numbered timezone elif res.hour is not None and l[i] in ('+', '-'): signal = (-1, 1)[l[i] == '+'] len_li = len(l[i + 1]) # TODO: check that l[i + 1] is integer? if len_li == 4: # -0300 hour_offset = int(l[i + 1][:2]) min_offset = int(l[i + 1][2:]) elif i + 2 < len_l and l[i + 2] == ':': # -03:00 hour_offset = int(l[i + 1]) min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like? i += 2 elif len_li <= 2: # -[0]3 hour_offset = int(l[i + 1][:2]) min_offset = 0 else: raise ValueError(timestr) res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60) # Look for a timezone name between parenthesis if (i + 5 < len_l and info.jump(l[i + 2]) and l[i + 3] == '(' and l[i + 5] == ')' and 3 <= len(l[i + 4]) and self._could_be_tzname(res.hour, res.tzname, None, l[i + 4])): # -0300 (BRST) res.tzname = l[i + 4] i += 4 i += 1 # Check jumps elif not (info.jump(l[i]) or fuzzy): raise ValueError(timestr) else: skipped_idxs.append(i) i += 1 # Process year/month/day year, month, day = ymd.resolve_ymd(yearfirst, dayfirst) res.century_specified = ymd.century_specified res.year = year res.month = month res.day = day except (IndexError, ValueError): return None, None if not info.validate(res): return None, None if fuzzy_with_tokens: skipped_tokens = self._recombine_skipped(l, skipped_idxs) return res, tuple(skipped_tokens) else: return res, None def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy): # Token is a number value_repr = tokens[idx] try: value = self._to_decimal(value_repr) except Exception as e: six.raise_from(ValueError('Unknown numeric token'), e) len_li = len(value_repr) len_l = len(tokens) if (len(ymd) == 3 and len_li in (2, 4) and res.hour is None and (idx + 1 >= len_l or (tokens[idx + 1] != ':' and info.hms(tokens[idx + 1]) is None))): # 19990101T23[59] s = tokens[idx] res.hour = int(s[:2]) if len_li == 4: res.minute = int(s[2:]) elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6): # YYMMDD or HHMMSS[.ss] s = tokens[idx] if not ymd and '.' not in tokens[idx]: ymd.append(s[:2]) ymd.append(s[2:4]) ymd.append(s[4:]) else: # 19990101T235959[.59] # TODO: Check if res attributes already set. res.hour = int(s[:2]) res.minute = int(s[2:4]) res.second, res.microsecond = self._parsems(s[4:]) elif len_li in (8, 12, 14): # YYYYMMDD s = tokens[idx] ymd.append(s[:4], 'Y') ymd.append(s[4:6]) ymd.append(s[6:8]) if len_li > 8: res.hour = int(s[8:10]) res.minute = int(s[10:12]) if len_li > 12: res.second = int(s[12:]) elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None: # HH[ ]h or MM[ ]m or SS[.ss][ ]s hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True) (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx) if hms is not None: # TODO: checking that hour/minute/second are not # already set? self._assign_hms(res, value_repr, hms) elif idx + 2 < len_l and tokens[idx + 1] == ':': # HH:MM[:SS[.ss]] res.hour = int(value) value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this? (res.minute, res.second) = self._parse_min_sec(value) if idx + 4 < len_l and tokens[idx + 3] == ':': res.second, res.microsecond = self._parsems(tokens[idx + 4]) idx += 2 idx += 2 elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'): sep = tokens[idx + 1] ymd.append(value_repr) if idx + 2 < len_l and not info.jump(tokens[idx + 2]): if tokens[idx + 2].isdigit(): # 01-01[-01] ymd.append(tokens[idx + 2]) else: # 01-Jan[-01] value = info.month(tokens[idx + 2]) if value is not None: ymd.append(value, 'M') else: raise ValueError() if idx + 3 < len_l and tokens[idx + 3] == sep: # We have three members value = info.month(tokens[idx + 4]) if value is not None: ymd.append(value, 'M') else: ymd.append(tokens[idx + 4]) idx += 2 idx += 1 idx += 1 elif idx + 1 >= len_l or info.jump(tokens[idx + 1]): if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None: # 12 am hour = int(value) res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2])) idx += 1 else: # Year, month or day ymd.append(value) idx += 1 elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24): # 12am hour = int(value) res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1])) idx += 1 elif ymd.could_be_day(value): ymd.append(value) elif not fuzzy: raise ValueError() return idx def _find_hms_idx(self, idx, tokens, info, allow_jump): len_l = len(tokens) if idx+1 < len_l and info.hms(tokens[idx+1]) is not None: # There is an "h", "m", or "s" label following this token. We take # assign the upcoming label to the current token. # e.g. the "12" in 12h" hms_idx = idx + 1 elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and info.hms(tokens[idx+2]) is not None): # There is a space and then an "h", "m", or "s" label. # e.g. the "12" in "12 h" hms_idx = idx + 2 elif idx > 0 and info.hms(tokens[idx-1]) is not None: # There is a "h", "m", or "s" preceding this token. Since neither # of the previous cases was hit, there is no label following this # token, so we use the previous label. # e.g. the "04" in "12h04" hms_idx = idx-1 elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and info.hms(tokens[idx-2]) is not None): # If we are looking at the final token, we allow for a # backward-looking check to skip over a space. # TODO: Are we sure this is the right condition here? hms_idx = idx - 2 else: hms_idx = None return hms_idx def _assign_hms(self, res, value_repr, hms): # See GH issue #427, fixing float rounding value = self._to_decimal(value_repr) if hms == 0: # Hour res.hour = int(value) if value % 1: res.minute = int(60*(value % 1)) elif hms == 1: (res.minute, res.second) = self._parse_min_sec(value) elif hms == 2: (res.second, res.microsecond) = self._parsems(value_repr) def _could_be_tzname(self, hour, tzname, tzoffset, token): return (hour is not None and tzname is None and tzoffset is None and len(token) <= 5 and (all(x in string.ascii_uppercase for x in token) or token in self.info.UTCZONE)) def _ampm_valid(self, hour, ampm, fuzzy): """ For fuzzy parsing, 'a' or 'am' (both valid English words) may erroneously trigger the AM/PM flag. Deal with that here. """ val_is_ampm = True # If there's already an AM/PM flag, this one isn't one. if fuzzy and ampm is not None: val_is_ampm = False # If AM/PM is found and hour is not, raise a ValueError if hour is None: if fuzzy: val_is_ampm = False else: raise ValueError('No hour specified with AM or PM flag.') elif not 0 <= hour <= 12: # If AM/PM is found, it's a 12 hour clock, so raise # an error for invalid range if fuzzy: val_is_ampm = False else: raise ValueError('Invalid hour specified for 12-hour clock.') return val_is_ampm def _adjust_ampm(self, hour, ampm): if hour < 12 and ampm == 1: hour += 12 elif hour == 12 and ampm == 0: hour = 0 return hour def _parse_min_sec(self, value): # TODO: Every usage of this function sets res.second to the return # value. Are there any cases where second will be returned as None and # we *don't* want to set res.second = None? minute = int(value) second = None sec_remainder = value % 1 if sec_remainder: second = int(60 * sec_remainder) return (minute, second) def _parse_hms(self, idx, tokens, info, hms_idx): # TODO: Is this going to admit a lot of false-positives for when we # just happen to have digits and "h", "m" or "s" characters in non-date # text? I guess hex hashes won't have that problem, but there's plenty # of random junk out there. if hms_idx is None: hms = None new_idx = idx elif hms_idx > idx: hms = info.hms(tokens[hms_idx]) new_idx = hms_idx else: # Looking backwards, increment one. hms = info.hms(tokens[hms_idx]) + 1 new_idx = idx return (new_idx, hms) # ------------------------------------------------------------------ # Handling for individual tokens. These are kept as methods instead # of functions for the sake of customizability via subclassing. def _parsems(self, value): """Parse a I[.F] seconds value into (seconds, microseconds).""" if "." not in value: return int(value), 0 else: i, f = value.split(".") return int(i), int(f.ljust(6, "0")[:6]) def _to_decimal(self, val): try: decimal_value = Decimal(val) # See GH 662, edge case, infinite value should not be converted # via `_to_decimal` if not decimal_value.is_finite(): raise ValueError("Converted decimal value is infinite or NaN") except Exception as e: msg = "Could not convert %s to decimal" % val six.raise_from(ValueError(msg), e) else: return decimal_value # ------------------------------------------------------------------ # Post-Parsing construction of datetime output. These are kept as # methods instead of functions for the sake of customizability via # subclassing. def _build_tzinfo(self, tzinfos, tzname, tzoffset): if callable(tzinfos): tzdata = tzinfos(tzname, tzoffset) else: tzdata = tzinfos.get(tzname) # handle case where tzinfo is paased an options that returns None # eg tzinfos = {'BRST' : None} if isinstance(tzdata, datetime.tzinfo) or tzdata is None: tzinfo = tzdata elif isinstance(tzdata, text_type): tzinfo = tz.tzstr(tzdata) elif isinstance(tzdata, integer_types): tzinfo = tz.tzoffset(tzname, tzdata) else: raise TypeError("Offset must be tzinfo subclass, tz string, " "or int offset.") return tzinfo def _build_tzaware(self, naive, res, tzinfos): if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)): tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset) aware = naive.replace(tzinfo=tzinfo) aware = self._assign_tzname(aware, res.tzname) elif res.tzname and res.tzname in time.tzname: aware = naive.replace(tzinfo=tz.tzlocal()) # Handle ambiguous local datetime aware = self._assign_tzname(aware, res.tzname) # This is mostly relevant for winter GMT zones parsed in the UK if (aware.tzname() != res.tzname and res.tzname in self.info.UTCZONE): aware = aware.replace(tzinfo=tz.UTC) elif res.tzoffset == 0: aware = naive.replace(tzinfo=tz.UTC) elif res.tzoffset: aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset)) elif not res.tzname and not res.tzoffset: # i.e. no timezone information was found. aware = naive elif res.tzname: # tz-like string was parsed but we don't know what to do # with it warnings.warn("tzname {tzname} identified but not understood. " "Pass `tzinfos` argument in order to correctly " "return a timezone-aware datetime. In a future " "version, this will raise an " "exception.".format(tzname=res.tzname), category=UnknownTimezoneWarning) aware = naive return aware def _build_naive(self, res, default): repl = {} for attr in ("year", "month", "day", "hour", "minute", "second", "microsecond"): value = getattr(res, attr) if value is not None: repl[attr] = value if 'day' not in repl: # If the default day exceeds the last day of the month, fall back # to the end of the month. cyear = default.year if res.year is None else res.year cmonth = default.month if res.month is None else res.month cday = default.day if res.day is None else res.day if cday > monthrange(cyear, cmonth)[1]: repl['day'] = monthrange(cyear, cmonth)[1] naive = default.replace(**repl) if res.weekday is not None and not res.day: naive = naive + relativedelta.relativedelta(weekday=res.weekday) return naive def _assign_tzname(self, dt, tzname): if dt.tzname() != tzname: new_dt = tz.enfold(dt, fold=1) if new_dt.tzname() == tzname: return new_dt return dt def _recombine_skipped(self, tokens, skipped_idxs): """ >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"] >>> skipped_idxs = [0, 1, 2, 5] >>> _recombine_skipped(tokens, skipped_idxs) ["foo bar", "baz"] """ skipped_tokens = [] for i, idx in enumerate(sorted(skipped_idxs)): if i > 0 and idx - 1 == skipped_idxs[i - 1]: skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx] else: skipped_tokens.append(tokens[idx]) return skipped_tokens DEFAULTPARSER = parser() def parse(timestr, parserinfo=None, **kwargs): """ Parse a string in one of the supported formats, using the ``parserinfo`` parameters. :param timestr: A string containing a date/time stamp. :param parserinfo: A :class:`parserinfo` object containing parameters for the parser. If ``None``, the default arguments to the :class:`parserinfo` constructor are used. The ``**kwargs`` parameter takes the following keyword arguments: :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. If set to ``None``, this value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to ``None``, the value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param fuzzy: Whether to allow fuzzy parsing, allowing for string like "Today is January 1, 2047 at 8:21:00AM". :param fuzzy_with_tokens: If ``True``, ``fuzzy`` is automatically set to True, and the parser will return a tuple where the first element is the parsed :class:`datetime.datetime` datetimestamp and the second element is a tuple containing the portions of the string which were ignored: .. doctest:: >>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ValueError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. """ if parserinfo: return parser(parserinfo).parse(timestr, **kwargs) else: return DEFAULTPARSER.parse(timestr, **kwargs) class _tzparser(object): class _result(_resultbase): __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", "start", "end"] class _attr(_resultbase): __slots__ = ["month", "week", "weekday", "yday", "jyday", "day", "time"] def __repr__(self): return self._repr("") def __init__(self): _resultbase.__init__(self) self.start = self._attr() self.end = self._attr() def parse(self, tzstr): res = self._result() l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x] used_idxs = list() try: len_l = len(l) i = 0 while i < len_l: # BRST+3[BRDT[+2]] j = i while j < len_l and not [x for x in l[j] if x in "0123456789:,-+"]: j += 1 if j != i: if not res.stdabbr: offattr = "stdoffset" res.stdabbr = "".join(l[i:j]) else: offattr = "dstoffset" res.dstabbr = "".join(l[i:j]) for ii in range(j): used_idxs.append(ii) i = j if (i < len_l and (l[i] in ('+', '-') or l[i][0] in "0123456789")): if l[i] in ('+', '-'): # Yes, that's right. See the TZ variable # documentation. signal = (1, -1)[l[i] == '+'] used_idxs.append(i) i += 1 else: signal = -1 len_li = len(l[i]) if len_li == 4: # -0300 setattr(res, offattr, (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) * signal) elif i + 1 < len_l and l[i + 1] == ':': # -03:00 setattr(res, offattr, (int(l[i]) * 3600 + int(l[i + 2]) * 60) * signal) used_idxs.append(i) i += 2 elif len_li <= 2: # -[0]3 setattr(res, offattr, int(l[i][:2]) * 3600 * signal) else: return None used_idxs.append(i) i += 1 if res.dstabbr: break else: break if i < len_l: for j in range(i, len_l): if l[j] == ';': l[j] = ',' assert l[i] == ',' i += 1 if i >= len_l: pass elif (8 <= l.count(',') <= 9 and not [y for x in l[i:] if x != ',' for y in x if y not in "0123456789+-"]): # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] for x in (res.start, res.end): x.month = int(l[i]) used_idxs.append(i) i += 2 if l[i] == '-': value = int(l[i + 1]) * -1 used_idxs.append(i) i += 1 else: value = int(l[i]) used_idxs.append(i) i += 2 if value: x.week = value x.weekday = (int(l[i]) - 1) % 7 else: x.day = int(l[i]) used_idxs.append(i) i += 2 x.time = int(l[i]) used_idxs.append(i) i += 2 if i < len_l: if l[i] in ('-', '+'): signal = (-1, 1)[l[i] == "+"] used_idxs.append(i) i += 1 else: signal = 1 used_idxs.append(i) res.dstoffset = (res.stdoffset + int(l[i]) * signal) # This was a made-up format that is not in normal use warn(('Parsed time zone "%s"' % tzstr) + 'is in a non-standard dateutil-specific format, which ' + 'is now deprecated; support for parsing this format ' + 'will be removed in future versions. It is recommended ' + 'that you switch to a standard format like the GNU ' + 'TZ variable format.', tz.DeprecatedTzFormatWarning) elif (l.count(',') == 2 and l[i:].count('/') <= 2 and not [y for x in l[i:] if x not in (',', '/', 'J', 'M', '.', '-', ':') for y in x if y not in "0123456789"]): for x in (res.start, res.end): if l[i] == 'J': # non-leap year day (1 based) used_idxs.append(i) i += 1 x.jyday = int(l[i]) elif l[i] == 'M': # month[-.]week[-.]weekday used_idxs.append(i) i += 1 x.month = int(l[i]) used_idxs.append(i) i += 1 assert l[i] in ('-', '.') used_idxs.append(i) i += 1 x.week = int(l[i]) if x.week == 5: x.week = -1 used_idxs.append(i) i += 1 assert l[i] in ('-', '.') used_idxs.append(i) i += 1 x.weekday = (int(l[i]) - 1) % 7 else: # year day (zero based) x.yday = int(l[i]) + 1 used_idxs.append(i) i += 1 if i < len_l and l[i] == '/': used_idxs.append(i) i += 1 # start time len_li = len(l[i]) if len_li == 4: # -0300 x.time = (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) elif i + 1 < len_l and l[i + 1] == ':': # -03:00 x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 used_idxs.append(i) i += 2 if i + 1 < len_l and l[i + 1] == ':': used_idxs.append(i) i += 2 x.time += int(l[i]) elif len_li <= 2: # -[0]3 x.time = (int(l[i][:2]) * 3600) else: return None used_idxs.append(i) i += 1 assert i == len_l or l[i] == ',' i += 1 assert i >= len_l except (IndexError, ValueError, AssertionError): return None unused_idxs = set(range(len_l)).difference(used_idxs) res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"}) return res DEFAULTTZPARSER = _tzparser() def _parsetz(tzstr): return DEFAULTTZPARSER.parse(tzstr) class ParserError(ValueError): """Error class for representing failure to parse a datetime string.""" def __str__(self): try: return self.args[0] % self.args[1:] except (TypeError, IndexError): return super(ParserError, self).__str__() def __repr__(self): return "%s(%s)" % (self.__class__.__name__, str(self)) class UnknownTimezoneWarning(RuntimeWarning): """Raised when the parser finds a timezone it cannot parse into a tzinfo""" # vim:ts=4:sw=4:et
dateutil/parser/_parser.py
codereval_python_data_183
Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurrence, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. @_validate_fromutc_inputs def fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurrence, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. """ dt_wall = self._fromutc(dt) # Calculate the fold status given the two datetimes. _fold = self._fold_status(dt, dt_wall) # Set the default fold value for ambiguous dates return enfold(dt_wall, fold=_fold) from six import PY2 from functools import wraps from datetime import datetime, timedelta, tzinfo ZERO = timedelta(0) __all__ = ['tzname_in_python2', 'enfold'] def tzname_in_python2(namefunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """ if PY2: @wraps(namefunc) def adjust_encoding(*args, **kwargs): name = namefunc(*args, **kwargs) if name is not None: name = name.encode() return name return adjust_encoding else: return namefunc # The following is adapted from Alexander Belopolsky's tz library # https://github.com/abalkin/tz if hasattr(datetime, 'fold'): # This is the pre-python 3.6 fold situation def enfold(dt, fold=1): """ Provides a unified interface for assigning the ``fold`` attribute to datetimes both before and after the implementation of PEP-495. :param fold: The value for the ``fold`` attribute in the returned datetime. This should be either 0 or 1. :return: Returns an object for which ``getattr(dt, 'fold', 0)`` returns ``fold`` for all versions of Python. In versions prior to Python 3.6, this is a ``_DatetimeWithFold`` object, which is a subclass of :py:class:`datetime.datetime` with the ``fold`` attribute added, if ``fold`` is 1. .. versionadded:: 2.6.0 """ return dt.replace(fold=fold) else: class _DatetimeWithFold(datetime): """ This is a class designed to provide a PEP 495-compliant interface for Python versions before 3.6. It is used only for dates in a fold, so the ``fold`` attribute is fixed at ``1``. .. versionadded:: 2.6.0 """ __slots__ = () def replace(self, *args, **kwargs): """ Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive datetime from an aware datetime with no conversion of date and time data. This is reimplemented in ``_DatetimeWithFold`` because pypy3 will return a ``datetime.datetime`` even if ``fold`` is unchanged. """ argnames = ( 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'tzinfo' ) for arg, argname in zip(args, argnames): if argname in kwargs: raise TypeError('Duplicate argument: {}'.format(argname)) kwargs[argname] = arg for argname in argnames: if argname not in kwargs: kwargs[argname] = getattr(self, argname) dt_class = self.__class__ if kwargs.get('fold', 1) else datetime return dt_class(**kwargs) @property def fold(self): return 1 def enfold(dt, fold=1): """ Provides a unified interface for assigning the ``fold`` attribute to datetimes both before and after the implementation of PEP-495. :param fold: The value for the ``fold`` attribute in the returned datetime. This should be either 0 or 1. :return: Returns an object for which ``getattr(dt, 'fold', 0)`` returns ``fold`` for all versions of Python. In versions prior to Python 3.6, this is a ``_DatetimeWithFold`` object, which is a subclass of :py:class:`datetime.datetime` with the ``fold`` attribute added, if ``fold`` is 1. .. versionadded:: 2.6.0 """ if getattr(dt, 'fold', 0) == fold: return dt args = dt.timetuple()[:6] args += (dt.microsecond, dt.tzinfo) if fold: return _DatetimeWithFold(*args) else: return datetime(*args) def _validate_fromutc_inputs(f): """ The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``. """ @wraps(f) def fromutc(self, dt): if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") return f(self, dt) return fromutc class _tzinfo(tzinfo): """ Base class for all ``dateutil`` ``tzinfo`` objects. """ def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ dt = dt.replace(tzinfo=self) wall_0 = enfold(dt, fold=0) wall_1 = enfold(dt, fold=1) same_offset = wall_0.utcoffset() == wall_1.utcoffset() same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None) return same_dt and not same_offset def _fold_status(self, dt_utc, dt_wall): """ Determine the fold status of a "wall" datetime, given a representation of the same datetime as a (naive) UTC datetime. This is calculated based on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all datetimes, and that this offset is the actual number of hours separating ``dt_utc`` and ``dt_wall``. :param dt_utc: Representation of the datetime as UTC :param dt_wall: Representation of the datetime as "wall time". This parameter must either have a `fold` attribute or have a fold-naive :class:`datetime.tzinfo` attached, otherwise the calculation may fail. """ if self.is_ambiguous(dt_wall): delta_wall = dt_wall - dt_utc _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst())) else: _fold = 0 return _fold def _fold(self, dt): return getattr(dt, 'fold', 0) def _fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurrence, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. """ # Re-implement the algorithm from Python's datetime.py dtoff = dt.utcoffset() if dtoff is None: raise ValueError("fromutc() requires a non-None utcoffset() " "result") # The original datetime.py code assumes that `dst()` defaults to # zero during ambiguous times. PEP 495 inverts this presumption, so # for pre-PEP 495 versions of python, we need to tweak the algorithm. dtdst = dt.dst() if dtdst is None: raise ValueError("fromutc() requires a non-None dst() result") delta = dtoff - dtdst dt += delta # Set fold=1 so we can default to being in the fold for # ambiguous dates. dtdst = enfold(dt, fold=1).dst() if dtdst is None: raise ValueError("fromutc(): dt.dst gave inconsistent " "results; cannot convert") return dt + dtdst @_validate_fromutc_inputs def fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurrence, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. """ dt_wall = self._fromutc(dt) # Calculate the fold status given the two datetimes. _fold = self._fold_status(dt, dt_wall) # Set the default fold value for ambiguous dates return enfold(dt_wall, fold=_fold) class tzrangebase(_tzinfo): """ This is an abstract base class for time zones represented by an annual transition into and out of DST. Child classes should implement the following methods: * ``__init__(self, *args, **kwargs)`` * ``transitions(self, year)`` - this is expected to return a tuple of datetimes representing the DST on and off transitions in standard time. A fully initialized ``tzrangebase`` subclass should also provide the following attributes: * ``hasdst``: Boolean whether or not the zone uses DST. * ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects representing the respective UTC offsets. * ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short abbreviations in DST and STD, respectively. * ``_hasdst``: Whether or not the zone has DST. .. versionadded:: 2.6.0 """ def __init__(self): raise NotImplementedError('tzrangebase is an abstract base class') def utcoffset(self, dt): isdst = self._isdst(dt) if isdst is None: return None elif isdst: return self._dst_offset else: return self._std_offset def dst(self, dt): isdst = self._isdst(dt) if isdst is None: return None elif isdst: return self._dst_base_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr def fromutc(self, dt): """ Given a datetime in UTC, return local time """ if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") # Get transitions - if there are none, fixed offset transitions = self.transitions(dt.year) if transitions is None: return dt + self.utcoffset(dt) # Get the transition times in UTC dston, dstoff = transitions dston -= self._std_offset dstoff -= self._std_offset utc_transitions = (dston, dstoff) dt_utc = dt.replace(tzinfo=None) isdst = self._naive_isdst(dt_utc, utc_transitions) if isdst: dt_wall = dt + self._dst_offset else: dt_wall = dt + self._std_offset _fold = int(not isdst and self.is_ambiguous(dt_wall)) return enfold(dt_wall, fold=_fold) def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ if not self.hasdst: return False start, end = self.transitions(dt.year) dt = dt.replace(tzinfo=None) return (end <= dt < end + self._dst_base_offset) def _isdst(self, dt): if not self.hasdst: return False elif dt is None: return None transitions = self.transitions(dt.year) if transitions is None: return False dt = dt.replace(tzinfo=None) isdst = self._naive_isdst(dt, transitions) # Handle ambiguous dates if not isdst and self.is_ambiguous(dt): return not self._fold(dt) else: return isdst def _naive_isdst(self, dt, transitions): dston, dstoff = transitions dt = dt.replace(tzinfo=None) if dston < dstoff: isdst = dston <= dt < dstoff else: isdst = not dstoff <= dt < dston return isdst @property def _dst_base_offset(self): return self._dst_offset - self._std_offset __hash__ = None def __ne__(self, other): return not (self == other) def __repr__(self): return "%s(...)" % self.__class__.__name__ __reduce__ = object.__reduce__
dateutil/tz/_common.py
codereval_python_data_184
Sets the ``tzinfo`` parameter on naive datetimes only This is useful for example when you are provided a datetime that may have either an implicit or explicit time zone, such as when parsing a time zone string. .. doctest:: >>> from dateutil.tz import tzoffset >>> from dateutil.parser import parse >>> from dateutil.utils import default_tzinfo >>> dflt_tz = tzoffset("EST", -18000) >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) 2014-01-01 12:30:00+00:00 >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) 2014-01-01 12:30:00-05:00 :param dt: The datetime on which to replace the time zone :param tzinfo: The :py:class:`datetime.tzinfo` subclass instance to assign to ``dt`` if (and only if) it is naive. :return: Returns an aware :py:class:`datetime.datetime`. def default_tzinfo(dt, tzinfo): """ Sets the ``tzinfo`` parameter on naive datetimes only This is useful for example when you are provided a datetime that may have either an implicit or explicit time zone, such as when parsing a time zone string. .. doctest:: >>> from dateutil.tz import tzoffset >>> from dateutil.parser import parse >>> from dateutil.utils import default_tzinfo >>> dflt_tz = tzoffset("EST", -18000) >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) 2014-01-01 12:30:00+00:00 >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) 2014-01-01 12:30:00-05:00 :param dt: The datetime on which to replace the time zone :param tzinfo: The :py:class:`datetime.tzinfo` subclass instance to assign to ``dt`` if (and only if) it is naive. :return: Returns an aware :py:class:`datetime.datetime`. """ if dt.tzinfo is not None: return dt else: return dt.replace(tzinfo=tzinfo) # -*- coding: utf-8 -*- """ This module offers general convenience and utility functions for dealing with datetimes. .. versionadded:: 2.7.0 """ from __future__ import unicode_literals from datetime import datetime, time def today(tzinfo=None): """ Returns a :py:class:`datetime` representing the current day at midnight :param tzinfo: The time zone to attach (also used to determine the current day). :return: A :py:class:`datetime.datetime` object representing the current day at midnight. """ dt = datetime.now(tzinfo) return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) def default_tzinfo(dt, tzinfo): """ Sets the ``tzinfo`` parameter on naive datetimes only This is useful for example when you are provided a datetime that may have either an implicit or explicit time zone, such as when parsing a time zone string. .. doctest:: >>> from dateutil.tz import tzoffset >>> from dateutil.parser import parse >>> from dateutil.utils import default_tzinfo >>> dflt_tz = tzoffset("EST", -18000) >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) 2014-01-01 12:30:00+00:00 >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) 2014-01-01 12:30:00-05:00 :param dt: The datetime on which to replace the time zone :param tzinfo: The :py:class:`datetime.tzinfo` subclass instance to assign to ``dt`` if (and only if) it is naive. :return: Returns an aware :py:class:`datetime.datetime`. """ if dt.tzinfo is not None: return dt else: return dt.replace(tzinfo=tzinfo) def within_delta(dt1, dt2, delta): """ Useful for comparing two datetimes that may a negilible difference to be considered equal. """ delta = abs(delta) difference = dt1 - dt2 return -delta <= difference <= delta
dateutil/utils.py
codereval_python_data_185
Set the bytes used to delimit slice points. Args: before: Split file before these delimiters. after: Split file after these delimiters. def set_cut_chars(self, before: bytes, after: bytes) -> None: """Set the bytes used to delimit slice points. Args: before: Split file before these delimiters. after: Split file after these delimiters. """ self._cutter = re.compile( b"[" + before + b"]?" + b"[^" + before + after + b"]*" + b"(?:[" + after + b"]|$|(?=[" + before + b"]))" ) # coding=utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. """Lithium Testcase definitions. A testcase is a file to be reduced, split in a certain way (eg. bytes, lines). """ import abc import argparse import logging import os.path import re from pathlib import Path from typing import List, Optional, Pattern, Tuple, Union from .util import LithiumError DEFAULT = "line" LOG = logging.getLogger(__name__) class Testcase(abc.ABC): """Lithium testcase base class.""" atom: str """description of the units this testcase splits into""" def __init__(self) -> None: self.before: bytes = b"" self.after: bytes = b"" self.parts: List[bytes] = [] # bool array with same length as `parts` # parts with a matchine `False` in `reducible` should # not be removed by the Strategy self.reducible: List[bool] = [] self.filename: Optional[str] = None self.extension: Optional[str] = None def __len__(self) -> int: """Length of the testcase in terms of parts to be reduced. Returns: length of parts """ return len(self.parts) - self.reducible.count(False) def _slice_xlat( self, start: Optional[int] = None, stop: Optional[int] = None ) -> Tuple[int, int]: # translate slice bounds within `[0, len(self))` (excluding non-reducible parts) # to bounds within `self.parts` len_self = len(self) def _clamp(bound: Optional[int], default: int) -> int: if bound is None: return default if bound < 0: return max(len_self + bound, 0) if bound > len_self: return len_self return bound start = _clamp(start, 0) stop = _clamp(stop, len_self) opts = [i for i in range(len(self.parts)) if self.reducible[i]] opts = [0] + opts[1:] + [len(self.parts)] return opts[start], opts[stop] def rmslice(self, start: int, stop: int) -> None: """Remove a slice of the testcase between `self.parts[start:stop]`, preserving non-reducible parts. Slice indices are between 0 and len(self), which may not be = len(self.parts) if any parts are marked non-reducible. Args: start: Slice start index stop: Slice stop index """ start, stop = self._slice_xlat(start, stop) keep = [ x for i, x in enumerate(self.parts[start:stop]) if not self.reducible[start + i] ] self.parts = self.parts[:start] + keep + self.parts[stop:] self.reducible = ( self.reducible[:start] + ([False] * len(keep)) + self.reducible[stop:] ) def copy(self) -> "Testcase": """Duplicate the current object. Returns: type(self): A new object with the same type & contents of the original. """ new = type(self)() new.before = self.before new.after = self.after new.parts = self.parts[:] new.reducible = self.reducible[:] new.filename = self.filename new.extension = self.extension return new def load(self, path: Union[Path, str]) -> None: """Load and split a testcase from disk. Args: path: Location on disk of testcase to read. Raises: LithiumError: DDBEGIN/DDEND token mismatch. """ self.__init__() # type: ignore[misc] self.filename = str(path) self.extension = os.path.splitext(self.filename)[1] with open(self.filename, "rb") as fileobj: text = fileobj.read().decode("utf-8", errors="surrogateescape") lines = [ line.encode("utf-8", errors="surrogateescape") for line in text.splitlines(keepends=True) ] before = [] while lines: line = lines.pop(0) before.append(line) if line.find(b"DDBEGIN") != -1: self.before = b"".join(before) del before break if line.find(b"DDEND") != -1: raise LithiumError( "The testcase (%s) has a line containing 'DDEND' " "without a line containing 'DDBEGIN' before it." % (self.filename,) ) else: # no DDBEGIN/END, `before` contains the whole testcase self.split_parts(b"".join(before)) return between = [] while lines: line = lines.pop(0) if line.find(b"DDEND") != -1: self.after = line + b"".join(lines) break between.append(line) else: raise LithiumError( "The testcase (%s) has a line containing 'DDBEGIN' " "but no line containing 'DDEND'." % (self.filename,) ) self.split_parts(b"".join(between)) @staticmethod def add_arguments(parser: argparse.ArgumentParser) -> None: """Add any testcase specific arguments. Args: parser: argparse object to add arguments to. """ def handle_args(self, args: argparse.Namespace) -> None: """Handle arguments after they have been parsed. Args: args: parsed argparse arguments. """ @abc.abstractmethod def split_parts(self, data: bytes) -> None: """Should take testcase data and update `self.parts`. Args: data: Input read from the testcase file (between DDBEGIN/END, if present). """ def dump(self, path: Optional[Union[Path, str]] = None) -> None: """Write the testcase to the filesystem. Args: path: Output path (default: self.filename) """ if path is None: assert self.filename is not None path = self.filename else: path = str(path) with open(path, "wb") as fileobj: fileobj.write(self.before) fileobj.writelines(self.parts) fileobj.write(self.after) class TestcaseLine(Testcase): """Testcase file split by lines.""" atom = "line" args = ("-l", "--lines") arg_help = "Treat the file as a sequence of lines." def split_parts(self, data: bytes) -> None: """Take input data and add lines to `parts` to be reduced. Args: data: Input data read from the testcase file. """ orig = len(self.parts) self.parts.extend( line.encode("utf-8", errors="surrogateescape") for line in data.decode("utf-8", errors="surrogateescape").splitlines( keepends=True ) ) added = len(self.parts) - orig self.reducible.extend([True] * added) class TestcaseChar(Testcase): """Testcase file split by bytes.""" atom = "char" args = ("-c", "--char") arg_help = "Treat the file as a sequence of bytes." def load(self, path: Union[Path, str]) -> None: super().load(path) if (self.before or self.after) and self.parts: # Move the line break at the end of the last line out of the reducible # part so the "DDEND" line doesn't get combined with another line. self.parts.pop() self.reducible.pop() self.after = b"\n" + self.after def split_parts(self, data: bytes) -> None: orig = len(self.parts) self.parts.extend(data[i : i + 1] for i in range(len(data))) added = len(self.parts) - orig self.reducible.extend([True] * added) class TestcaseJsStr(Testcase): """Testcase type for splitting JS strings byte-wise. Escapes are also kept together and treated as a single token for reduction. ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference /Global_Objects/String#Escape_notation """ atom = "jsstr char" args = ("-j", "--js") arg_help = ( "Same as --char but only operate within JS strings, keeping escapes intact." ) def split_parts(self, data: bytes) -> None: instr = None chars: List[int] = [] while True: last = 0 while True: if instr: match = re.match( br"(\\u[0-9A-Fa-f]{4}|\\x[0-9A-Fa-f]{2}|" br"\\u\{[0-9A-Fa-f]+\}|\\.|.)", data[last:], re.DOTALL, ) if not match: break chars.append(len(self.parts)) if match.group(0) == instr: instr = None chars.pop() else: match = re.search(br"""['"]""", data[last:]) if not match: break instr = match.group(0) self.parts.append(data[last : last + match.end(0)]) last += match.end(0) if last != len(data): self.parts.append(data[last:]) if instr is None: break # we hit EOF while looking for end of string, we need to rewind to the state # before we matched on that quote character and try again. idx = None for idx in reversed(range(len(self.parts))): if self.parts[idx].endswith(instr) and idx not in chars: break else: raise RuntimeError("error while backtracking from unmatched " + instr) self.parts, data = self.parts[: idx + 1], b"".join(self.parts[idx + 1 :]) chars = [c for c in chars if c < idx] instr = None # beginning and end are special because we can put them in # self.before/self.after if chars: # merge everything before first char (pre chars[0]) into self.before offset = chars[0] if offset: header, self.parts = b"".join(self.parts[:offset]), self.parts[offset:] self.before = self.before + header # update chars which is a list of offsets into self.parts chars = [c - offset for c in chars] # merge everything after last char (post chars[-1]) into self.after offset = chars[-1] + 1 if offset < len(self.parts): self.parts, footer = self.parts[:offset], b"".join(self.parts[offset:]) self.after = footer + self.after # now scan for chars with a gap > 2 between, which means we can merge # the goal is to take a string like this: # parts = [a x x x b c] # chars = [0 4 5] # and merge it into this: # parts = [a xxx b c] # chars = [0 2 3] for i in range(len(chars) - 1): char1, char2 = chars[i], chars[i + 1] if (char2 - char1) > 2: self.parts[char1 + 1 : char2] = [ b"".join(self.parts[char1 + 1 : char2]) ] offset = char2 - char1 - 2 # num of parts we eliminated chars[i + 1 :] = [c - offset for c in chars[i + 1 :]] # default to everything non-reducible # mark every char index as reducible, so it can be removed self.reducible = [False] * len(self.parts) for idx in chars: self.reducible[idx] = True class TestcaseSymbol(Testcase): """Testcase type for splitting a file before/after a set of delimiters.""" atom = "symbol-delimiter" DEFAULT_CUT_AFTER = b"?=;{[\n" DEFAULT_CUT_BEFORE = b"]}:" args = ("-s", "--symbol") arg_help = ( "Treat the file as a sequence of strings separated by tokens. " "The characters by which the strings are delimited are defined by " "the --cut-before, and --cut-after options." ) def __init__(self) -> None: super().__init__() self._cutter: Optional[Pattern[bytes]] = None self.set_cut_chars(self.DEFAULT_CUT_BEFORE, self.DEFAULT_CUT_AFTER) def set_cut_chars(self, before: bytes, after: bytes) -> None: """Set the bytes used to delimit slice points. Args: before: Split file before these delimiters. after: Split file after these delimiters. """ self._cutter = re.compile( b"[" + before + b"]?" + b"[^" + before + after + b"]*" + b"(?:[" + after + b"]|$|(?=[" + before + b"]))" ) def split_parts(self, data: bytes) -> None: assert self._cutter is not None for statement in self._cutter.finditer(data): if statement.group(0): self.parts.append(statement.group(0)) self.reducible.append(True) def handle_args(self, args: argparse.Namespace) -> None: self.set_cut_chars(args.cut_before, args.cut_after) @classmethod def add_arguments(cls, parser: argparse.ArgumentParser) -> None: grp_add = parser.add_argument_group( description="Additional options for the symbol-delimiter testcase type." ) grp_add.add_argument( "--cut-before", default=cls.DEFAULT_CUT_BEFORE, help="See --symbol. default: " + cls.DEFAULT_CUT_BEFORE.decode("ascii"), ) grp_add.add_argument( "--cut-after", default=cls.DEFAULT_CUT_AFTER, help="See --symbol. default: " + cls.DEFAULT_CUT_AFTER.decode("ascii"), ) class TestcaseAttrs(Testcase): """Testcase file split by anything that looks like an XML attribute.""" atom = "attribute" args = ("-a", "--attrs") arg_help = "Delimit a file by XML attributes." TAG_PATTERN = br"<\s*[A-Za-z][A-Za-z-]*" ATTR_PATTERN = br"((\s+|^)[A-Za-z][A-Za-z0-9:-]*(=|>|\s)|\s*>)" def split_parts(self, data: bytes) -> None: in_tag = False while data: if in_tag: # we're in what looks like an element definition `<tag ...` # look for attributes, or the end `>` match = re.match(self.ATTR_PATTERN, data) if match is None: # before bailing out of the tag, try consuming up to the next space # and resuming the search match = re.search(self.ATTR_PATTERN, data, flags=re.MULTILINE) if match is not None and match.group(0).strip() != b">": LOG.debug("skipping unrecognized data (%r)", match) self.parts.append(data[: match.start(0)]) self.reducible.append(False) data = data[match.start(0) :] continue if match is None or match.group(0).strip() == b">": in_tag = False LOG.debug( "no attribute found (%r) in %r..., looking for other tags", match, data[:20], ) if match is not None: self.parts.append(data[: match.end(0)]) self.reducible.append(False) data = data[match.end(0) :] continue # got an attribute if not match.group(0).endswith(b"="): # value-less attribute, accept and continue # # only consume up to `match.end()-1` because we don't want the # `\s` or `>` that occurred after the attribute. we need to match # that for the next attribute / element end LOG.debug("value-less attribute") self.parts.append(data[: match.end(0) - 1]) self.reducible.append(True) data = data[match.end(0) - 1 :] continue # attribute has a value, need to find it's end attr_parts = [match.group(0)] data = data[match.end(0) :] if data[0:1] in {b"'", b'"'}: # quote delimited string value, look for the end quote attr_parts.append(data[0:1]) data = data[1:] end_match = re.search(attr_parts[-1], data) incl_end = True else: end_match = re.search(br"(\s|>)", data) incl_end = False if end_match is None: # EOF looking for end quote data = b"".join(attr_parts) + data LOG.debug("EOF looking for attr end quote") in_tag = False continue end = end_match.end(0) if not incl_end: end -= 1 attr_parts.append(data[:end]) data = data[end:] self.parts.append(b"".join(attr_parts)) self.reducible.append(True) LOG.debug("found attribute: %r", self.parts[-1]) else: match = re.search(self.TAG_PATTERN, data) if match is None: break LOG.debug("entering tag: %s", match.group(0)) in_tag = True self.parts.append(data[: match.end(0)]) self.reducible.append(False) data = data[match.end(0) :] if data: LOG.debug("remaining data: %s", match and match.group(0)) self.parts.append(data) self.reducible.append(False)
src/lithium/testcases.py
codereval_python_data_186
Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a legacy payload. def identify_request(request: RequestType): """Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a legacy payload. """ # Private encrypted JSON payload try: data = json.loads(decode_if_bytes(request.body)) if "encrypted_magic_envelope" in data: return True except Exception: pass # Public XML payload try: xml = etree.fromstring(encode_if_text(request.body)) if xml.tag == MAGIC_ENV_TAG: return True except Exception: pass return False import json import logging from base64 import urlsafe_b64decode from typing import Callable, Tuple, Union, Dict from urllib.parse import unquote from Crypto.PublicKey.RSA import RsaKey from lxml import etree from federation.entities.mixins import BaseEntity from federation.exceptions import EncryptedMessageError, NoSenderKeyFoundError from federation.protocols.diaspora.encrypted import EncryptedPayload from federation.protocols.diaspora.magic_envelope import MagicEnvelope from federation.types import UserType, RequestType from federation.utils.diaspora import fetch_public_key from federation.utils.text import decode_if_bytes, encode_if_text, validate_handle logger = logging.getLogger("federation") PROTOCOL_NAME = "diaspora" PROTOCOL_NS = "https://joindiaspora.com/protocol" MAGIC_ENV_TAG = "{http://salmon-protocol.org/ns/magic-env}env" def identify_id(id: str) -> bool: """ Try to identify if this ID is a Diaspora ID. """ return validate_handle(id) # noinspection PyBroadException def identify_request(request: RequestType): """Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a legacy payload. """ # Private encrypted JSON payload try: data = json.loads(decode_if_bytes(request.body)) if "encrypted_magic_envelope" in data: return True except Exception: pass # Public XML payload try: xml = etree.fromstring(encode_if_text(request.body)) if xml.tag == MAGIC_ENV_TAG: return True except Exception: pass return False class Protocol: """Diaspora protocol parts Original legacy implementation mostly taken from Pyaspora (https://github.com/lukeross/pyaspora). """ content = None doc = None get_contact_key = None user = None sender_handle = None def get_json_payload_magic_envelope(self, payload): """Encrypted JSON payload""" private_key = self._get_user_key() return EncryptedPayload.decrypt(payload=payload, private_key=private_key) def store_magic_envelope_doc(self, payload): """Get the Magic Envelope, trying JSON first.""" try: json_payload = json.loads(decode_if_bytes(payload)) except ValueError: # XML payload xml = unquote(decode_if_bytes(payload)) xml = xml.lstrip().encode("utf-8") logger.debug("diaspora.protocol.store_magic_envelope_doc: xml payload: %s", xml) self.doc = etree.fromstring(xml) else: logger.debug("diaspora.protocol.store_magic_envelope_doc: json payload: %s", json_payload) self.doc = self.get_json_payload_magic_envelope(json_payload) def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, str]: """Receive a payload. For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified.""" self.user = user self.get_contact_key = sender_key_fetcher self.store_magic_envelope_doc(request.body) # Open payload and get actual message self.content = self.get_message_content() # Get sender handle self.sender_handle = self.get_sender() # Verify the message is from who it claims to be if not skip_author_verification: self.verify_signature() return self.sender_handle, self.content def _get_user_key(self): if not getattr(self.user, "private_key", None): raise EncryptedMessageError("Cannot decrypt private message without user key") return self.user.rsa_private_key def get_sender(self): return MagicEnvelope.get_sender(self.doc) def get_message_content(self): """ Given the Slap XML, extract out the payload. """ body = self.doc.find( ".//{http://salmon-protocol.org/ns/magic-env}data").text body = urlsafe_b64decode(body.encode("ascii")) logger.debug("diaspora.protocol.get_message_content: %s", body) return body def verify_signature(self): """ Verify the signed XML elements to have confidence that the claimed author did actually generate this message. """ if self.get_contact_key: sender_key = self.get_contact_key(self.sender_handle) else: sender_key = fetch_public_key(self.sender_handle) if not sender_key: raise NoSenderKeyFoundError("Could not find a sender contact to retrieve key") MagicEnvelope(doc=self.doc, public_key=sender_key, verify=True) def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]: """ Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Optional) Public key of user we're sending a private payload to. :returns: dict or string depending on if private or public payload. """ if entity.outbound_doc is not None: # Use pregenerated outbound document xml = entity.outbound_doc else: xml = entity.to_xml() me = MagicEnvelope(etree.tostring(xml), private_key=from_user.rsa_private_key, author_handle=from_user.handle) rendered = me.render() if to_user_key: return EncryptedPayload.encrypt(rendered, to_user_key) return rendered
federation/protocols/diaspora/protocol.py
codereval_python_data_187
Try to identify whether this is a Matrix request def identify_request(request: RequestType) -> bool: """ Try to identify whether this is a Matrix request """ # noinspection PyBroadException try: data = json.loads(decode_if_bytes(request.body)) if "events" in data: return True except Exception: pass return False import json import logging import re from typing import Callable, Tuple, List, Dict from federation.entities.matrix.entities import MatrixEntityMixin from federation.types import UserType, RequestType from federation.utils.text import decode_if_bytes logger = logging.getLogger('federation') PROTOCOL_NAME = "activitypub" def identify_id(identifier: str) -> bool: """ Try to identify whether this is a Matrix identifier. TODO fix, not entirely correct.. """ return re.match(r'^[@#!].*:.*$', identifier, flags=re.IGNORECASE) is not None def identify_request(request: RequestType) -> bool: """ Try to identify whether this is a Matrix request """ # noinspection PyBroadException try: data = json.loads(decode_if_bytes(request.body)) if "events" in data: return True except Exception: pass return False class Protocol: actor = None get_contact_key = None payload = None request = None user = None # noinspection PyUnusedLocal @staticmethod def build_send(entity: MatrixEntityMixin, *args, **kwargs) -> List[Dict]: """ Build POST data for sending out to the homeserver. :param entity: The outbound ready entity for this protocol. :returns: list of payloads """ return entity.payloads() def extract_actor(self): # TODO TBD pass def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, dict]: """ Receive a request. Matrix appservices will deliver 1+ events at a time. """ # TODO TBD return self.actor, self.payload
federation/protocols/matrix/protocol.py
codereval_python_data_188
Format a datetime in the way that D* nodes expect. def format_dt(dt): """ Format a datetime in the way that D* nodes expect. """ return ensure_timezone(dt).astimezone(tzutc()).strftime( '%Y-%m-%dT%H:%M:%SZ' ) from dateutil.tz import tzlocal, tzutc from lxml import etree def ensure_timezone(dt, tz=None): """ Make sure the datetime <dt> has a timezone set, using timezone <tz> if it doesn't. <tz> defaults to the local timezone. """ if dt.tzinfo is None: return dt.replace(tzinfo=tz or tzlocal()) else: return dt def format_dt(dt): """ Format a datetime in the way that D* nodes expect. """ return ensure_timezone(dt).astimezone(tzutc()).strftime( '%Y-%m-%dT%H:%M:%SZ' ) def struct_to_xml(node, struct): """ Turn a list of dicts into XML nodes with tag names taken from the dict keys and element text taken from dict values. This is a list of dicts so that the XML nodes can be ordered in the XML output. """ for obj in struct: for k, v in obj.items(): etree.SubElement(node, k).text = v def get_full_xml_representation(entity, private_key): """Get full XML representation of an entity. This contains the <XML><post>..</post></XML> wrapper. Accepts either a Base entity or a Diaspora entity. Author `private_key` must be given so that certain entities can be signed. """ from federation.entities.diaspora.mappers import get_outbound_entity diaspora_entity = get_outbound_entity(entity, private_key) xml = diaspora_entity.to_xml() return "<XML><post>%s</post></XML>" % etree.tostring(xml).decode("utf-8") def add_element_to_doc(doc, tag, value): """Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist.""" element = doc.find(".//%s" % tag) if element is None: element = etree.SubElement(doc, tag) element.text = value
federation/entities/diaspora/utils.py
codereval_python_data_189
Find tags in text. Tries to ignore tags inside code blocks. Optionally, if passed a "replacer", will also replace the tag word with the result of the replacer function called with the tag word. Returns a set of tags and the original or replaced text. def find_tags(text: str, replacer: callable = None) -> Tuple[Set, str]: """Find tags in text. Tries to ignore tags inside code blocks. Optionally, if passed a "replacer", will also replace the tag word with the result of the replacer function called with the tag word. Returns a set of tags and the original or replaced text. """ found_tags = set() # <br> and <p> tags cause issues in us finding words - add some spacing around them new_text = text.replace("<br>", " <br> ").replace("<p>", " <p> ").replace("</p>", " </p> ") lines = new_text.splitlines(keepends=True) final_lines = [] code_block = False final_text = None # Check each line separately for line in lines: final_words = [] if line[0:3] == "```": code_block = not code_block if line.find("#") == -1 or line[0:4] == " " or code_block: # Just add the whole line final_lines.append(line) continue # Check each word separately words = line.split(" ") for word in words: if word.find('#') > -1: candidate = word.strip().strip("([]),.!?:*_%/") if candidate.find('<') > -1 or candidate.find('>') > -1: # Strip html candidate = bleach.clean(word, strip=True) # Now split with slashes candidates = candidate.split("/") to_replace = [] for candidate in candidates: if candidate.startswith("#"): candidate = candidate.strip("#") if test_tag(candidate.lower()): found_tags.add(candidate.lower()) to_replace.append(candidate) if replacer: tag_word = word try: for counter, replacee in enumerate(to_replace, 1): tag_word = tag_word.replace("#%s" % replacee, replacer(replacee)) except Exception: pass final_words.append(tag_word) else: final_words.append(word) else: final_words.append(word) final_lines.append(" ".join(final_words)) if replacer: final_text = "".join(final_lines) if final_text: final_text = final_text.replace(" <br> ", "<br>").replace(" <p> ", "<p>").replace(" </p> ", "</p>") return found_tags, final_text or text import re from typing import Set, Tuple from urllib.parse import urlparse import bleach from bleach import callbacks ILLEGAL_TAG_CHARS = "!#$%^&*+.,@£/()=?`'\\{[]}~;:\"’”—\xa0" def decode_if_bytes(text): try: return text.decode("utf-8") except AttributeError: return text def encode_if_text(text): try: return bytes(text, encoding="utf-8") except TypeError: return text def find_tags(text: str, replacer: callable = None) -> Tuple[Set, str]: """Find tags in text. Tries to ignore tags inside code blocks. Optionally, if passed a "replacer", will also replace the tag word with the result of the replacer function called with the tag word. Returns a set of tags and the original or replaced text. """ found_tags = set() # <br> and <p> tags cause issues in us finding words - add some spacing around them new_text = text.replace("<br>", " <br> ").replace("<p>", " <p> ").replace("</p>", " </p> ") lines = new_text.splitlines(keepends=True) final_lines = [] code_block = False final_text = None # Check each line separately for line in lines: final_words = [] if line[0:3] == "```": code_block = not code_block if line.find("#") == -1 or line[0:4] == " " or code_block: # Just add the whole line final_lines.append(line) continue # Check each word separately words = line.split(" ") for word in words: if word.find('#') > -1: candidate = word.strip().strip("([]),.!?:*_%/") if candidate.find('<') > -1 or candidate.find('>') > -1: # Strip html candidate = bleach.clean(word, strip=True) # Now split with slashes candidates = candidate.split("/") to_replace = [] for candidate in candidates: if candidate.startswith("#"): candidate = candidate.strip("#") if test_tag(candidate.lower()): found_tags.add(candidate.lower()) to_replace.append(candidate) if replacer: tag_word = word try: for counter, replacee in enumerate(to_replace, 1): tag_word = tag_word.replace("#%s" % replacee, replacer(replacee)) except Exception: pass final_words.append(tag_word) else: final_words.append(word) else: final_words.append(word) final_lines.append(" ".join(final_words)) if replacer: final_text = "".join(final_lines) if final_text: final_text = final_text.replace(" <br> ", "<br>").replace(" <p> ", "<p>").replace(" </p> ", "</p>") return found_tags, final_text or text def get_path_from_url(url: str) -> str: """ Return only the path part of an URL. """ parsed = urlparse(url) return parsed.path def process_text_links(text): """Process links in text, adding some attributes and linkifying textual links.""" link_callbacks = [callbacks.nofollow, callbacks.target_blank] def link_attributes(attrs, new=False): """Run standard callbacks except for internal links.""" href_key = (None, "href") if attrs.get(href_key).startswith("/"): return attrs # Run the standard callbacks for callback in link_callbacks: attrs = callback(attrs, new) return attrs return bleach.linkify( text, callbacks=[link_attributes], parse_email=False, skip_tags=["code"], ) def test_tag(tag: str) -> bool: """Test a word whether it could be accepted as a tag.""" if not tag: return False for char in ILLEGAL_TAG_CHARS: if char in tag: return False return True def validate_handle(handle): """ Very basic handle validation as per https://diaspora.github.io/diaspora_federation/federation/types.html#diaspora-id """ return re.match(r"[a-z0-9\-_.]+@[^@/]+\.[^@/]+", handle, flags=re.IGNORECASE) is not None def with_slash(url): if url.endswith('/'): return url return f"{url}/"
federation/utils/text.py
codereval_python_data_190
Process links in text, adding some attributes and linkifying textual links. def process_text_links(text): """Process links in text, adding some attributes and linkifying textual links.""" link_callbacks = [callbacks.nofollow, callbacks.target_blank] def link_attributes(attrs, new=False): """Run standard callbacks except for internal links.""" href_key = (None, "href") if attrs.get(href_key).startswith("/"): return attrs # Run the standard callbacks for callback in link_callbacks: attrs = callback(attrs, new) return attrs return bleach.linkify( text, callbacks=[link_attributes], parse_email=False, skip_tags=["code"], ) import re from typing import Set, Tuple from urllib.parse import urlparse import bleach from bleach import callbacks ILLEGAL_TAG_CHARS = "!#$%^&*+.,@£/()=?`'\\{[]}~;:\"’”—\xa0" def decode_if_bytes(text): try: return text.decode("utf-8") except AttributeError: return text def encode_if_text(text): try: return bytes(text, encoding="utf-8") except TypeError: return text def find_tags(text: str, replacer: callable = None) -> Tuple[Set, str]: """Find tags in text. Tries to ignore tags inside code blocks. Optionally, if passed a "replacer", will also replace the tag word with the result of the replacer function called with the tag word. Returns a set of tags and the original or replaced text. """ found_tags = set() # <br> and <p> tags cause issues in us finding words - add some spacing around them new_text = text.replace("<br>", " <br> ").replace("<p>", " <p> ").replace("</p>", " </p> ") lines = new_text.splitlines(keepends=True) final_lines = [] code_block = False final_text = None # Check each line separately for line in lines: final_words = [] if line[0:3] == "```": code_block = not code_block if line.find("#") == -1 or line[0:4] == " " or code_block: # Just add the whole line final_lines.append(line) continue # Check each word separately words = line.split(" ") for word in words: if word.find('#') > -1: candidate = word.strip().strip("([]),.!?:*_%/") if candidate.find('<') > -1 or candidate.find('>') > -1: # Strip html candidate = bleach.clean(word, strip=True) # Now split with slashes candidates = candidate.split("/") to_replace = [] for candidate in candidates: if candidate.startswith("#"): candidate = candidate.strip("#") if test_tag(candidate.lower()): found_tags.add(candidate.lower()) to_replace.append(candidate) if replacer: tag_word = word try: for counter, replacee in enumerate(to_replace, 1): tag_word = tag_word.replace("#%s" % replacee, replacer(replacee)) except Exception: pass final_words.append(tag_word) else: final_words.append(word) else: final_words.append(word) final_lines.append(" ".join(final_words)) if replacer: final_text = "".join(final_lines) if final_text: final_text = final_text.replace(" <br> ", "<br>").replace(" <p> ", "<p>").replace(" </p> ", "</p>") return found_tags, final_text or text def get_path_from_url(url: str) -> str: """ Return only the path part of an URL. """ parsed = urlparse(url) return parsed.path def process_text_links(text): """Process links in text, adding some attributes and linkifying textual links.""" link_callbacks = [callbacks.nofollow, callbacks.target_blank] def link_attributes(attrs, new=False): """Run standard callbacks except for internal links.""" href_key = (None, "href") if attrs.get(href_key).startswith("/"): return attrs # Run the standard callbacks for callback in link_callbacks: attrs = callback(attrs, new) return attrs return bleach.linkify( text, callbacks=[link_attributes], parse_email=False, skip_tags=["code"], ) def test_tag(tag: str) -> bool: """Test a word whether it could be accepted as a tag.""" if not tag: return False for char in ILLEGAL_TAG_CHARS: if char in tag: return False return True def validate_handle(handle): """ Very basic handle validation as per https://diaspora.github.io/diaspora_federation/federation/types.html#diaspora-id """ return re.match(r"[a-z0-9\-_.]+@[^@/]+\.[^@/]+", handle, flags=re.IGNORECASE) is not None def with_slash(url): if url.endswith('/'): return url return f"{url}/"
federation/utils/text.py
codereval_python_data_191
Fetch the HEAD of the remote url to determine the content type. def fetch_content_type(url: str) -> Optional[str]: """ Fetch the HEAD of the remote url to determine the content type. """ try: response = requests.head(url, headers={'user-agent': USER_AGENT}, timeout=10) except RequestException as ex: logger.warning("fetch_content_type - %s when fetching url %s", ex, url) else: return response.headers.get('Content-Type') import calendar import datetime import logging import re import socket from typing import Optional, Dict from urllib.parse import quote from uuid import uuid4 import requests from requests.exceptions import RequestException, HTTPError, SSLError from requests.exceptions import ConnectionError from requests.structures import CaseInsensitiveDict from federation import __version__ logger = logging.getLogger("federation") USER_AGENT = "python/federation/%s" % __version__ def fetch_content_type(url: str) -> Optional[str]: """ Fetch the HEAD of the remote url to determine the content type. """ try: response = requests.head(url, headers={'user-agent': USER_AGENT}, timeout=10) except RequestException as ex: logger.warning("fetch_content_type - %s when fetching url %s", ex, url) else: return response.headers.get('Content-Type') def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None, **kwargs): """Helper method to fetch remote document. Must be given either the ``url`` or ``host``. If ``url`` is given, only that will be tried without falling back to http from https. If ``host`` given, `path` will be added to it. Will fall back to http on non-success status code. :arg url: Full url to fetch, including protocol :arg host: Domain part only without path or protocol :arg path: Path without domain (defaults to "/") :arg timeout: Seconds to wait for response (defaults to 10) :arg raise_ssl_errors: Pass False if you want to try HTTP even for sites with SSL errors (default True) :arg extra_headers: Optional extra headers dictionary to add to requests :arg kwargs holds extra args passed to requests.get :returns: Tuple of document (str or None), status code (int or None) and error (an exception class instance or None) :raises ValueError: If neither url nor host are given as parameters """ if not url and not host: raise ValueError("Need url or host.") logger.debug("fetch_document: url=%s, host=%s, path=%s, timeout=%s, raise_ssl_errors=%s", url, host, path, timeout, raise_ssl_errors) headers = {'user-agent': USER_AGENT} if extra_headers: headers.update(extra_headers) if url: # Use url since it was given logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers, **kwargs) logger.debug("fetch_document: found document, code %s", response.status_code) response.raise_for_status() return response.text, response.status_code, None except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex # Build url with some little sanitizing host_string = host.replace("http://", "").replace("https://", "").strip("/") path_string = path if path.startswith("/") else "/%s" % path url = "https://%s%s" % (host_string, path_string) logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers) logger.debug("fetch_document: found document, code %s", response.status_code) response.raise_for_status() return response.text, response.status_code, None except (HTTPError, SSLError, ConnectionError) as ex: if isinstance(ex, SSLError) and raise_ssl_errors: logger.debug("fetch_document: exception %s", ex) return None, None, ex # Try http then url = url.replace("https://", "http://") logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers) logger.debug("fetch_document: found document, code %s", response.status_code) response.raise_for_status() return response.text, response.status_code, None except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex def fetch_host_ip(host: str) -> str: """ Fetch ip by host """ try: ip = socket.gethostbyname(host) except socket.gaierror: return '' return ip def fetch_file(url: str, timeout: int = 30, extra_headers: Dict = None) -> str: """ Download a file with a temporary name and return the name. """ headers = {'user-agent': USER_AGENT} if extra_headers: headers.update(extra_headers) response = requests.get(url, timeout=timeout, headers=headers, stream=True) response.raise_for_status() name = f"/tmp/{str(uuid4())}" with open(name, "wb") as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) return name def parse_http_date(date): """ Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. Implementation copied from Django. https://github.com/django/django/blob/master/django/utils/http.py#L157 License: BSD 3-clause """ MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() __D = r'(?P<day>\d{2})' __D2 = r'(?P<day>[ \d]\d)' __M = r'(?P<mon>\w{3})' __Y = r'(?P<year>\d{4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) # email.utils.parsedate() does the job for RFC1123 dates; unfortunately # RFC7231 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: year = int(m.group('year')) if year < 100: if year < 70: year += 2000 else: year += 1900 month = MONTHS.index(m.group('mon').lower()) + 1 day = int(m.group('day')) hour = int(m.group('hour')) min = int(m.group('min')) sec = int(m.group('sec')) result = datetime.datetime(year, month, day, hour, min, sec) return calendar.timegm(result.utctimetuple()) except Exception as exc: raise ValueError("%r is not a valid date" % date) from exc def send_document(url, data, timeout=10, method="post", *args, **kwargs): """Helper method to send a document via POST. Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``. :arg url: Full url to send to, including protocol :arg data: Dictionary (will be form-encoded), bytes, or file-like object to send in the body :arg timeout: Seconds to wait for response (defaults to 10) :arg method: Method to use, defaults to post :returns: Tuple of status code (int or None) and error (exception class instance or None) """ logger.debug("send_document: url=%s, data=%s, timeout=%s, method=%s", url, data, timeout, method) if not method: method = "post" headers = CaseInsensitiveDict({ 'User-Agent': USER_AGENT, }) if "headers" in kwargs: # Update from kwargs headers.update(kwargs.get("headers")) kwargs.update({ "data": data, "timeout": timeout, "headers": headers }) request_func = getattr(requests, method) try: response = request_func(url, *args, **kwargs) logger.debug("send_document: response status code %s", response.status_code) return response.status_code, None # TODO support rate limit 429 code except RequestException as ex: logger.debug("send_document: exception %s", ex) return None, ex def try_retrieve_webfinger_document(handle: str) -> Optional[str]: """ Try to retrieve an RFC7033 webfinger document. Does not raise if it fails. """ try: host = handle.split("@")[1] except AttributeError: logger.warning("retrieve_webfinger_document: invalid handle given: %s", handle) return None document, code, exception = fetch_document( host=host, path="/.well-known/webfinger?resource=acct:%s" % quote(handle), ) if exception: logger.debug("retrieve_webfinger_document: failed to fetch webfinger document: %s, %s", code, exception) return document
federation/utils/network.py
codereval_python_data_192
Test a word whether it could be accepted as a tag. def test_tag(tag: str) -> bool: """Test a word whether it could be accepted as a tag.""" if not tag: return False for char in ILLEGAL_TAG_CHARS: if char in tag: return False return True import re from typing import Set, Tuple from urllib.parse import urlparse import bleach from bleach import callbacks ILLEGAL_TAG_CHARS = "!#$%^&*+.,@£/()=?`'\\{[]}~;:\"’”—\xa0" def decode_if_bytes(text): try: return text.decode("utf-8") except AttributeError: return text def encode_if_text(text): try: return bytes(text, encoding="utf-8") except TypeError: return text def find_tags(text: str, replacer: callable = None) -> Tuple[Set, str]: """Find tags in text. Tries to ignore tags inside code blocks. Optionally, if passed a "replacer", will also replace the tag word with the result of the replacer function called with the tag word. Returns a set of tags and the original or replaced text. """ found_tags = set() # <br> and <p> tags cause issues in us finding words - add some spacing around them new_text = text.replace("<br>", " <br> ").replace("<p>", " <p> ").replace("</p>", " </p> ") lines = new_text.splitlines(keepends=True) final_lines = [] code_block = False final_text = None # Check each line separately for line in lines: final_words = [] if line[0:3] == "```": code_block = not code_block if line.find("#") == -1 or line[0:4] == " " or code_block: # Just add the whole line final_lines.append(line) continue # Check each word separately words = line.split(" ") for word in words: if word.find('#') > -1: candidate = word.strip().strip("([]),.!?:*_%/") if candidate.find('<') > -1 or candidate.find('>') > -1: # Strip html candidate = bleach.clean(word, strip=True) # Now split with slashes candidates = candidate.split("/") to_replace = [] for candidate in candidates: if candidate.startswith("#"): candidate = candidate.strip("#") if test_tag(candidate.lower()): found_tags.add(candidate.lower()) to_replace.append(candidate) if replacer: tag_word = word try: for counter, replacee in enumerate(to_replace, 1): tag_word = tag_word.replace("#%s" % replacee, replacer(replacee)) except Exception: pass final_words.append(tag_word) else: final_words.append(word) else: final_words.append(word) final_lines.append(" ".join(final_words)) if replacer: final_text = "".join(final_lines) if final_text: final_text = final_text.replace(" <br> ", "<br>").replace(" <p> ", "<p>").replace(" </p> ", "</p>") return found_tags, final_text or text def get_path_from_url(url: str) -> str: """ Return only the path part of an URL. """ parsed = urlparse(url) return parsed.path def process_text_links(text): """Process links in text, adding some attributes and linkifying textual links.""" link_callbacks = [callbacks.nofollow, callbacks.target_blank] def link_attributes(attrs, new=False): """Run standard callbacks except for internal links.""" href_key = (None, "href") if attrs.get(href_key).startswith("/"): return attrs # Run the standard callbacks for callback in link_callbacks: attrs = callback(attrs, new) return attrs return bleach.linkify( text, callbacks=[link_attributes], parse_email=False, skip_tags=["code"], ) def test_tag(tag: str) -> bool: """Test a word whether it could be accepted as a tag.""" if not tag: return False for char in ILLEGAL_TAG_CHARS: if char in tag: return False return True def validate_handle(handle): """ Very basic handle validation as per https://diaspora.github.io/diaspora_federation/federation/types.html#diaspora-id """ return re.match(r"[a-z0-9\-_.]+@[^@/]+\.[^@/]+", handle, flags=re.IGNORECASE) is not None def with_slash(url): if url.endswith('/'): return url return f"{url}/"
federation/utils/text.py
codereval_python_data_193
Turn the children of node <xml> into a dict, keyed by tag name. This is only a shallow conversation - child nodes are not recursively processed. def xml_children_as_dict(node): """Turn the children of node <xml> into a dict, keyed by tag name. This is only a shallow conversation - child nodes are not recursively processed. """ return dict((e.tag, e.text) for e in node) import logging from datetime import datetime from typing import Callable, List # noinspection PyPackageRequirements from Crypto.PublicKey.RSA import RsaKey from lxml import etree from federation.entities.base import Comment, Follow, Post, Profile, Reaction, Retraction, Share from federation.entities.diaspora.entities import ( DiasporaComment, DiasporaContact, DiasporaLike, DiasporaPost, DiasporaProfile, DiasporaReshare, DiasporaRetraction, DiasporaImage) from federation.entities.diaspora.mixins import DiasporaRelayableMixin from federation.entities.mixins import BaseEntity from federation.protocols.diaspora.signatures import get_element_child_info from federation.types import UserType, ReceiverVariant from federation.utils.diaspora import retrieve_and_parse_profile logger = logging.getLogger("federation") MAPPINGS = { "status_message": DiasporaPost, "comment": DiasporaComment, "photo": DiasporaImage, "like": DiasporaLike, "profile": DiasporaProfile, "retraction": DiasporaRetraction, "contact": DiasporaContact, "reshare": DiasporaReshare, } TAGS = [ # Order is important. Any top level tags should be before possibly child tags "reshare", "status_message", "comment", "like", "request", "profile", "retraction", "photo", "contact", ] BOOLEAN_KEYS = ( "public", "nsfw", "following", "sharing", ) DATETIME_KEYS = ( "created_at", ) INTEGER_KEYS = ( "height", "width", ) def xml_children_as_dict(node): """Turn the children of node <xml> into a dict, keyed by tag name. This is only a shallow conversation - child nodes are not recursively processed. """ return dict((e.tag, e.text) for e in node) def check_sender_and_entity_handle_match(sender_handle, entity_handle): """Ensure that sender and entity handles match. Basically we've already verified the sender is who they say when receiving the payload. However, the sender might be trying to set another author in the payload itself, since Diaspora has the sender in both the payload headers AND the object. We must ensure they're the same. """ if sender_handle != entity_handle: logger.warning("sender_handle and entity_handle don't match, aborting! sender_handle: %s, entity_handle: %s", sender_handle, entity_handle) return False return True def element_to_objects( element: etree.ElementTree, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None, ) -> List: """Transform an Element to a list of entities recursively. Possible child entities are added to each entity ``_children`` list. Optional parameter ``sender_key_fetcher`` can be a function to fetch sender public key. If not given, key will always be fetched over the network. The function should take sender as the only parameter. """ entities = [] cls = MAPPINGS.get(element.tag) if not cls: return [] attrs = xml_children_as_dict(element) transformed = transform_attributes(attrs, cls) if hasattr(cls, "fill_extra_attributes"): transformed = cls.fill_extra_attributes(transformed) entity = cls(**transformed) # Add protocol name entity._source_protocol = "diaspora" # Save element object to entity for possible later use entity._source_object = etree.tostring(element) # Save receivers on the entity if user: # Single receiver entity._receivers = [UserType(id=user.id, receiver_variant=ReceiverVariant.ACTOR)] else: # Followers entity._receivers = [UserType(id=sender, receiver_variant=ReceiverVariant.FOLLOWERS)] if issubclass(cls, DiasporaRelayableMixin): # If relayable, fetch sender key for validation entity._xml_tags = get_element_child_info(element, "tag") if sender_key_fetcher: entity._sender_key = sender_key_fetcher(entity.actor_id) else: profile = retrieve_and_parse_profile(entity.handle) if profile: entity._sender_key = profile.public_key else: # If not relayable, ensure handles match if not check_sender_and_entity_handle_match(sender, entity.handle): return [] try: entity.validate() except ValueError as ex: logger.error("Failed to validate entity %s: %s", entity, ex, extra={ "attrs": attrs, "transformed": transformed, }) return [] # Extract mentions if hasattr(entity, "extract_mentions"): entity.extract_mentions() # Do child elements for child in element: # noinspection PyProtectedMember entity._children.extend(element_to_objects(child, sender, user=user)) # Add to entities list entities.append(entity) return entities def message_to_objects( message: str, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None, ) -> List: """Takes in a message extracted by a protocol and maps it to entities. :param message: XML payload :type message: str :param sender: Payload sender id :type message: str :param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched over network. The function should take sender handle as the only parameter. :param user: Optional receiving user object. If given, should have a `handle`. :returns: list of entities """ doc = etree.fromstring(message) if doc.tag in TAGS: return element_to_objects(doc, sender, sender_key_fetcher, user) return [] def transform_attributes(attrs, cls): """Transform some attribute keys. :param attrs: Properties from the XML :type attrs: dict :param cls: Class of the entity :type cls: class """ transformed = {} for key, value in attrs.items(): if value is None: value = "" if key == "text": transformed["raw_content"] = value elif key == "activitypub_id": transformed["id"] = value elif key == "author": if cls == DiasporaProfile: # Diaspora Profile XML message contains no GUID. We need the guid. Fetch it. profile = retrieve_and_parse_profile(value) transformed['id'] = value transformed["guid"] = profile.guid else: transformed["actor_id"] = value transformed["handle"] = value elif key == 'guid': if cls != DiasporaProfile: transformed["id"] = value transformed["guid"] = value elif key in ("root_author", "recipient"): transformed["target_id"] = value transformed["target_handle"] = value elif key in ("target_guid", "root_guid", "parent_guid"): transformed["target_id"] = value transformed["target_guid"] = value elif key == "thread_parent_guid": transformed["root_target_id"] = value transformed["root_target_guid"] = value elif key in ("first_name", "last_name"): values = [attrs.get('first_name'), attrs.get('last_name')] values = [v for v in values if v] transformed["name"] = " ".join(values) elif key == "image_url": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["large"] = value elif key == "image_url_small": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["small"] = value elif key == "image_url_medium": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["medium"] = value elif key == "tag_string": if value: transformed["tag_list"] = value.replace("#", "").split(" ") elif key == "bio": transformed["raw_content"] = value elif key == "searchable": transformed["public"] = True if value == "true" else False elif key in ["target_type"] and cls == DiasporaRetraction: transformed["entity_type"] = DiasporaRetraction.entity_type_from_remote(value) elif key == "remote_photo_path": transformed["url"] = f"{value}{attrs.get('remote_photo_name')}" elif key == "author_signature": transformed["signature"] = value elif key in BOOLEAN_KEYS: transformed[key] = True if value == "true" else False elif key in DATETIME_KEYS: transformed[key] = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ") elif key in INTEGER_KEYS: transformed[key] = int(value) else: transformed[key] = value return transformed def get_outbound_entity(entity: BaseEntity, private_key: RsaKey): """Get the correct outbound entity for this protocol. We might have to look at entity values to decide the correct outbound entity. If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol. Private key of author is needed to be passed for signing the outbound entity. :arg entity: An entity instance which can be of a base or protocol entity class. :arg private_key: Private key of sender as an RSA object :returns: Protocol specific entity class instance. :raises ValueError: If conversion cannot be done. """ if getattr(entity, "outbound_doc", None): # If the entity already has an outbound doc, just return the entity as is return entity outbound = None cls = entity.__class__ if cls in [DiasporaPost, DiasporaImage, DiasporaComment, DiasporaLike, DiasporaProfile, DiasporaRetraction, DiasporaContact, DiasporaReshare]: # Already fine outbound = entity elif cls == Post: outbound = DiasporaPost.from_base(entity) elif cls == Comment: outbound = DiasporaComment.from_base(entity) elif cls == Reaction: if entity.reaction == "like": outbound = DiasporaLike.from_base(entity) elif cls == Follow: outbound = DiasporaContact.from_base(entity) elif cls == Profile: outbound = DiasporaProfile.from_base(entity) elif cls == Retraction: outbound = DiasporaRetraction.from_base(entity) elif cls == Share: outbound = DiasporaReshare.from_base(entity) if not outbound: raise ValueError("Don't know how to convert this base entity to Diaspora protocol entities.") if isinstance(outbound, DiasporaRelayableMixin) and not outbound.signature: # Sign by author if not signed yet. We don't want to overwrite any existing signature in the case # that this is being sent by the parent author outbound.sign(private_key) # If missing, also add same signature to `parent_author_signature`. This is required at the moment # in all situations but is apparently being removed. # TODO: remove this once Diaspora removes the extra signature outbound.parent_signature = outbound.signature # Validate the entity outbound.validate(direction="outbound") return outbound
federation/entities/diaspora/mappers.py
codereval_python_data_194
Ensure that sender and entity handles match. Basically we've already verified the sender is who they say when receiving the payload. However, the sender might be trying to set another author in the payload itself, since Diaspora has the sender in both the payload headers AND the object. We must ensure they're the same. def check_sender_and_entity_handle_match(sender_handle, entity_handle): """Ensure that sender and entity handles match. Basically we've already verified the sender is who they say when receiving the payload. However, the sender might be trying to set another author in the payload itself, since Diaspora has the sender in both the payload headers AND the object. We must ensure they're the same. """ if sender_handle != entity_handle: logger.warning("sender_handle and entity_handle don't match, aborting! sender_handle: %s, entity_handle: %s", sender_handle, entity_handle) return False return True import logging from datetime import datetime from typing import Callable, List # noinspection PyPackageRequirements from Crypto.PublicKey.RSA import RsaKey from lxml import etree from federation.entities.base import Comment, Follow, Post, Profile, Reaction, Retraction, Share from federation.entities.diaspora.entities import ( DiasporaComment, DiasporaContact, DiasporaLike, DiasporaPost, DiasporaProfile, DiasporaReshare, DiasporaRetraction, DiasporaImage) from federation.entities.diaspora.mixins import DiasporaRelayableMixin from federation.entities.mixins import BaseEntity from federation.protocols.diaspora.signatures import get_element_child_info from federation.types import UserType, ReceiverVariant from federation.utils.diaspora import retrieve_and_parse_profile logger = logging.getLogger("federation") MAPPINGS = { "status_message": DiasporaPost, "comment": DiasporaComment, "photo": DiasporaImage, "like": DiasporaLike, "profile": DiasporaProfile, "retraction": DiasporaRetraction, "contact": DiasporaContact, "reshare": DiasporaReshare, } TAGS = [ # Order is important. Any top level tags should be before possibly child tags "reshare", "status_message", "comment", "like", "request", "profile", "retraction", "photo", "contact", ] BOOLEAN_KEYS = ( "public", "nsfw", "following", "sharing", ) DATETIME_KEYS = ( "created_at", ) INTEGER_KEYS = ( "height", "width", ) def xml_children_as_dict(node): """Turn the children of node <xml> into a dict, keyed by tag name. This is only a shallow conversation - child nodes are not recursively processed. """ return dict((e.tag, e.text) for e in node) def check_sender_and_entity_handle_match(sender_handle, entity_handle): """Ensure that sender and entity handles match. Basically we've already verified the sender is who they say when receiving the payload. However, the sender might be trying to set another author in the payload itself, since Diaspora has the sender in both the payload headers AND the object. We must ensure they're the same. """ if sender_handle != entity_handle: logger.warning("sender_handle and entity_handle don't match, aborting! sender_handle: %s, entity_handle: %s", sender_handle, entity_handle) return False return True def element_to_objects( element: etree.ElementTree, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None, ) -> List: """Transform an Element to a list of entities recursively. Possible child entities are added to each entity ``_children`` list. Optional parameter ``sender_key_fetcher`` can be a function to fetch sender public key. If not given, key will always be fetched over the network. The function should take sender as the only parameter. """ entities = [] cls = MAPPINGS.get(element.tag) if not cls: return [] attrs = xml_children_as_dict(element) transformed = transform_attributes(attrs, cls) if hasattr(cls, "fill_extra_attributes"): transformed = cls.fill_extra_attributes(transformed) entity = cls(**transformed) # Add protocol name entity._source_protocol = "diaspora" # Save element object to entity for possible later use entity._source_object = etree.tostring(element) # Save receivers on the entity if user: # Single receiver entity._receivers = [UserType(id=user.id, receiver_variant=ReceiverVariant.ACTOR)] else: # Followers entity._receivers = [UserType(id=sender, receiver_variant=ReceiverVariant.FOLLOWERS)] if issubclass(cls, DiasporaRelayableMixin): # If relayable, fetch sender key for validation entity._xml_tags = get_element_child_info(element, "tag") if sender_key_fetcher: entity._sender_key = sender_key_fetcher(entity.actor_id) else: profile = retrieve_and_parse_profile(entity.handle) if profile: entity._sender_key = profile.public_key else: # If not relayable, ensure handles match if not check_sender_and_entity_handle_match(sender, entity.handle): return [] try: entity.validate() except ValueError as ex: logger.error("Failed to validate entity %s: %s", entity, ex, extra={ "attrs": attrs, "transformed": transformed, }) return [] # Extract mentions if hasattr(entity, "extract_mentions"): entity.extract_mentions() # Do child elements for child in element: # noinspection PyProtectedMember entity._children.extend(element_to_objects(child, sender, user=user)) # Add to entities list entities.append(entity) return entities def message_to_objects( message: str, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None, ) -> List: """Takes in a message extracted by a protocol and maps it to entities. :param message: XML payload :type message: str :param sender: Payload sender id :type message: str :param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched over network. The function should take sender handle as the only parameter. :param user: Optional receiving user object. If given, should have a `handle`. :returns: list of entities """ doc = etree.fromstring(message) if doc.tag in TAGS: return element_to_objects(doc, sender, sender_key_fetcher, user) return [] def transform_attributes(attrs, cls): """Transform some attribute keys. :param attrs: Properties from the XML :type attrs: dict :param cls: Class of the entity :type cls: class """ transformed = {} for key, value in attrs.items(): if value is None: value = "" if key == "text": transformed["raw_content"] = value elif key == "activitypub_id": transformed["id"] = value elif key == "author": if cls == DiasporaProfile: # Diaspora Profile XML message contains no GUID. We need the guid. Fetch it. profile = retrieve_and_parse_profile(value) transformed['id'] = value transformed["guid"] = profile.guid else: transformed["actor_id"] = value transformed["handle"] = value elif key == 'guid': if cls != DiasporaProfile: transformed["id"] = value transformed["guid"] = value elif key in ("root_author", "recipient"): transformed["target_id"] = value transformed["target_handle"] = value elif key in ("target_guid", "root_guid", "parent_guid"): transformed["target_id"] = value transformed["target_guid"] = value elif key == "thread_parent_guid": transformed["root_target_id"] = value transformed["root_target_guid"] = value elif key in ("first_name", "last_name"): values = [attrs.get('first_name'), attrs.get('last_name')] values = [v for v in values if v] transformed["name"] = " ".join(values) elif key == "image_url": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["large"] = value elif key == "image_url_small": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["small"] = value elif key == "image_url_medium": if "image_urls" not in transformed: transformed["image_urls"] = {} transformed["image_urls"]["medium"] = value elif key == "tag_string": if value: transformed["tag_list"] = value.replace("#", "").split(" ") elif key == "bio": transformed["raw_content"] = value elif key == "searchable": transformed["public"] = True if value == "true" else False elif key in ["target_type"] and cls == DiasporaRetraction: transformed["entity_type"] = DiasporaRetraction.entity_type_from_remote(value) elif key == "remote_photo_path": transformed["url"] = f"{value}{attrs.get('remote_photo_name')}" elif key == "author_signature": transformed["signature"] = value elif key in BOOLEAN_KEYS: transformed[key] = True if value == "true" else False elif key in DATETIME_KEYS: transformed[key] = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ") elif key in INTEGER_KEYS: transformed[key] = int(value) else: transformed[key] = value return transformed def get_outbound_entity(entity: BaseEntity, private_key: RsaKey): """Get the correct outbound entity for this protocol. We might have to look at entity values to decide the correct outbound entity. If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol. Private key of author is needed to be passed for signing the outbound entity. :arg entity: An entity instance which can be of a base or protocol entity class. :arg private_key: Private key of sender as an RSA object :returns: Protocol specific entity class instance. :raises ValueError: If conversion cannot be done. """ if getattr(entity, "outbound_doc", None): # If the entity already has an outbound doc, just return the entity as is return entity outbound = None cls = entity.__class__ if cls in [DiasporaPost, DiasporaImage, DiasporaComment, DiasporaLike, DiasporaProfile, DiasporaRetraction, DiasporaContact, DiasporaReshare]: # Already fine outbound = entity elif cls == Post: outbound = DiasporaPost.from_base(entity) elif cls == Comment: outbound = DiasporaComment.from_base(entity) elif cls == Reaction: if entity.reaction == "like": outbound = DiasporaLike.from_base(entity) elif cls == Follow: outbound = DiasporaContact.from_base(entity) elif cls == Profile: outbound = DiasporaProfile.from_base(entity) elif cls == Retraction: outbound = DiasporaRetraction.from_base(entity) elif cls == Share: outbound = DiasporaReshare.from_base(entity) if not outbound: raise ValueError("Don't know how to convert this base entity to Diaspora protocol entities.") if isinstance(outbound, DiasporaRelayableMixin) and not outbound.signature: # Sign by author if not signed yet. We don't want to overwrite any existing signature in the case # that this is being sent by the parent author outbound.sign(private_key) # If missing, also add same signature to `parent_author_signature`. This is required at the moment # in all situations but is apparently being removed. # TODO: remove this once Diaspora removes the extra signature outbound.parent_signature = outbound.signature # Validate the entity outbound.validate(direction="outbound") return outbound
federation/entities/diaspora/mappers.py
codereval_python_data_195
Generate a NodeInfo .well-known document. See spec: http://nodeinfo.diaspora.software :arg url: The full base url with protocol, ie https://example.com :arg document_path: Custom NodeInfo document path if supplied (optional) :returns: dict def get_nodeinfo_well_known_document(url, document_path=None): """Generate a NodeInfo .well-known document. See spec: http://nodeinfo.diaspora.software :arg url: The full base url with protocol, ie https://example.com :arg document_path: Custom NodeInfo document path if supplied (optional) :returns: dict """ return { "links": [ { "rel": "http://nodeinfo.diaspora.software/ns/schema/1.0", "href": "{url}{path}".format( url=url, path=document_path or NODEINFO_DOCUMENT_PATH ) } ] } import json import os import warnings from base64 import b64encode from string import Template from typing import Dict from jsonschema import validate from jsonschema.exceptions import ValidationError from xrd import XRD, Link, Element def generate_host_meta(template=None, *args, **kwargs): """Generate a host-meta XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document (str) """ if template == "diaspora": hostmeta = DiasporaHostMeta(*args, **kwargs) else: hostmeta = BaseHostMeta(*args, **kwargs) return hostmeta.render() def generate_legacy_webfinger(template=None, *args, **kwargs): """Generate a legacy webfinger XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document (str) """ if template == "diaspora": webfinger = DiasporaWebFinger(*args, **kwargs) else: webfinger = BaseLegacyWebFinger(*args, **kwargs) return webfinger.render() def generate_nodeinfo2_document(**kwargs): """ Generate a NodeInfo2 document. Pass in a dictionary as per NodeInfo2 1.0 schema: https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json Minimum required schema: {server: baseUrl name software version } openRegistrations Protocols default will match what this library supports, ie "diaspora" currently. :return: dict :raises: KeyError on missing required items """ return { "version": "1.0", "server": { "baseUrl": kwargs['server']['baseUrl'], "name": kwargs['server']['name'], "software": kwargs['server']['software'], "version": kwargs['server']['version'], }, "organization": { "name": kwargs.get('organization', {}).get('name', None), "contact": kwargs.get('organization', {}).get('contact', None), "account": kwargs.get('organization', {}).get('account', None), }, "protocols": kwargs.get('protocols', ["diaspora"]), "relay": kwargs.get('relay', ''), "services": { "inbound": kwargs.get('service', {}).get('inbound', []), "outbound": kwargs.get('service', {}).get('outbound', []), }, "openRegistrations": kwargs['openRegistrations'], "usage": { "users": { "total": kwargs.get('usage', {}).get('users', {}).get('total'), "activeHalfyear": kwargs.get('usage', {}).get('users', {}).get('activeHalfyear'), "activeMonth": kwargs.get('usage', {}).get('users', {}).get('activeMonth'), "activeWeek": kwargs.get('usage', {}).get('users', {}).get('activeWeek'), }, "localPosts": kwargs.get('usage', {}).get('localPosts'), "localComments": kwargs.get('usage', {}).get('localComments'), } } def generate_hcard(template=None, **kwargs): """Generate a hCard document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: HTML document (str) """ if template == "diaspora": hcard = DiasporaHCard(**kwargs) else: raise NotImplementedError() return hcard.render() class BaseHostMeta: def __init__(self, *args, **kwargs): self.xrd = XRD() def render(self): return self.xrd.to_xml().toprettyxml(indent=" ", encoding="UTF-8") class DiasporaHostMeta(BaseHostMeta): """Diaspora host-meta. Required keyword args: * webfinger_host (str) """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) link = Link( rel='lrdd', type_='application/xrd+xml', template='%s/webfinger?q={uri}' % kwargs["webfinger_host"] ) self.xrd.links.append(link) class BaseLegacyWebFinger(BaseHostMeta): """Legacy XRD WebFinger. See: https://code.google.com/p/webfinger/wiki/WebFingerProtocol """ def __init__(self, address, *args, **kwargs): super().__init__(*args, **kwargs) subject = Element("Subject", "acct:%s" % address) self.xrd.elements.append(subject) class DiasporaWebFinger(BaseLegacyWebFinger): """Diaspora version of legacy WebFinger. Required keyword args: * handle (str) - eg user@domain.tld * host (str) - eg https://domain.tld * guid (str) - guid of user * public_key (str) - public key """ def __init__(self, handle, host, guid, public_key, *args, **kwargs): super().__init__(handle, *args, **kwargs) self.xrd.elements.append(Element("Alias", "%s/people/%s" % ( host, guid ))) username = handle.split("@")[0] self.xrd.links.append(Link( rel="http://microformats.org/profile/hcard", type_="text/html", href="%s/hcard/users/%s" %( host, guid ) )) self.xrd.links.append(Link( rel="http://joindiaspora.com/seed_location", type_="text/html", href=host )) self.xrd.links.append(Link( rel="http://joindiaspora.com/guid", type_="text/html", href=guid )) self.xrd.links.append(Link( rel="http://webfinger.net/rel/profile-page", type_="text/html", href="%s/u/%s" % ( host, username ) )) self.xrd.links.append(Link( rel="http://schemas.google.com/g/2010#updates-from", type_="application/atom+xml", href="%s/public/%s.atom" % ( host, username ) )) # Base64 the key # See https://wiki.diasporafoundation.org/Federation_Protocol_Overview#Diaspora_Public_Key try: base64_key = b64encode(bytes(public_key, encoding="UTF-8")).decode("ascii") except TypeError: # Python 2 base64_key = b64encode(public_key).decode("ascii") self.xrd.links.append(Link( rel="diaspora-public-key", type_="RSA", href=base64_key )) class DiasporaHCard: """Diaspora hCard document. Must receive the `required` attributes as keyword arguments to init. """ required = [ "hostname", "fullname", "firstname", "lastname", "photo300", "photo100", "photo50", "searchable", "guid", "public_key", "username", ] def __init__(self, **kwargs): self.kwargs = kwargs template_path = os.path.join(os.path.dirname(__file__), "templates", "hcard_diaspora.html") with open(template_path) as f: self.template = Template(f.read()) def render(self): required = self.required[:] for key, value in self.kwargs.items(): required.remove(key) assert value is not None assert isinstance(value, str) assert len(required) == 0 return self.template.substitute(self.kwargs) class SocialRelayWellKnown: """A `.well-known/social-relay` document in JSON. For apps wanting to announce their preferences towards relay applications. See WIP spec: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts Schema see `schemas/social-relay-well-known.json` :arg subscribe: bool :arg tags: tuple, optional :arg scope: Should be either "all" or "tags", default is "all" if not given """ def __init__(self, subscribe, tags=(), scope="all", *args, **kwargs): self.doc = { "subscribe": subscribe, "scope": scope, "tags": list(tags), } def render(self): self.validate_doc() return json.dumps(self.doc) def validate_doc(self): schema_path = os.path.join(os.path.dirname(__file__), "schemas", "social-relay-well-known.json") with open(schema_path) as f: schema = json.load(f) validate(self.doc, schema) class NodeInfo: """Generate a NodeInfo document. See spec: http://nodeinfo.diaspora.software NodeInfo is unnecessarely restrictive in field values. We wont be supporting such strictness, though we will raise a warning unless validation is skipped with `skip_validate=True`. For strictness, `raise_on_validate=True` will cause a `ValidationError` to be raised. See schema document `federation/hostmeta/schemas/nodeinfo-1.0.json` for how to instantiate this class. """ def __init__(self, software, protocols, services, open_registrations, usage, metadata, skip_validate=False, raise_on_validate=False): self.doc = { "version": "1.0", "software": software, "protocols": protocols, "services": services, "openRegistrations": open_registrations, "usage": usage, "metadata": metadata, } self.skip_validate = skip_validate self.raise_on_validate = raise_on_validate def render(self): if not self.skip_validate: self.validate_doc() return json.dumps(self.doc) def validate_doc(self): schema_path = os.path.join(os.path.dirname(__file__), "schemas", "nodeinfo-1.0.json") with open(schema_path) as f: schema = json.load(f) try: validate(self.doc, schema) except ValidationError: if self.raise_on_validate: raise warnings.warn("NodeInfo document generated does not validate against NodeInfo 1.0 specification.") # The default NodeInfo document path NODEINFO_DOCUMENT_PATH = "/nodeinfo/1.0" def get_nodeinfo_well_known_document(url, document_path=None): """Generate a NodeInfo .well-known document. See spec: http://nodeinfo.diaspora.software :arg url: The full base url with protocol, ie https://example.com :arg document_path: Custom NodeInfo document path if supplied (optional) :returns: dict """ return { "links": [ { "rel": "http://nodeinfo.diaspora.software/ns/schema/1.0", "href": "{url}{path}".format( url=url, path=document_path or NODEINFO_DOCUMENT_PATH ) } ] } class MatrixClientWellKnown: """ Matrix Client well-known as per https://matrix.org/docs/spec/client_server/r0.6.1#server-discovery """ def __init__(self, homeserver_base_url: str, identity_server_base_url: str = None, other_keys: Dict = None): self.homeserver_base_url = homeserver_base_url self.identity_server_base_url = identity_server_base_url self.other_keys = other_keys def render(self): doc = { "m.homeserver": { "base_url": self.homeserver_base_url, } } if self.identity_server_base_url: doc["m.identity_server"] = { "base_url": self.identity_server_base_url, } if self.other_keys: doc.update(self.other_keys) return doc class MatrixServerWellKnown: """ Matrix Server well-known as per https://matrix.org/docs/spec/server_server/r0.1.4#server-discovery """ def __init__(self, homeserver_domain_with_port: str): self.homeserver_domain_with_port = homeserver_domain_with_port def render(self): return { "m.server": self.homeserver_domain_with_port, } class RFC7033Webfinger: """ RFC 7033 webfinger - see https://tools.ietf.org/html/rfc7033 A Django view is also available, see the child ``django`` module for view and url configuration. :param id: Profile ActivityPub ID in URL format :param handle: Profile Diaspora handle :param guid: Profile Diaspora guid :param base_url: The base URL of the server (protocol://domain.tld) :param profile_path: Profile path for the user (for example `/profile/johndoe/`) :param hcard_path: (Optional) hCard path, defaults to ``/hcard/users/``. :param atom_path: (Optional) atom feed path :returns: dict """ def __init__( self, id: str, handle: str, guid: str, base_url: str, profile_path: str, hcard_path: str="/hcard/users/", atom_path: str=None, search_path: str=None, ): self.id = id self.handle = handle self.guid = guid self.base_url = base_url self.hcard_path = hcard_path self.profile_path = profile_path self.atom_path = atom_path self.search_path = search_path def render(self): webfinger = { "subject": "acct:%s" % self.handle, "aliases": [ f"{self.base_url}{self.profile_path}", self.id, ], "links": [ { "rel": "http://microformats.org/profile/hcard", "type": "text/html", "href": "%s%s%s" % (self.base_url, self.hcard_path, self.guid), }, { "rel": "http://joindiaspora.com/seed_location", "type": "text/html", "href": self.base_url, }, { "rel": "http://webfinger.net/rel/profile-page", "type": "text/html", "href": "%s%s" % (self.base_url, self.profile_path), }, { "rel": "salmon", "href": "%s/receive/users/%s" % (self.base_url, self.guid), }, ], } webfinger["links"].append({ "rel": "self", "href": self.id, "type": "application/activity+json", }) if self.atom_path: webfinger['links'].append( { "rel": "http://schemas.google.com/g/2010#updates-from", "type": "application/atom+xml", "href": "%s%s" % (self.base_url, self.atom_path), } ) if self.search_path: webfinger['links'].append( { "rel": "http://ostatus.org/schema/1.0/subscribe", "template": "%s%s{uri}" % (self.base_url, self.search_path), }, ) return webfinger
federation/hostmeta/generators.py
codereval_python_data_196
Verify the signed XML elements to have confidence that the claimed author did actually generate this message. def verify_relayable_signature(public_key, doc, signature): """ Verify the signed XML elements to have confidence that the claimed author did actually generate this message. """ sig_hash = _create_signature_hash(doc) cipher = PKCS1_v1_5.new(RSA.importKey(public_key)) return cipher.verify(sig_hash, b64decode(signature)) from base64 import b64decode, b64encode from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto.PublicKey.RSA import RsaKey from Crypto.Signature import PKCS1_v1_5 def get_element_child_info(doc, attr): """Get information from child elements of this elementas a list since order is important. Don't include signature tags. :param doc: XML element :param attr: Attribute to get from the elements, for example "tag" or "text". """ props = [] for child in doc: if child.tag not in ["author_signature", "parent_author_signature"]: props.append(getattr(child, attr)) return props def _create_signature_hash(doc): props = get_element_child_info(doc, "text") content = ";".join(props) return SHA256.new(content.encode("utf-8")) def verify_relayable_signature(public_key, doc, signature): """ Verify the signed XML elements to have confidence that the claimed author did actually generate this message. """ sig_hash = _create_signature_hash(doc) cipher = PKCS1_v1_5.new(RSA.importKey(public_key)) return cipher.verify(sig_hash, b64decode(signature)) def create_relayable_signature(private_key: RsaKey, doc): sig_hash = _create_signature_hash(doc) cipher = PKCS1_v1_5.new(private_key) return b64encode(cipher.sign(sig_hash)).decode("ascii")
federation/protocols/diaspora/signatures.py
codereval_python_data_197
Parse Diaspora webfinger which is either in JSON format (new) or XRD (old). https://diaspora.github.io/diaspora_federation/discovery/webfinger.html def parse_diaspora_webfinger(document: str) -> Dict: """ Parse Diaspora webfinger which is either in JSON format (new) or XRD (old). https://diaspora.github.io/diaspora_federation/discovery/webfinger.html """ webfinger = { "hcard_url": None, } # noinspection PyBroadException try: doc = json.loads(document) for link in doc["links"]: if link["rel"] == "http://microformats.org/profile/hcard": webfinger["hcard_url"] = link["href"] break else: logger.warning("parse_diaspora_webfinger: found JSON webfinger but it has no hcard href") raise ValueError except Exception: try: xrd = XRD.parse_xrd(document) webfinger["hcard_url"] = xrd.find_link(rels="http://microformats.org/profile/hcard").href except (xml.parsers.expat.ExpatError, TypeError): logger.warning("parse_diaspora_webfinger: found XML webfinger but it fails to parse") pass return webfinger import json import logging import xml from typing import Callable, Dict from urllib.parse import quote from lxml import html from xrd import XRD from federation.inbound import handle_receive from federation.types import RequestType from federation.utils.network import fetch_document, try_retrieve_webfinger_document from federation.utils.text import validate_handle logger = logging.getLogger("federation") def fetch_public_key(handle): """Fetch public key over the network. :param handle: Remote handle to retrieve public key for. :return: Public key in str format from parsed profile. """ profile = retrieve_and_parse_profile(handle) return profile.public_key def parse_diaspora_webfinger(document: str) -> Dict: """ Parse Diaspora webfinger which is either in JSON format (new) or XRD (old). https://diaspora.github.io/diaspora_federation/discovery/webfinger.html """ webfinger = { "hcard_url": None, } # noinspection PyBroadException try: doc = json.loads(document) for link in doc["links"]: if link["rel"] == "http://microformats.org/profile/hcard": webfinger["hcard_url"] = link["href"] break else: logger.warning("parse_diaspora_webfinger: found JSON webfinger but it has no hcard href") raise ValueError except Exception: try: xrd = XRD.parse_xrd(document) webfinger["hcard_url"] = xrd.find_link(rels="http://microformats.org/profile/hcard").href except (xml.parsers.expat.ExpatError, TypeError): logger.warning("parse_diaspora_webfinger: found XML webfinger but it fails to parse") pass return webfinger def retrieve_diaspora_hcard(handle): """ Retrieve a remote Diaspora hCard document. :arg handle: Remote handle to retrieve :return: str (HTML document) """ webfinger = retrieve_and_parse_diaspora_webfinger(handle) document, code, exception = fetch_document(webfinger.get("hcard_url")) if exception: return None return document def retrieve_and_parse_diaspora_webfinger(handle): """ Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict """ document = try_retrieve_webfinger_document(handle) if document: return parse_diaspora_webfinger(document) host = handle.split("@")[1] hostmeta = retrieve_diaspora_host_meta(host) if not hostmeta: return None url = hostmeta.find_link(rels="lrdd").template.replace("{uri}", quote(handle)) document, code, exception = fetch_document(url) if exception: return None return parse_diaspora_webfinger(document) def retrieve_diaspora_host_meta(host): """ Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance """ document, code, exception = fetch_document(host=host, path="/.well-known/host-meta") if exception: return None xrd = XRD.parse_xrd(document) return xrd def _get_element_text_or_none(document, selector): """ Using a CSS selector, get the element and return the text, or None if no element. :arg document: ``HTMLElement`` document :arg selector: CSS selector :returns: str or None """ element = document.cssselect(selector) if element: return element[0].text return None def _get_element_attr_or_none(document, selector, attribute): """ Using a CSS selector, get the element and return the given attribute value, or None if no element. Args: document (HTMLElement) - HTMLElement document selector (str) - CSS selector attribute (str) - The attribute to get from the element """ element = document.cssselect(selector) if element: return element[0].get(attribute) return None def parse_profile_from_hcard(hcard: str, handle: str): """ Parse all the fields we can from a hCard document to get a Profile. :arg hcard: HTML hcard document (str) :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance """ from federation.entities.diaspora.entities import DiasporaProfile # Circulars doc = html.fromstring(hcard) profile = DiasporaProfile( name=_get_element_text_or_none(doc, ".fn"), image_urls={ "small": _get_element_attr_or_none(doc, ".entity_photo_small .photo", "src"), "medium": _get_element_attr_or_none(doc, ".entity_photo_medium .photo", "src"), "large": _get_element_attr_or_none(doc, ".entity_photo .photo", "src"), }, public=True, id=handle, handle=handle, guid=_get_element_text_or_none(doc, ".uid"), public_key=_get_element_text_or_none(doc, ".key"), username=handle.split('@')[0], _source_protocol="diaspora", ) return profile def retrieve_and_parse_content( id: str, guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None): """Retrieve remote content and return an Entity class instance. This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive". :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used to fetch the profile and the key. Function must take handle as only parameter and return a public key. :returns: Entity object instance or ``None`` """ if not validate_handle(handle): return _username, domain = handle.split("@") url = get_fetch_content_endpoint(domain, entity_type.lower(), guid) document, status_code, error = fetch_document(url) if status_code == 200: request = RequestType(body=document) _sender, _protocol, entities = handle_receive(request, sender_key_fetcher=sender_key_fetcher) if len(entities) > 1: logger.warning("retrieve_and_parse_content - more than one entity parsed from remote even though we" "expected only one! ID %s", guid) if entities: return entities[0] return elif status_code == 404: logger.warning("retrieve_and_parse_content - remote content %s not found", guid) return if error: raise error raise Exception("retrieve_and_parse_content - unknown problem when fetching document: %s, %s, %s" % ( document, status_code, error, )) def retrieve_and_parse_profile(handle): """ Retrieve the remote user and return a Profile object. :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.Profile`` instance or None """ hcard = retrieve_diaspora_hcard(handle) if not hcard: return None profile = parse_profile_from_hcard(hcard, handle) try: profile.validate() except ValueError as ex: logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s", profile, ex) return None return profile def get_fetch_content_endpoint(domain, entity_type, guid): """Get remote fetch content endpoint. See: https://diaspora.github.io/diaspora_federation/federation/fetching.html """ return "https://%s/fetch/%s/%s" % (domain, entity_type, guid) def get_public_endpoint(id: str) -> str: """Get remote endpoint for delivering public payloads.""" _username, domain = id.split("@") return "https://%s/receive/public" % domain def get_private_endpoint(id: str, guid: str) -> str: """Get remote endpoint for delivering private payloads.""" _username, domain = id.split("@") return "https://%s/receive/users/%s" % (domain, guid)
federation/utils/diaspora.py
codereval_python_data_198
Try to retrieve an RFC7033 webfinger document. Does not raise if it fails. def try_retrieve_webfinger_document(handle: str) -> Optional[str]: """ Try to retrieve an RFC7033 webfinger document. Does not raise if it fails. """ try: host = handle.split("@")[1] except AttributeError: logger.warning("retrieve_webfinger_document: invalid handle given: %s", handle) return None document, code, exception = fetch_document( host=host, path="/.well-known/webfinger?resource=acct:%s" % quote(handle), ) if exception: logger.debug("retrieve_webfinger_document: failed to fetch webfinger document: %s, %s", code, exception) return document import calendar import datetime import logging import re import socket from typing import Optional, Dict from urllib.parse import quote from uuid import uuid4 import requests from requests.exceptions import RequestException, HTTPError, SSLError from requests.exceptions import ConnectionError from requests.structures import CaseInsensitiveDict from federation import __version__ logger = logging.getLogger("federation") USER_AGENT = "python/federation/%s" % __version__ def fetch_content_type(url: str) -> Optional[str]: """ Fetch the HEAD of the remote url to determine the content type. """ try: response = requests.head(url, headers={'user-agent': USER_AGENT}, timeout=10) except RequestException as ex: logger.warning("fetch_content_type - %s when fetching url %s", ex, url) else: return response.headers.get('Content-Type') def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None, **kwargs): """Helper method to fetch remote document. Must be given either the ``url`` or ``host``. If ``url`` is given, only that will be tried without falling back to http from https. If ``host`` given, `path` will be added to it. Will fall back to http on non-success status code. :arg url: Full url to fetch, including protocol :arg host: Domain part only without path or protocol :arg path: Path without domain (defaults to "/") :arg timeout: Seconds to wait for response (defaults to 10) :arg raise_ssl_errors: Pass False if you want to try HTTP even for sites with SSL errors (default True) :arg extra_headers: Optional extra headers dictionary to add to requests :arg kwargs holds extra args passed to requests.get :returns: Tuple of document (str or None), status code (int or None) and error (an exception class instance or None) :raises ValueError: If neither url nor host are given as parameters """ if not url and not host: raise ValueError("Need url or host.") logger.debug("fetch_document: url=%s, host=%s, path=%s, timeout=%s, raise_ssl_errors=%s", url, host, path, timeout, raise_ssl_errors) headers = {'user-agent': USER_AGENT} if extra_headers: headers.update(extra_headers) if url: # Use url since it was given logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers, **kwargs) logger.debug("fetch_document: found document, code %s", response.status_code) response.raise_for_status() return response.text, response.status_code, None except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex # Build url with some little sanitizing host_string = host.replace("http://", "").replace("https://", "").strip("/") path_string = path if path.startswith("/") else "/%s" % path url = "https://%s%s" % (host_string, path_string) logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers) logger.debug("fetch_document: found document, code %s", response.status_code) response.raise_for_status() return response.text, response.status_code, None except (HTTPError, SSLError, ConnectionError) as ex: if isinstance(ex, SSLError) and raise_ssl_errors: logger.debug("fetch_document: exception %s", ex) return None, None, ex # Try http then url = url.replace("https://", "http://") logger.debug("fetch_document: trying %s", url) try: response = requests.get(url, timeout=timeout, headers=headers) logger.debug("fetch_document: found document, code %s", response.status_code) response.raise_for_status() return response.text, response.status_code, None except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex except RequestException as ex: logger.debug("fetch_document: exception %s", ex) return None, None, ex def fetch_host_ip(host: str) -> str: """ Fetch ip by host """ try: ip = socket.gethostbyname(host) except socket.gaierror: return '' return ip def fetch_file(url: str, timeout: int = 30, extra_headers: Dict = None) -> str: """ Download a file with a temporary name and return the name. """ headers = {'user-agent': USER_AGENT} if extra_headers: headers.update(extra_headers) response = requests.get(url, timeout=timeout, headers=headers, stream=True) response.raise_for_status() name = f"/tmp/{str(uuid4())}" with open(name, "wb") as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) return name def parse_http_date(date): """ Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. Implementation copied from Django. https://github.com/django/django/blob/master/django/utils/http.py#L157 License: BSD 3-clause """ MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() __D = r'(?P<day>\d{2})' __D2 = r'(?P<day>[ \d]\d)' __M = r'(?P<mon>\w{3})' __Y = r'(?P<year>\d{4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) # email.utils.parsedate() does the job for RFC1123 dates; unfortunately # RFC7231 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: year = int(m.group('year')) if year < 100: if year < 70: year += 2000 else: year += 1900 month = MONTHS.index(m.group('mon').lower()) + 1 day = int(m.group('day')) hour = int(m.group('hour')) min = int(m.group('min')) sec = int(m.group('sec')) result = datetime.datetime(year, month, day, hour, min, sec) return calendar.timegm(result.utctimetuple()) except Exception as exc: raise ValueError("%r is not a valid date" % date) from exc def send_document(url, data, timeout=10, method="post", *args, **kwargs): """Helper method to send a document via POST. Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``. :arg url: Full url to send to, including protocol :arg data: Dictionary (will be form-encoded), bytes, or file-like object to send in the body :arg timeout: Seconds to wait for response (defaults to 10) :arg method: Method to use, defaults to post :returns: Tuple of status code (int or None) and error (exception class instance or None) """ logger.debug("send_document: url=%s, data=%s, timeout=%s, method=%s", url, data, timeout, method) if not method: method = "post" headers = CaseInsensitiveDict({ 'User-Agent': USER_AGENT, }) if "headers" in kwargs: # Update from kwargs headers.update(kwargs.get("headers")) kwargs.update({ "data": data, "timeout": timeout, "headers": headers }) request_func = getattr(requests, method) try: response = request_func(url, *args, **kwargs) logger.debug("send_document: response status code %s", response.status_code) return response.status_code, None # TODO support rate limit 429 code except RequestException as ex: logger.debug("send_document: exception %s", ex) return None, ex def try_retrieve_webfinger_document(handle: str) -> Optional[str]: """ Try to retrieve an RFC7033 webfinger document. Does not raise if it fails. """ try: host = handle.split("@")[1] except AttributeError: logger.warning("retrieve_webfinger_document: invalid handle given: %s", handle) return None document, code, exception = fetch_document( host=host, path="/.well-known/webfinger?resource=acct:%s" % quote(handle), ) if exception: logger.debug("retrieve_webfinger_document: failed to fetch webfinger document: %s, %s", code, exception) return document
federation/utils/network.py
codereval_python_data_199
Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict def retrieve_and_parse_diaspora_webfinger(handle): """ Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict """ document = try_retrieve_webfinger_document(handle) if document: return parse_diaspora_webfinger(document) host = handle.split("@")[1] hostmeta = retrieve_diaspora_host_meta(host) if not hostmeta: return None url = hostmeta.find_link(rels="lrdd").template.replace("{uri}", quote(handle)) document, code, exception = fetch_document(url) if exception: return None return parse_diaspora_webfinger(document) import json import logging import xml from typing import Callable, Dict from urllib.parse import quote from lxml import html from xrd import XRD from federation.inbound import handle_receive from federation.types import RequestType from federation.utils.network import fetch_document, try_retrieve_webfinger_document from federation.utils.text import validate_handle logger = logging.getLogger("federation") def fetch_public_key(handle): """Fetch public key over the network. :param handle: Remote handle to retrieve public key for. :return: Public key in str format from parsed profile. """ profile = retrieve_and_parse_profile(handle) return profile.public_key def parse_diaspora_webfinger(document: str) -> Dict: """ Parse Diaspora webfinger which is either in JSON format (new) or XRD (old). https://diaspora.github.io/diaspora_federation/discovery/webfinger.html """ webfinger = { "hcard_url": None, } # noinspection PyBroadException try: doc = json.loads(document) for link in doc["links"]: if link["rel"] == "http://microformats.org/profile/hcard": webfinger["hcard_url"] = link["href"] break else: logger.warning("parse_diaspora_webfinger: found JSON webfinger but it has no hcard href") raise ValueError except Exception: try: xrd = XRD.parse_xrd(document) webfinger["hcard_url"] = xrd.find_link(rels="http://microformats.org/profile/hcard").href except (xml.parsers.expat.ExpatError, TypeError): logger.warning("parse_diaspora_webfinger: found XML webfinger but it fails to parse") pass return webfinger def retrieve_diaspora_hcard(handle): """ Retrieve a remote Diaspora hCard document. :arg handle: Remote handle to retrieve :return: str (HTML document) """ webfinger = retrieve_and_parse_diaspora_webfinger(handle) document, code, exception = fetch_document(webfinger.get("hcard_url")) if exception: return None return document def retrieve_and_parse_diaspora_webfinger(handle): """ Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict """ document = try_retrieve_webfinger_document(handle) if document: return parse_diaspora_webfinger(document) host = handle.split("@")[1] hostmeta = retrieve_diaspora_host_meta(host) if not hostmeta: return None url = hostmeta.find_link(rels="lrdd").template.replace("{uri}", quote(handle)) document, code, exception = fetch_document(url) if exception: return None return parse_diaspora_webfinger(document) def retrieve_diaspora_host_meta(host): """ Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance """ document, code, exception = fetch_document(host=host, path="/.well-known/host-meta") if exception: return None xrd = XRD.parse_xrd(document) return xrd def _get_element_text_or_none(document, selector): """ Using a CSS selector, get the element and return the text, or None if no element. :arg document: ``HTMLElement`` document :arg selector: CSS selector :returns: str or None """ element = document.cssselect(selector) if element: return element[0].text return None def _get_element_attr_or_none(document, selector, attribute): """ Using a CSS selector, get the element and return the given attribute value, or None if no element. Args: document (HTMLElement) - HTMLElement document selector (str) - CSS selector attribute (str) - The attribute to get from the element """ element = document.cssselect(selector) if element: return element[0].get(attribute) return None def parse_profile_from_hcard(hcard: str, handle: str): """ Parse all the fields we can from a hCard document to get a Profile. :arg hcard: HTML hcard document (str) :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance """ from federation.entities.diaspora.entities import DiasporaProfile # Circulars doc = html.fromstring(hcard) profile = DiasporaProfile( name=_get_element_text_or_none(doc, ".fn"), image_urls={ "small": _get_element_attr_or_none(doc, ".entity_photo_small .photo", "src"), "medium": _get_element_attr_or_none(doc, ".entity_photo_medium .photo", "src"), "large": _get_element_attr_or_none(doc, ".entity_photo .photo", "src"), }, public=True, id=handle, handle=handle, guid=_get_element_text_or_none(doc, ".uid"), public_key=_get_element_text_or_none(doc, ".key"), username=handle.split('@')[0], _source_protocol="diaspora", ) return profile def retrieve_and_parse_content( id: str, guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None): """Retrieve remote content and return an Entity class instance. This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive". :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used to fetch the profile and the key. Function must take handle as only parameter and return a public key. :returns: Entity object instance or ``None`` """ if not validate_handle(handle): return _username, domain = handle.split("@") url = get_fetch_content_endpoint(domain, entity_type.lower(), guid) document, status_code, error = fetch_document(url) if status_code == 200: request = RequestType(body=document) _sender, _protocol, entities = handle_receive(request, sender_key_fetcher=sender_key_fetcher) if len(entities) > 1: logger.warning("retrieve_and_parse_content - more than one entity parsed from remote even though we" "expected only one! ID %s", guid) if entities: return entities[0] return elif status_code == 404: logger.warning("retrieve_and_parse_content - remote content %s not found", guid) return if error: raise error raise Exception("retrieve_and_parse_content - unknown problem when fetching document: %s, %s, %s" % ( document, status_code, error, )) def retrieve_and_parse_profile(handle): """ Retrieve the remote user and return a Profile object. :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.Profile`` instance or None """ hcard = retrieve_diaspora_hcard(handle) if not hcard: return None profile = parse_profile_from_hcard(hcard, handle) try: profile.validate() except ValueError as ex: logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s", profile, ex) return None return profile def get_fetch_content_endpoint(domain, entity_type, guid): """Get remote fetch content endpoint. See: https://diaspora.github.io/diaspora_federation/federation/fetching.html """ return "https://%s/fetch/%s/%s" % (domain, entity_type, guid) def get_public_endpoint(id: str) -> str: """Get remote endpoint for delivering public payloads.""" _username, domain = id.split("@") return "https://%s/receive/public" % domain def get_private_endpoint(id: str, guid: str) -> str: """Get remote endpoint for delivering private payloads.""" _username, domain = id.split("@") return "https://%s/receive/users/%s" % (domain, guid)
federation/utils/diaspora.py
codereval_python_data_200
Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance def retrieve_diaspora_host_meta(host): """ Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance """ document, code, exception = fetch_document(host=host, path="/.well-known/host-meta") if exception: return None xrd = XRD.parse_xrd(document) return xrd import json import logging import xml from typing import Callable, Dict from urllib.parse import quote from lxml import html from xrd import XRD from federation.inbound import handle_receive from federation.types import RequestType from federation.utils.network import fetch_document, try_retrieve_webfinger_document from federation.utils.text import validate_handle logger = logging.getLogger("federation") def fetch_public_key(handle): """Fetch public key over the network. :param handle: Remote handle to retrieve public key for. :return: Public key in str format from parsed profile. """ profile = retrieve_and_parse_profile(handle) return profile.public_key def parse_diaspora_webfinger(document: str) -> Dict: """ Parse Diaspora webfinger which is either in JSON format (new) or XRD (old). https://diaspora.github.io/diaspora_federation/discovery/webfinger.html """ webfinger = { "hcard_url": None, } # noinspection PyBroadException try: doc = json.loads(document) for link in doc["links"]: if link["rel"] == "http://microformats.org/profile/hcard": webfinger["hcard_url"] = link["href"] break else: logger.warning("parse_diaspora_webfinger: found JSON webfinger but it has no hcard href") raise ValueError except Exception: try: xrd = XRD.parse_xrd(document) webfinger["hcard_url"] = xrd.find_link(rels="http://microformats.org/profile/hcard").href except (xml.parsers.expat.ExpatError, TypeError): logger.warning("parse_diaspora_webfinger: found XML webfinger but it fails to parse") pass return webfinger def retrieve_diaspora_hcard(handle): """ Retrieve a remote Diaspora hCard document. :arg handle: Remote handle to retrieve :return: str (HTML document) """ webfinger = retrieve_and_parse_diaspora_webfinger(handle) document, code, exception = fetch_document(webfinger.get("hcard_url")) if exception: return None return document def retrieve_and_parse_diaspora_webfinger(handle): """ Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict """ document = try_retrieve_webfinger_document(handle) if document: return parse_diaspora_webfinger(document) host = handle.split("@")[1] hostmeta = retrieve_diaspora_host_meta(host) if not hostmeta: return None url = hostmeta.find_link(rels="lrdd").template.replace("{uri}", quote(handle)) document, code, exception = fetch_document(url) if exception: return None return parse_diaspora_webfinger(document) def retrieve_diaspora_host_meta(host): """ Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance """ document, code, exception = fetch_document(host=host, path="/.well-known/host-meta") if exception: return None xrd = XRD.parse_xrd(document) return xrd def _get_element_text_or_none(document, selector): """ Using a CSS selector, get the element and return the text, or None if no element. :arg document: ``HTMLElement`` document :arg selector: CSS selector :returns: str or None """ element = document.cssselect(selector) if element: return element[0].text return None def _get_element_attr_or_none(document, selector, attribute): """ Using a CSS selector, get the element and return the given attribute value, or None if no element. Args: document (HTMLElement) - HTMLElement document selector (str) - CSS selector attribute (str) - The attribute to get from the element """ element = document.cssselect(selector) if element: return element[0].get(attribute) return None def parse_profile_from_hcard(hcard: str, handle: str): """ Parse all the fields we can from a hCard document to get a Profile. :arg hcard: HTML hcard document (str) :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance """ from federation.entities.diaspora.entities import DiasporaProfile # Circulars doc = html.fromstring(hcard) profile = DiasporaProfile( name=_get_element_text_or_none(doc, ".fn"), image_urls={ "small": _get_element_attr_or_none(doc, ".entity_photo_small .photo", "src"), "medium": _get_element_attr_or_none(doc, ".entity_photo_medium .photo", "src"), "large": _get_element_attr_or_none(doc, ".entity_photo .photo", "src"), }, public=True, id=handle, handle=handle, guid=_get_element_text_or_none(doc, ".uid"), public_key=_get_element_text_or_none(doc, ".key"), username=handle.split('@')[0], _source_protocol="diaspora", ) return profile def retrieve_and_parse_content( id: str, guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None): """Retrieve remote content and return an Entity class instance. This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive". :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used to fetch the profile and the key. Function must take handle as only parameter and return a public key. :returns: Entity object instance or ``None`` """ if not validate_handle(handle): return _username, domain = handle.split("@") url = get_fetch_content_endpoint(domain, entity_type.lower(), guid) document, status_code, error = fetch_document(url) if status_code == 200: request = RequestType(body=document) _sender, _protocol, entities = handle_receive(request, sender_key_fetcher=sender_key_fetcher) if len(entities) > 1: logger.warning("retrieve_and_parse_content - more than one entity parsed from remote even though we" "expected only one! ID %s", guid) if entities: return entities[0] return elif status_code == 404: logger.warning("retrieve_and_parse_content - remote content %s not found", guid) return if error: raise error raise Exception("retrieve_and_parse_content - unknown problem when fetching document: %s, %s, %s" % ( document, status_code, error, )) def retrieve_and_parse_profile(handle): """ Retrieve the remote user and return a Profile object. :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.Profile`` instance or None """ hcard = retrieve_diaspora_hcard(handle) if not hcard: return None profile = parse_profile_from_hcard(hcard, handle) try: profile.validate() except ValueError as ex: logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s", profile, ex) return None return profile def get_fetch_content_endpoint(domain, entity_type, guid): """Get remote fetch content endpoint. See: https://diaspora.github.io/diaspora_federation/federation/fetching.html """ return "https://%s/fetch/%s/%s" % (domain, entity_type, guid) def get_public_endpoint(id: str) -> str: """Get remote endpoint for delivering public payloads.""" _username, domain = id.split("@") return "https://%s/receive/public" % domain def get_private_endpoint(id: str, guid: str) -> str: """Get remote endpoint for delivering private payloads.""" _username, domain = id.split("@") return "https://%s/receive/users/%s" % (domain, guid)
federation/utils/diaspora.py