text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tags(): "Get a set of tags for the current git repo." result = [t.decode('ascii') for t in subprocess.check_output([ 'git', 'tag' ]).split(b"\n")] assert len(set(result)) == len(result) return set(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_tag_and_push(version): "Create a git tag for `version` and push it to origin." assert version not in tags() git('config', 'user.name', 'Travis CI on behalf of Austin Bingham') git('config', 'user.email', 'austin@sixty-north.com') git('config', 'core.sshCommand', 'ssh -i deploy_key') git( 'remote', 'add', 'ssh-origin', 'git@github.com:sixty-north/cosmic-ray.git' ) git('tag', version) subprocess.check_call([ 'ssh-agent', 'sh', '-c', 'chmod 0600 deploy_key && ' + 'ssh-add deploy_key && ' + # 'git push ssh-origin HEAD:master &&' 'git push ssh-origin --tags' ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def worker_task(work_item, config): """The celery task which performs a single mutation and runs a test suite. This runs `cosmic-ray worker` in a subprocess and returns the results, passing `config` to it via stdin. Args: work_item: A dict describing a WorkItem. config: The configuration to use for the test execution. Returns: An updated WorkItem """
global _workspace _ensure_workspace(config) result = worker( work_item.module_path, config.python_version, work_item.operator_name, work_item.occurrence, config.test_command, config.timeout) return work_item.job_id, result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_work_items(work_items, config): """Execute a suite of tests for a given set of work items. Args: work_items: An iterable of `work_db.WorkItem`s. config: The configuration to use for the test execution. Returns: An iterable of WorkItems. """
return celery.group( worker_task.s(work_item, config) for work_item in work_items )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cloned_workspace(clone_config, chdir=True): """Create a cloned workspace and yield it. This creates a workspace for a with-block and cleans it up on exit. By default, this will also change to the workspace's `clone_dir` for the duration of the with-block. Args: clone_config: The execution engine configuration to use for the workspace. chdir: Whether to change to the workspace's `clone_dir` before entering the with-block. Yields: The `CloneWorkspace` instance created for the context. """
workspace = ClonedWorkspace(clone_config) original_dir = os.getcwd() if chdir: os.chdir(workspace.clone_dir) try: yield workspace finally: os.chdir(original_dir) workspace.cleanup()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone_with_git(repo_uri, dest_path): """Create a clone by cloning a git repository. Args: repo_uri: The URI of the git repository to clone. dest_path: The location to clone to. """
log.info('Cloning git repo %s to %s', repo_uri, dest_path) git.Repo.clone_from(repo_uri, dest_path, depth=1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone_with_copy(src_path, dest_path): """Clone a directory try by copying it. Args: src_path: The directory to be copied. dest_path: The location to copy the directory to. """
log.info('Cloning directory tree %s to %s', src_path, dest_path) shutil.copytree(src_path, dest_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_env(venv_dir): """Create a new virtual environment in `venv_dir`. This uses the base prefix of any virtual environment that you may be using when you call this. """
# NB: We had to create the because the venv modules wasn't doing what we # needed. In particular, if we used it create a venv from an existing venv, # it *always* created symlinks back to the original venv's python # executables. Then, when you used those linked executables, you ended up # interacting with the original venv. I could find no way around this, hence # this function. prefix = getattr(sys, 'real_prefix', sys.prefix) python = Path(prefix) / 'bin' / 'python' command = '{} -m venv {}'.format(python, venv_dir) try: log.info('Creating virtual environment: %s', command) subprocess.run(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True) except subprocess.CalledProcessError as exc: log.error("Error creating virtual environment: %s", exc.output) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_variables(self, text): """Replace variable placeholders in `text` with values from the virtual env. The variables are: - {python-executable} Args: text: The text to do replacment int. Returns: The text after replacement. """
variables = { 'python-executable': str(self._venv_path / 'bin' / 'python') } return text.format(**variables)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def cleanup(self): "Remove the directory containin the clone and virtual environment." log.info('Removing temp dir %s', self._tempdir.name) self._tempdir.cleanup()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def as_dict(self): "Get the WorkResult as a dict." return { 'output': self.output, 'test_outcome': self.test_outcome, 'worker_outcome': self.worker_outcome, 'diff': self.diff, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_dict(self): """Get fields as a dict. """
return { 'module_path': str(self.module_path), 'operator_name': self.operator_name, 'occurrence': self.occurrence, 'start_pos': self.start_pos, 'end_pos': self.end_pos, 'job_id': self.job_id, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intercept(work_db): """Look for WorkItems in `work_db` that should not be mutated due to spor metadata. For each WorkItem, find anchors for the item's file/line/columns. If an anchor exists with metadata containing `{mutate: False}` then the WorkItem is marked as SKIPPED. """
@lru_cache() def file_contents(file_path): "A simple cache of file contents." with file_path.open(mode="rt") as handle: return handle.readlines() for item in work_db.work_items: try: repo = open_repository(item.module_path) except ValueError: log.info("No spor repository for %s", item.module_path) continue for _, anchor in repo.items(): if anchor.file_path != item.module_path.absolute(): continue metadata = anchor.metadata lines = file_contents(item.module_path) if _item_in_context( lines, item, anchor.context) and not metadata.get("mutate", True): log.info( "spor skipping %s %s %s %s %s %s", item.job_id, item.operator_name, item.occurrence, item.module_path, item.start_pos, item.end_pos, ) work_db.set_result( item.job_id, WorkResult( output=None, test_outcome=None, diff=None, worker_outcome=WorkerOutcome.SKIPPED, ), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _line_and_col_to_offset(lines, line, col): """Figure out the offset into a file for a particular line and col. This can return offsets that don't actually exist in the file. If you specify a line that exists and a col that is past the end of that line, this will return a "fake" offset. This is to account for the fact that a WorkItem's end_pos is one-past the end of a mutation, and hence potentially one-past the end of a file. Args: lines: A sequence of the lines in a file. line: A one-based index indicating the line in the file. col: A zero-based index indicating the column on `line`. Raises: ValueError: If the specified line found in the file. """
offset = 0 for index, contents in enumerate(lines, 1): if index == line: return offset + col offset += len(contents) raise ValueError("Offset {}:{} not found".format(line, col))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _item_in_context(lines, item, context): """Determines if a WorkItem falls within an anchor. This only returns True if a WorkItems start-/stop-pos range is *completely* within an anchor, not just if it overalaps. """
start_offset = _line_and_col_to_offset(lines, item.start_pos[0], item.start_pos[1]) stop_offset = _line_and_col_to_offset(lines, item.end_pos[0], item.end_pos[1]) width = stop_offset - start_offset return start_offset >= context.offset and width <= len(context.topic)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def use_mutation(module_path, operator, occurrence): """A context manager that applies a mutation for the duration of a with-block. This applies a mutation to a file on disk, and after the with-block it put the unmutated code back in place. Args: module_path: The path to the module to mutate. operator: The `Operator` instance to use. occurrence: The occurrence of the operator to apply. Yields: A `(unmutated-code, mutated-code)` tuple to the with-block. If there was no mutation performed, the `mutated-code` is `None`. """
original_code, mutated_code = apply_mutation(module_path, operator, occurrence) try: yield original_code, mutated_code finally: with module_path.open(mode='wt', encoding='utf-8') as handle: handle.write(original_code) handle.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_mutation(module_path, operator, occurrence): """Apply a specific mutation to a file on disk. Args: module_path: The path to the module to mutate. operator: The `operator` instance to use. occurrence: The occurrence of the operator to apply. Returns: A `(unmutated-code, mutated-code)` tuple to the with-block. If there was no mutation performed, the `mutated-code` is `None`. """
module_ast = get_ast(module_path, python_version=operator.python_version) original_code = module_ast.get_code() visitor = MutationVisitor(occurrence, operator) mutated_ast = visitor.walk(module_ast) mutated_code = None if visitor.mutation_applied: mutated_code = mutated_ast.get_code() with module_path.open(mode='wt', encoding='utf-8') as handle: handle.write(mutated_code) handle.flush() return original_code, mutated_code
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_requirements(): """Extract the list of requirements from our requirements.txt. :rtype: 2-tuple :returns: Two lists, the first is a list of requirements in the form of pkgname==version. The second is a list of URIs or VCS checkout strings which specify the dependency links for obtaining a copy of the requirement. """
requirements_file = os.path.join(os.getcwd(), 'requirements.txt') requirements = [] links=[] try: with open(requirements_file) as reqfile: for line in reqfile.readlines(): line = line.strip() if line.startswith('#'): continue elif line.startswith( ('https://', 'git://', 'hg://', 'svn://')): links.append(line) else: requirements.append(line) except (IOError, OSError) as error: print(error) if python26(): # Required to make `collections.OrderedDict` available on Python<=2.6 requirements.append('ordereddict==1.1#a0ed854ee442051b249bfad0f638bbec') # Don't try to install psutil on PyPy: if _isPyPy: for line in requirements[:]: if line.startswith('psutil'): print("Not installing %s on PyPy..." % line) requirements.remove(line) return requirements, links
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createBatchfile(keyparams=allparams): """Create the batchfile for our new key. :params dict keyparams: A dictionary of arguments for creating the key. It should probably be ``allparams``. :rtype: str :returns: A string containing the entire GnuPG batchfile. """
useparams = {} for key, value in keyparams.items(): if value: useparams.update({key: value}) batchfile = gpg.gen_key_input(separate_keyring=True, save_batchfile=True, **useparams) log.info("Generated GnuPG batch file:\n%s" % batchfile) return batchfile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exportNewKey(fingerprint): """Export the new keys into .asc files. :param str fingerprint: A full key fingerprint. """
log.info("Exporting key: %s" % fingerprint) keyfn = os.path.join(gpg.homedir, fingerprint + '-8192-bit-key') + os.path.extsep pubkey = gpg.export_keys(fingerprint) seckey = gpg.export_keys(fingerprint, secret=True) subkey = gpg.export_keys(fingerprint, secret=True, subkeys=True) with open(keyfn + 'pub' + os.path.extsep + 'asc', 'w') as fh: fh.write(pubkey) with open(keyfn + 'sec' + os.path.extsep + 'asc', 'w') as fh: fh.write(seckey) with open(keyfn + 'sub' + os.path.extsep + 'asc', 'w') as fh: fh.write(subkey)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_keyserver(location): """Check that a given keyserver is a known protocol and does not contain shell escape characters. :param str location: A string containing the default keyserver. This should contain the desired keyserver protocol which is supported by the keyserver, for example, the default is ``'hkp://wwwkeys .pgp.net'``. :rtype: :obj:`str` or :obj:`None` :returns: A string specifying the protocol and keyserver hostname, if the checks passed. If not, returns None. """
protocols = ['hkp://', 'hkps://', 'http://', 'https://', 'ldap://', 'mailto:'] ## xxx feels like i´m forgetting one... for proto in protocols: if location.startswith(proto): url = location.replace(proto, str()) host, slash, extra = url.partition('/') if extra: log.warn("URI text for %s: '%s'" % (host, extra)) log.debug("Got host string for keyserver setting: '%s'" % host) host = _fix_unsafe(host) if host: log.debug("Cleaned host string: '%s'" % host) keyserver = proto + host return keyserver return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_preferences(prefs, pref_type=None): """Check cipher, digest, and compression preference settings. MD5 is not allowed. This is `not 1994`__. SHA1 is allowed_ grudgingly_. __ http://www.cs.colorado.edu/~jrblack/papers/md5e-full.pdf .. _allowed: http://eprint.iacr.org/2008/469.pdf .. _grudgingly: https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html """
if prefs is None: return cipher = frozenset(['AES256', 'AES192', 'AES128', 'CAMELLIA256', 'CAMELLIA192', 'TWOFISH', '3DES']) digest = frozenset(['SHA512', 'SHA384', 'SHA256', 'SHA224', 'RMD160', 'SHA1']) compress = frozenset(['BZIP2', 'ZLIB', 'ZIP', 'Uncompressed']) trust = frozenset(['gpg', 'classic', 'direct', 'always', 'auto']) pinentry = frozenset(['loopback']) all = frozenset([cipher, digest, compress, trust, pinentry]) if isinstance(prefs, str): prefs = set(prefs.split()) elif isinstance(prefs, list): prefs = set(prefs) else: msg = "prefs must be list of strings, or space-separated string" log.error("parsers._check_preferences(): %s" % message) raise TypeError(message) if not pref_type: pref_type = 'all' allowed = str() if pref_type == 'cipher': allowed += ' '.join(prefs.intersection(cipher)) if pref_type == 'digest': allowed += ' '.join(prefs.intersection(digest)) if pref_type == 'compress': allowed += ' '.join(prefs.intersection(compress)) if pref_type == 'trust': allowed += ' '.join(prefs.intersection(trust)) if pref_type == 'pinentry': allowed += ' '.join(prefs.intersection(pinentry)) if pref_type == 'all': allowed += ' '.join(prefs.intersection(all)) return allowed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hyphenate(input, add_prefix=False): """Change underscores to hyphens so that object attributes can be easily tranlated to GPG option names. :param str input: The attribute to hyphenate. :param bool add_prefix: If True, add leading hyphens to the input. :rtype: str :return: The ``input`` with underscores changed to hyphens. """
ret = '--' if add_prefix else '' ret += input.replace('_', '-') return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_allowed(input): """Check that an option or argument given to GPG is in the set of allowed options, the latter being a strict subset of the set of all options known to GPG. :param str input: An input meant to be parsed as an option or flag to the GnuPG process. Should be formatted the same as an option or flag to the commandline gpg, i.e. "--encrypt-files". :ivar frozenset gnupg_options: All known GPG options and flags. :ivar frozenset allowed: All allowed GPG options and flags, e.g. all GPG options and flags which we are willing to acknowledge and parse. If we want to support a new option, it will need to have its own parsing class and its name will need to be added to this set. :raises: :exc:`UsageError` if **input** is not a subset of the hard-coded set of all GnuPG options in :func:`_get_all_gnupg_options`. :exc:`ProtectedOption` if **input** is not in the set of allowed options. :rtype: str :return: The original **input** parameter, unmodified and unsanitized, if no errors occur. """
gnupg_options = _get_all_gnupg_options() allowed = _get_options_group("allowed") ## these are the allowed options we will handle so far, all others should ## be dropped. this dance is so that when new options are added later, we ## merely add the to the _allowed list, and the `` _allowed.issubset`` ## assertion will check that GPG will recognise them try: ## check that allowed is a subset of all gnupg_options assert allowed.issubset(gnupg_options) except AssertionError: raise UsageError("'allowed' isn't a subset of known options, diff: %s" % allowed.difference(gnupg_options)) ## if we got a list of args, join them ## ## see TODO file, tag :cleanup: if not isinstance(input, str): input = ' '.join([x for x in input]) if isinstance(input, str): if input.find('_') > 0: if not input.startswith('--'): hyphenated = _hyphenate(input, add_prefix=True) else: hyphenated = _hyphenate(input) else: hyphenated = input ## xxx we probably want to use itertools.dropwhile here try: assert hyphenated in allowed except AssertionError as ae: dropped = _fix_unsafe(hyphenated) log.warn("_is_allowed(): Dropping option '%s'..." % dropped) raise ProtectedOption("Option '%s' not supported." % dropped) else: return input return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_string(thing): """Python character arrays are a mess. If Python2, check if **thing** is an :obj:`unicode` or a :obj:`str`. If Python3, check if **thing** is a :obj:`str`. :param thing: The thing to check. :returns: ``True`` if **thing** is a string according to whichever version of Python we're running in. """
if _util._py3k: return isinstance(thing, str) else: return isinstance(thing, basestring)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sanitise_list(arg_list): """A generator for iterating through a list of gpg options and sanitising them. :param list arg_list: A list of options and flags for GnuPG. :rtype: generator :returns: A generator whose next() method returns each of the items in ``arg_list`` after calling ``_sanitise()`` with that item as a parameter. """
if isinstance(arg_list, list): for arg in arg_list: safe_arg = _sanitise(arg) if safe_arg != "": yield safe_arg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_options_group(group=None): """Get a specific group of options which are allowed."""
#: These expect a hexidecimal keyid as their argument, and can be parsed #: with :func:`_is_hex`. hex_options = frozenset(['--check-sigs', '--default-key', '--default-recipient', '--delete-keys', '--delete-secret-keys', '--delete-secret-and-public-keys', '--desig-revoke', '--export', '--export-secret-keys', '--export-secret-subkeys', '--fingerprint', '--gen-revoke', '--hidden-encrypt-to', '--hidden-recipient', '--list-key', '--list-keys', '--list-public-keys', '--list-secret-keys', '--list-sigs', '--recipient', '--recv-keys', '--send-keys', '--edit-key', '--sign-key', ]) #: These options expect value which are left unchecked, though still run #: through :func:`_fix_unsafe`. unchecked_options = frozenset(['--list-options', '--passphrase-fd', '--status-fd', '--verify-options', '--command-fd', ]) #: These have their own parsers and don't really fit into a group other_options = frozenset(['--debug-level', '--keyserver', ]) #: These should have a directory for an argument dir_options = frozenset(['--homedir', ]) #: These expect a keyring or keyfile as their argument keyring_options = frozenset(['--keyring', '--primary-keyring', '--secret-keyring', '--trustdb-name', ]) #: These expect a filename (or the contents of a file as a string) or None #: (meaning that they read from stdin) file_or_none_options = frozenset(['--decrypt', '--decrypt-files', '--encrypt', '--encrypt-files', '--import', '--verify', '--verify-files', '--output', ]) #: These options expect a string. see :func:`_check_preferences`. pref_options = frozenset(['--digest-algo', '--cipher-algo', '--compress-algo', '--compression-algo', '--cert-digest-algo', '--personal-digest-prefs', '--personal-digest-preferences', '--personal-cipher-prefs', '--personal-cipher-preferences', '--personal-compress-prefs', '--personal-compress-preferences', '--pinentry-mode', '--print-md', '--trust-model', ]) #: These options expect no arguments none_options = frozenset(['--allow-loopback-pinentry', '--always-trust', '--armor', '--armour', '--batch', '--check-sigs', '--check-trustdb', '--clearsign', '--debug-all', '--default-recipient-self', '--detach-sign', '--export', '--export-ownertrust', '--export-secret-keys', '--export-secret-subkeys', '--fingerprint', '--fixed-list-mode', '--gen-key', '--import-ownertrust', '--list-config', '--list-key', '--list-keys', '--list-packets', '--list-public-keys', '--list-secret-keys', '--list-sigs', '--lock-multiple', '--lock-never', '--lock-once', '--no-default-keyring', '--no-default-recipient', '--no-emit-version', '--no-options', '--no-tty', '--no-use-agent', '--no-verbose', '--print-mds', '--quiet', '--sign', '--symmetric', '--throw-keyids', '--use-agent', '--verbose', '--version', '--with-colons', '--yes', ]) #: These options expect either None or a hex string hex_or_none_options = hex_options.intersection(none_options) allowed = hex_options.union(unchecked_options, other_options, dir_options, keyring_options, file_or_none_options, pref_options, none_options) if group and group in locals().keys(): return locals()[group]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_all_gnupg_options(): """Get all GnuPG options and flags. This is hardcoded within a local scope to reduce the chance of a tampered GnuPG binary reporting falsified option sets, i.e. because certain options (namedly the ``--no-options`` option, which prevents the usage of gpg.conf files) are necessary and statically specified in :meth:`gnupg._meta.GPGBase._make_args`, if the inputs into Python are already controlled, and we were to summon the GnuPG binary to ask it for its options, it would be possible to receive a falsified options set missing the ``--no-options`` option in response. This seems unlikely, and the method is stupid and ugly, but at least we'll never have to debug whether or not an option *actually* disappeared in a different GnuPG version, or some funny business is happening. These are the options as of GnuPG 1.4.12; the current stable branch of the 2.1.x tree contains a few more -- if you need them you'll have to add them in here. :type gnupg_options: frozenset :ivar gnupg_options: All known GPG options and flags. :rtype: frozenset :returns: ``gnupg_options`` """
three_hundred_eighteen = (""" --allow-freeform-uid --multifile --allow-multiple-messages --no --allow-multisig-verification --no-allow-freeform-uid --allow-non-selfsigned-uid --no-allow-multiple-messages --allow-secret-key-import --no-allow-non-selfsigned-uid --always-trust --no-armor --armor --no-armour --armour --no-ask-cert-expire --ask-cert-expire --no-ask-cert-level --ask-cert-level --no-ask-sig-expire --ask-sig-expire --no-auto-check-trustdb --attribute-fd --no-auto-key-locate --attribute-file --no-auto-key-retrieve --auto-check-trustdb --no-batch --auto-key-locate --no-comments --auto-key-retrieve --no-default-keyring --batch --no-default-recipient --bzip2-compress-level --no-disable-mdc --bzip2-decompress-lowmem --no-emit-version --card-edit --no-encrypt-to --card-status --no-escape-from-lines --cert-digest-algo --no-expensive-trust-checks --cert-notation --no-expert --cert-policy-url --no-force-mdc --change-pin --no-force-v3-sigs --charset --no-force-v4-certs --check-sig --no-for-your-eyes-only --check-sigs --no-greeting --check-trustdb --no-groups --cipher-algo --no-literal --clearsign --no-mangle-dos-filenames --command-fd --no-mdc-warning --command-file --no-options --comment --no-permission-warning --completes-needed --no-pgp2 --compress-algo --no-pgp6 --compression-algo --no-pgp7 --compress-keys --no-pgp8 --compress-level --no-random-seed-file --compress-sigs --no-require-backsigs --ctapi-driver --no-require-cross-certification --dearmor --no-require-secmem --dearmour --no-rfc2440-text --debug --no-secmem-warning --debug-all --no-show-notation --debug-ccid-driver --no-show-photos --debug-level --no-show-policy-url --decrypt --no-sig-cache --decrypt-files --no-sig-create-check --default-cert-check-level --no-sk-comments --default-cert-expire --no-strict --default-cert-level --notation-data --default-comment --not-dash-escaped --default-key --no-textmode --default-keyserver-url --no-throw-keyid --default-preference-list --no-throw-keyids --default-recipient --no-tty --default-recipient-self --no-use-agent --default-sig-expire --no-use-embedded-filename --delete-keys --no-utf8-strings --delete-secret-and-public-keys --no-verbose --delete-secret-keys --no-version --desig-revoke --openpgp --detach-sign --options --digest-algo --output --disable-ccid --override-session-key --disable-cipher-algo --passphrase --disable-dsa2 --passphrase-fd --disable-mdc --passphrase-file --disable-pubkey-algo --passphrase-repeat --display --pcsc-driver --display-charset --personal-cipher-preferences --dry-run --personal-cipher-prefs --dump-options --personal-compress-preferences --edit-key --personal-compress-prefs --emit-version --personal-digest-preferences --enable-dsa2 --personal-digest-prefs --enable-progress-filter --pgp2 --enable-special-filenames --pgp6 --enarmor --pgp7 --enarmour --pgp8 --encrypt --photo-viewer --encrypt-files --pipemode --encrypt-to --preserve-permissions --escape-from-lines --primary-keyring --exec-path --print-md --exit-on-status-write-error --print-mds --expert --quick-random --export --quiet --export-options --reader-port --export-ownertrust --rebuild-keydb-caches --export-secret-keys --recipient --export-secret-subkeys --recv-keys --fast-import --refresh-keys --fast-list-mode --remote-user --fetch-keys --require-backsigs --fingerprint --require-cross-certification --fixed-list-mode --require-secmem --fix-trustdb --rfc1991 --force-mdc --rfc2440 --force-ownertrust --rfc2440-text --force-v3-sigs --rfc4880 --force-v4-certs --run-as-shm-coprocess --for-your-eyes-only --s2k-cipher-algo --gen-key --s2k-count --gen-prime --s2k-digest-algo --gen-random --s2k-mode --gen-revoke --search-keys --gnupg --secret-keyring --gpg-agent-info --send-keys --gpgconf-list --set-filename --gpgconf-test --set-filesize --group --set-notation --help --set-policy-url --hidden-encrypt-to --show-keyring --hidden-recipient --show-notation --homedir --show-photos --honor-http-proxy --show-policy-url --ignore-crc-error --show-session-key --ignore-mdc-error --sig-keyserver-url --ignore-time-conflict --sign --ignore-valid-from --sign-key --import --sig-notation --import-options --sign-with --import-ownertrust --sig-policy-url --interactive --simple-sk-checksum --keyid-format --sk-comments --keyring --skip-verify --keyserver --status-fd --keyserver-options --status-file --lc-ctype --store --lc-messages --strict --limit-card-insert-tries --symmetric --list-config --temp-directory --list-key --textmode --list-keys --throw-keyid --list-only --throw-keyids --list-options --trustdb-name --list-ownertrust --trusted-key --list-packets --trust-model --list-public-keys --try-all-secrets --list-secret-keys --ttyname --list-sig --ttytype --list-sigs --ungroup --list-trustdb --update-trustdb --load-extension --use-agent --local-user --use-embedded-filename --lock-multiple --user --lock-never --utf8-strings --lock-once --verbose --logger-fd --verify --logger-file --verify-files --lsign-key --verify-options --mangle-dos-filenames --version --marginals-needed --warranty --max-cert-depth --with-colons --max-output --with-fingerprint --merge-only --with-key-data --min-cert-level --yes """).split() # These are extra options which only exist for GnuPG>=2.0.0 three_hundred_eighteen.append('--export-ownertrust') three_hundred_eighteen.append('--import-ownertrust') # These are extra options which only exist for GnuPG>=2.1.0 three_hundred_eighteen.append('--pinentry-mode') three_hundred_eighteen.append('--allow-loopback-pinentry') gnupg_options = frozenset(three_hundred_eighteen) return gnupg_options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nodata(status_code): """Translate NODATA status codes from GnuPG to messages."""
lookup = { '1': 'No armored data.', '2': 'Expected a packet but did not find one.', '3': 'Invalid packet found, this may indicate a non OpenPGP message.', '4': 'Signature expected but not found.' } for key, value in lookup.items(): if str(status_code) == key: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def progress(status_code): """Translate PROGRESS status codes from GnuPG to messages."""
lookup = { 'pk_dsa': 'DSA key generation', 'pk_elg': 'Elgamal key generation', 'primegen': 'Prime generation', 'need_entropy': 'Waiting for new entropy in the RNG', 'tick': 'Generic tick without any special meaning - still working.', 'starting_agent': 'A gpg-agent was started.', 'learncard': 'gpg-agent or gpgsm is learning the smartcard data.', 'card_busy': 'A smartcard is still working.' } for key, value in lookup.items(): if str(status_code) == key: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_key_expiration_option(self): """validates the expiration option supplied"""
allowed_entry = re.findall('^(\d+)(|w|m|y)$', self._expiration_time) if not allowed_entry: raise UsageError("Key expiration option: %s is not valid" % self._expiration_time)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_trustdb(cls): """Create the trustdb file in our homedir, if it doesn't exist."""
trustdb = os.path.join(cls.homedir, 'trustdb.gpg') if not os.path.isfile(trustdb): log.info("GnuPG complained that your trustdb file was missing. %s" % "This is likely due to changing to a new homedir.") log.info("Creating trustdb.gpg file in your GnuPG homedir.") cls.fix_trustdb(trustdb)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_ownertrust(cls, trustdb=None): """Export ownertrust to a trustdb file. If there is already a file named :file:`trustdb.gpg` in the current GnuPG homedir, it will be renamed to :file:`trustdb.gpg.bak`. :param string trustdb: The path to the trustdb.gpg file. If not given, defaults to ``'trustdb.gpg'`` in the current GnuPG homedir. """
if trustdb is None: trustdb = os.path.join(cls.homedir, 'trustdb.gpg') try: os.rename(trustdb, trustdb + '.bak') except (OSError, IOError) as err: log.debug(str(err)) export_proc = cls._open_subprocess(['--export-ownertrust']) tdb = open(trustdb, 'wb') _util._threaded_copy_data(export_proc.stdout, tdb) export_proc.wait()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_ownertrust(cls, trustdb=None): """Import ownertrust from a trustdb file. :param str trustdb: The path to the trustdb.gpg file. If not given, defaults to :file:`trustdb.gpg` in the current GnuPG homedir. """
if trustdb is None: trustdb = os.path.join(cls.homedir, 'trustdb.gpg') import_proc = cls._open_subprocess(['--import-ownertrust']) try: tdb = open(trustdb, 'rb') except (OSError, IOError): log.error("trustdb file %s does not exist!" % trustdb) _util._threaded_copy_data(tdb, import_proc.stdin) import_proc.wait()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_trustdb(cls, trustdb=None): """Attempt to repair a broken trustdb.gpg file. GnuPG>=2.0.x has this magical-seeming flag: `--fix-trustdb`. You'd think it would fix the the trustdb. Hah! It doesn't. Here's what it does instead:: (gpg)~/code/python-gnupg $ gpg2 --fix-trustdb gpg: You may try to re-create the trustdb using the commands: gpg: cd ~/.gnupg gpg: gpg2 --export-ownertrust > otrust.tmp gpg: rm trustdb.gpg gpg: gpg2 --import-ownertrust < otrust.tmp gpg: If that does not work, please consult the manual Brilliant piece of software engineering right there. :param str trustdb: The path to the trustdb.gpg file. If not given, defaults to :file:`trustdb.gpg` in the current GnuPG homedir. """
if trustdb is None: trustdb = os.path.join(cls.homedir, 'trustdb.gpg') export_proc = cls._open_subprocess(['--export-ownertrust']) import_proc = cls._open_subprocess(['--import-ownertrust']) _util._threaded_copy_data(export_proc.stdout, import_proc.stdin) export_proc.wait() import_proc.wait()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self, message, *args, **kwargs): """LogRecord for GnuPG internal status messages."""
if self.isEnabledFor(GNUPG_STATUS_LEVEL): self._log(GNUPG_STATUS_LEVEL, message, args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_logger(level=logging.NOTSET): """Create a logger for python-gnupg at a specific message level. :type level: :obj:`int` or :obj:`str` :param level: A string or an integer for the lowest level to include in logs. **Available levels:** ==== ======== ======================================== int str description ==== ======== ======================================== 0 NOTSET Disable all logging. 9 GNUPG Log GnuPG's internal status messages. 10 DEBUG Log module level debuging messages. 20 INFO Normal user-level messages. 30 WARN Warning messages. 40 ERROR Error messages and tracebacks. 50 CRITICAL Unhandled exceptions and tracebacks. ==== ======== ======================================== """
_test = os.path.join(os.path.join(os.getcwd(), 'pretty_bad_protocol'), 'test') _now = datetime.now().strftime("%Y-%m-%d_%H%M%S") _fn = os.path.join(_test, "%s_test_gnupg.log" % _now) _fmt = "%(relativeCreated)-4d L%(lineno)-4d:%(funcName)-18.18s %(levelname)-7.7s %(message)s" ## Add the GNUPG_STATUS_LEVEL LogRecord to all Loggers in the module: logging.addLevelName(GNUPG_STATUS_LEVEL, "GNUPG") logging.Logger.status = status if level > logging.NOTSET: logging.basicConfig(level=level, filename=_fn, filemode="a", format=_fmt) logging.logThreads = True if hasattr(logging,'captureWarnings'): logging.captureWarnings(True) colouriser = _ansistrm.ColorizingStreamHandler colouriser.level_map[9] = (None, 'blue', False) colouriser.level_map[10] = (None, 'cyan', False) handler = colouriser(sys.stderr) handler.setLevel(level) formatr = logging.Formatter(_fmt) handler.setFormatter(formatr) else: handler = NullHandler() log = logging.getLogger('gnupg') log.addHandler(handler) log.setLevel(level) log.info("Log opened: %s UTC" % datetime.ctime(datetime.utcnow())) return log
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_agent(cls): """Discover if a gpg-agent process for the current euid is running. If there is a matching gpg-agent process, set a :class:`psutil.Process` instance containing the gpg-agent process' information to ``cls._agent_proc``. For Unix systems, we check that the effective UID of this ``python-gnupg`` process is also the owner of the gpg-agent process. For Windows, we check that the usernames of the owners are the same. (Sorry Windows users; maybe you should switch to anything else.) .. note: This function will only run if the psutil_ Python extension is installed. Because psutil won't run with the PyPy interpreter, use of it is optional (although highly recommended). .. _psutil: https://pypi.python.org/pypi/psutil :returns: True if there exists a gpg-agent process running under the same effective user ID as that of this program. Otherwise, returns False. """
if not psutil: return False this_process = psutil.Process(os.getpid()) ownership_match = False if _util._running_windows: identity = this_process.username() else: identity = this_process.uids for proc in psutil.process_iter(): try: # In my system proc.name & proc.is_running are methods if (proc.name() == "gpg-agent") and proc.is_running(): log.debug("Found gpg-agent process with pid %d" % proc.pid) if _util._running_windows: if proc.username() == identity: ownership_match = True else: # proc.uids & identity are methods to if proc.uids() == identity(): ownership_match = True except psutil.Error as err: # Exception when getting proc info, possibly because the # process is zombie / process no longer exist. Just ignore it. log.warn("Error while attempting to find gpg-agent process: %s" % err) # Next code must be inside for operator. # Otherwise to _agent_proc will be saved not "gpg-agent" process buth an other. if ownership_match: log.debug("Effective UIDs of this process and gpg-agent match") setattr(cls, '_agent_proc', proc) return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_preference_list(self, prefs): """Set the default preference list. :param str prefs: A string containing the default preferences for ciphers, digests, and compression algorithms. """
prefs = _check_preferences(prefs) if prefs is not None: self._prefs = prefs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _homedir_setter(self, directory): """Set the directory to use as GnuPG's homedir. If unspecified, use $HOME/.config/python-gnupg. If specified, ensure that the ``directory`` does not contain various shell escape characters. If ``directory`` is not found, it will be automatically created. Lastly, the ``direcory`` will be checked that the EUID has read and write permissions for it. :param str directory: A relative or absolute path to the directory to use for storing/accessing GnuPG's files, including keyrings and the trustdb. :raises: :exc:`~exceptions.RuntimeError` if unable to find a suitable directory to use. """
if not directory: log.debug("GPGBase._homedir_setter(): Using default homedir: '%s'" % _util._conf) directory = _util._conf hd = _parsers._fix_unsafe(directory) log.debug("GPGBase._homedir_setter(): got directory '%s'" % hd) if hd: log.debug("GPGBase._homedir_setter(): Check existence of '%s'" % hd) _util._create_if_necessary(hd) if self.ignore_homedir_permissions: self._homedir = hd else: try: log.debug("GPGBase._homedir_setter(): checking permissions") assert _util._has_readwrite(hd), \ "Homedir '%s' needs read/write permissions" % hd except AssertionError as ae: msg = ("Unable to set '%s' as GnuPG homedir" % directory) log.debug("GPGBase.homedir.setter(): %s" % msg) log.debug(str(ae)) raise RuntimeError(str(ae)) else: log.info("Setting homedir to '%s'" % hd) self._homedir = hd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generated_keys_setter(self, directory): """Set the directory for storing generated keys. If unspecified, use :meth:`~gnupg._meta.GPGBase.homedir`/generated-keys. If specified, ensure that the ``directory`` does not contain various shell escape characters. If ``directory`` isn't found, it will be automatically created. Lastly, the ``directory`` will be checked to ensure that the current EUID has read and write permissions for it. :param str directory: A relative or absolute path to the directory to use for storing/accessing GnuPG's files, including keyrings and the trustdb. :raises: :exc:`~exceptions.RuntimeError` if unable to find a suitable directory to use. """
if not directory: directory = os.path.join(self.homedir, 'generated-keys') log.debug("GPGBase._generated_keys_setter(): Using '%s'" % directory) hd = _parsers._fix_unsafe(directory) log.debug("GPGBase._generated_keys_setter(): got directory '%s'" % hd) if hd: log.debug("GPGBase._generated_keys_setter(): Check exists '%s'" % hd) _util._create_if_necessary(hd) try: log.debug("GPGBase._generated_keys_setter(): check permissions") assert _util._has_readwrite(hd), \ "Keys dir '%s' needs read/write permissions" % hd except AssertionError as ae: msg = ("Unable to set '%s' as generated keys dir" % directory) log.debug("GPGBase._generated_keys_setter(): %s" % msg) log.debug(str(ae)) raise RuntimeError(str(ae)) else: log.info("Setting homedir to '%s'" % hd) self.__generated_keys = hd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_args(self, args, passphrase=False): """Make a list of command line elements for GPG. The value of ``args`` will be appended only if it passes the checks in :func:`gnupg._parsers._sanitise`. The ``passphrase`` argument needs to be True if a passphrase will be sent to GnuPG, else False. :param list args: A list of strings of options and flags to pass to ``GPG.binary``. This is input safe, meaning that these values go through strict checks (see ``parsers._sanitise_list``) before being passed to to the input file descriptor for the GnuPG process. Each string should be given exactly as it would be on the commandline interface to GnuPG, e.g. ["--cipher-algo AES256", "--default-key A3ADB67A2CDB8B35"]. :param bool passphrase: If True, the passphrase will be sent to the stdin file descriptor for the attached GnuPG process. """
## see TODO file, tag :io:makeargs: cmd = [self.binary, '--no-options --no-emit-version --no-tty --status-fd 2'] if self.homedir: cmd.append('--homedir "%s"' % self.homedir) if self.keyring: cmd.append('--no-default-keyring --keyring %s' % self.keyring) if self.secring: cmd.append('--secret-keyring %s' % self.secring) if passphrase: cmd.append('--batch --passphrase-fd 0') if self.use_agent is True: cmd.append('--use-agent') elif self.use_agent is False: cmd.append('--no-use-agent') # The arguments for debugging and verbosity should be placed into the # cmd list before the options/args in order to resolve Issue #76: # https://github.com/isislovecruft/python-gnupg/issues/76 if self.verbose: cmd.append('--debug-all') if (isinstance(self.verbose, str) or (isinstance(self.verbose, int) and (self.verbose >= 1))): # GnuPG<=1.4.18 parses the `--debug-level` command in a way # that is incompatible with all other GnuPG versions. :'( if self.binary_version and (self.binary_version <= '1.4.18'): cmd.append('--debug-level=%s' % self.verbose) else: cmd.append('--debug-level %s' % self.verbose) if self.options: [cmd.append(opt) for opt in iter(_sanitise_list(self.options))] if args: [cmd.append(arg) for arg in iter(_sanitise_list(args))] return cmd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _open_subprocess(self, args=None, passphrase=False): """Open a pipe to a GPG subprocess and return the file objects for communicating with it. :param list args: A list of strings of options and flags to pass to ``GPG.binary``. This is input safe, meaning that these values go through strict checks (see ``parsers._sanitise_list``) before being passed to to the input file descriptor for the GnuPG process. Each string should be given exactly as it would be on the commandline interface to GnuPG, e.g. ["--cipher-algo AES256", "--default-key A3ADB67A2CDB8B35"]. :param bool passphrase: If True, the passphrase will be sent to the stdin file descriptor for the attached GnuPG process. """
## see http://docs.python.org/2/library/subprocess.html#converting-an\ ## -argument-sequence-to-a-string-on-windows cmd = shlex.split(' '.join(self._make_args(args, passphrase))) log.debug("Sending command to GnuPG process:%s%s" % (os.linesep, cmd)) if platform.system() == "Windows": # TODO figure out what the hell is going on there. expand_shell = True else: expand_shell = False environment = { 'LANGUAGE': os.environ.get('LANGUAGE') or 'en', 'GPG_TTY': os.environ.get('GPG_TTY') or '', 'DISPLAY': os.environ.get('DISPLAY') or '', 'GPG_AGENT_INFO': os.environ.get('GPG_AGENT_INFO') or '', 'GPG_TTY': os.environ.get('GPG_TTY') or '', 'GPG_PINENTRY_PATH': os.environ.get('GPG_PINENTRY_PATH') or '', } return subprocess.Popen(cmd, shell=expand_shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_data(self, stream, result): """Incrementally read from ``stream`` and store read data. All data gathered from calling ``stream.read()`` will be concatenated and stored as ``result.data``. :param stream: An open file-like object to read() from. :param result: An instance of one of the :ref:`result parsing classes <parsers>` from :const:`~gnupg._meta.GPGBase._result_map`. """
chunks = [] log.debug("Reading data from stream %r..." % stream.__repr__()) while True: data = stream.read(1024) if len(data) == 0: break chunks.append(data) log.debug("Read %4d bytes" % len(data)) # Join using b'' or '', as appropriate result.data = type(data)().join(chunks) log.debug("Finishing reading from stream %r..." % stream.__repr__()) log.debug("Read %4d bytes total" % len(result.data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_io(self, args, file, result, passphrase=False, binary=False): """Handle a call to GPG - pass input data, collect output data."""
p = self._open_subprocess(args, passphrase) if not binary: stdin = codecs.getwriter(self._encoding)(p.stdin) else: stdin = p.stdin if passphrase: _util._write_passphrase(stdin, passphrase, self._encoding) writer = _util._threaded_copy_data(file, stdin) self._collect_output(p, result, writer, stdin) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sign_file(self, file, default_key=None, passphrase=None, clearsign=True, detach=False, binary=False, digest_algo='SHA512'): """Create a signature for a file. :param file: The file stream (i.e. it's already been open()'d) to sign. :param str default_key: The key to sign with. :param str passphrase: The passphrase to pipe to stdin. :param bool clearsign: If True, create a cleartext signature. :param bool detach: If True, create a detached signature. :param bool binary: If True, do not ascii armour the output. :param str digest_algo: The hash digest to use. Again, to see which hashes your GnuPG is capable of using, do: ``$ gpg --with-colons --list-config digestname``. The default, if unspecified, is ``'SHA512'``. """
log.debug("_sign_file():") if binary: log.info("Creating binary signature for file %s" % file) args = ['--sign'] else: log.info("Creating ascii-armoured signature for file %s" % file) args = ['--sign --armor'] if clearsign: args.append("--clearsign") if detach: log.warn("Cannot use both --clearsign and --detach-sign.") log.warn("Using default GPG behaviour: --clearsign only.") elif detach and not clearsign: args.append("--detach-sign") if default_key: args.append(str("--default-key %s" % default_key)) args.append(str("--digest-algo %s" % digest_algo)) ## We could use _handle_io here except for the fact that if the ## passphrase is bad, gpg bails and you can't write the message. result = self._result_map['sign'](self) ## If the passphrase is an empty string, the message up to and ## including its first newline will be cut off before making it to the ## GnuPG process. Therefore, if the passphrase='' or passphrase=b'', ## we set passphrase=None. See Issue #82: ## https://github.com/isislovecruft/python-gnupg/issues/82 if _util._is_string(passphrase): passphrase = passphrase if len(passphrase) > 0 else None elif _util._is_bytes(passphrase): passphrase = s(passphrase) if len(passphrase) > 0 else None else: passphrase = None proc = self._open_subprocess(args, passphrase is not None) try: if passphrase: _util._write_passphrase(proc.stdin, passphrase, self._encoding) writer = _util._threaded_copy_data(file, proc.stdin) except IOError as ioe: log.exception("Error writing message: %s" % str(ioe)) writer = None self._collect_output(proc, result, writer, proc.stdin) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_encodings(enc=None, system=False): """Find functions for encoding translations for a specific codec. :param str enc: The codec to find translation functions for. It will be normalized by converting to lowercase, excluding everything which is not ascii, and hyphens will be converted to underscores. :param bool system: If True, find encodings based on the system's stdin encoding, otherwise assume utf-8. :raises: :exc:LookupError if the normalized codec, ``enc``, cannot be found in Python's encoding translation map. """
if not enc: enc = 'utf-8' if system: if getattr(sys.stdin, 'encoding', None) is None: enc = sys.stdin.encoding log.debug("Obtained encoding from stdin: %s" % enc) else: enc = 'ascii' ## have to have lowercase to work, see ## http://docs.python.org/dev/library/codecs.html#standard-encodings enc = enc.lower() codec_alias = encodings.normalize_encoding(enc) codecs.register(encodings.search_function) coder = codecs.lookup(codec_alias) return coder
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def author_info(name, contact=None, public_key=None): """Easy object-oriented representation of contributor info. :param str name: The contributor´s name. :param str contact: The contributor´s email address or contact information, if given. :param str public_key: The contributor´s public keyid, if given. """
return Storage(name=name, contact=contact, public_key=public_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy_data(instream, outstream): """Copy data from one stream to another. :type instream: :class:`io.BytesIO` or :class:`io.StringIO` or file :param instream: A byte stream or open file to read from. :param file outstream: The file descriptor of a tmpfile to write to. """
sent = 0 while True: if ((_py3k and isinstance(instream, str)) or (not _py3k and isinstance(instream, basestring))): data = instream[:1024] instream = instream[1024:] else: data = instream.read(1024) if len(data) == 0: break sent += len(data) if ((_py3k and isinstance(data, str)) or (not _py3k and isinstance(data, basestring))): encoded = binary(data) else: encoded = data log.debug("Sending %d bytes of data..." % sent) log.debug("Encoded data (type %s):\n%s" % (type(encoded), encoded)) if not _py3k: try: outstream.write(encoded) except IOError as ioe: # Can get 'broken pipe' errors even when all data was sent if 'Broken pipe' in str(ioe): log.error('Error sending data: Broken pipe') else: log.exception(ioe) break else: log.debug("Wrote data type <type 'str'> to outstream.") else: try: outstream.write(bytes(encoded)) except TypeError as te: # XXX FIXME This appears to happen because # _threaded_copy_data() sometimes passes the `outstream` as an # object with type <_io.BufferredWriter> and at other times # with type <encodings.utf_8.StreamWriter>. We hit the # following error when the `outstream` has type # <encodings.utf_8.StreamWriter>. if not "convert 'bytes' object to str implicitly" in str(te): log.error(str(te)) try: outstream.write(encoded.decode()) except TypeError as yate: # We hit the "'str' does not support the buffer interface" # error in Python3 when the `outstream` is an io.BytesIO and # we try to write a str to it. We don't care about that # error, we'll just try again with bytes. if not "does not support the buffer interface" in str(yate): log.error(str(yate)) except IOError as ioe: # Can get 'broken pipe' errors even when all data was sent if 'Broken pipe' in str(ioe): log.error('Error sending data: Broken pipe') else: log.exception(ioe) break else: log.debug("Wrote data type <class 'str'> outstream.") except IOError as ioe: # Can get 'broken pipe' errors even when all data was sent if 'Broken pipe' in str(ioe): log.error('Error sending data: Broken pipe') else: log.exception(ioe) break else: log.debug("Wrote data type <class 'bytes'> to outstream.") try: outstream.close() except IOError as ioe: log.error("Unable to close outstream %s:\r\t%s" % (outstream, ioe)) else: log.debug("Closed outstream: %d bytes sent." % sent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_if_necessary(directory): """Create the specified directory, if necessary. :param str directory: The directory to use. :rtype: bool :returns: True if no errors occurred and the directory was created or existed beforehand, False otherwise. """
if not os.path.isabs(directory): log.debug("Got non-absolute path: %s" % directory) directory = os.path.abspath(directory) if not os.path.isdir(directory): log.info("Creating directory: %s" % directory) try: os.makedirs(directory, 0x1C0) except OSError as ose: log.error(ose, exc_info=1) return False else: log.debug("Created directory.") return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_uid_email(username=None, hostname=None): """Create an email address suitable for a UID on a GnuPG key. :param str username: The username portion of an email address. If None, defaults to the username of the running Python process. :param str hostname: The FQDN portion of an email address. If None, the hostname is obtained from gethostname(2). :rtype: str :returns: A string formatted as <username>@<hostname>. """
if hostname: hostname = hostname.replace(' ', '_') if not username: try: username = os.environ['LOGNAME'] except KeyError: username = os.environ['USERNAME'] if not hostname: hostname = gethostname() uid = "%s@%s" % (username.replace(' ', '_'), hostname) else: username = username.replace(' ', '_') if (not hostname) and (username.find('@') == 0): uid = "%s@%s" % (username, gethostname()) elif hostname: uid = "%s@%s" % (username, hostname) else: uid = username return uid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deprefix(line, prefix, callback=None): """Remove the prefix string from the beginning of line, if it exists. :param string line: A line, such as one output by GnuPG's status-fd. :param string prefix: A substring to remove from the beginning of ``line``. Case insensitive. :type callback: callable :param callback: Function to call if the prefix is found. The signature to callback will be only one argument, the ``line`` without the ``prefix``, i.e. ``callback(line)``. :rtype: string :returns: If the prefix was found, the ``line`` without the prefix is returned. Otherwise, the original ``line`` is returned. """
try: assert line.upper().startswith(u''.join(prefix).upper()) except AssertionError: log.debug("Line doesn't start with prefix '%s':\n%s" % (prefix, line)) return line else: newline = line[len(prefix):] if callback is not None: try: callback(newline) except Exception as exc: log.exception(exc) return newline
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_binary(binary=None): """Find the absolute path to the GnuPG binary. Also run checks that the binary is not a symlink, and check that our process real uid has exec permissions. :param str binary: The path to the GnuPG binary. :raises: :exc:`~exceptions.RuntimeError` if it appears that GnuPG is not installed. :rtype: str :returns: The absolute path to the GnuPG binary to use, if no exceptions occur. """
found = None if binary is not None: if os.path.isabs(binary) and os.path.isfile(binary): return binary if not os.path.isabs(binary): try: found = _which(binary) log.debug("Found potential binary paths: %s" % '\n'.join([path for path in found])) found = found[0] except IndexError as ie: log.info("Could not determine absolute path of binary: '%s'" % binary) elif os.access(binary, os.X_OK): found = binary if found is None: try: found = _which('gpg', abspath_only=True, disallow_symlinks=True)[0] except IndexError as ie: log.error("Could not find binary for 'gpg'.") try: found = _which('gpg2')[0] except IndexError as ie: log.error("Could not find binary for 'gpg2'.") if found is None: raise RuntimeError("GnuPG is not installed!") return found
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_gpg1(version): """Returns True if using GnuPG version 1.x. :param tuple version: A tuple of three integers indication major, minor, and micro version numbers. """
(major, minor, micro) = _match_version_string(version) if major == 1: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_gpg2(version): """Returns True if using GnuPG version 2.x. :param tuple version: A tuple of three integers indication major, minor, and micro version numbers. """
(major, minor, micro) = _match_version_string(version) if major == 2: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_passphrase(length=None, save=False, file=None): """Create a passphrase and write it to a file that only the user can read. This is not very secure, and should not be relied upon for actual key passphrases. :param int length: The length in bytes of the string to generate. :param file file: The file to save the generated passphrase in. If not given, defaults to 'passphrase-<the real user id>-<seconds since epoch>' in the top-level directory. """
if not length: length = 40 passphrase = _make_random_string(length) if save: ruid, euid, suid = os.getresuid() gid = os.getgid() now = mktime(localtime()) if not file: filename = str('passphrase-%s-%s' % uid, now) file = os.path.join(_repo, filename) with open(file, 'a') as fh: fh.write(passphrase) fh.flush() fh.close() os.chmod(file, stat.S_IRUSR | stat.S_IWUSR) os.chown(file, ruid, gid) log.warn("Generated passphrase saved to %s" % file) return passphrase
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_random_string(length): """Returns a random lowercase, uppercase, alphanumerical string. :param int length: The length in bytes of the string to generate. """
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits return ''.join(random.choice(chars) for x in range(length))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _match_version_string(version): """Sort a binary version string into major, minor, and micro integers. :param str version: A version string in the form x.x.x :raises GnuPGVersionError: if the **version** string couldn't be parsed. :rtype: tuple :returns: A 3-tuple of integers, representing the (MAJOR, MINOR, MICRO) version numbers. For example:: _match_version_string("2.1.3") would return ``(2, 1, 3)``. """
matched = _VERSION_STRING_REGEX.match(version) g = matched.groups() major, minor, micro = g[0], g[2], g[4] # If, for whatever reason, the binary didn't tell us its version, then # these might be (None, None, None), and so we should avoid typecasting # them when that is the case. if major and minor and micro: major, minor, micro = int(major), int(minor), int(micro) else: raise GnuPGVersionError("Could not parse GnuPG version from: %r" % version) return (major, minor, micro)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next_year(): """Get the date of today plus one year. :rtype: str :returns: The date of this day next year, in the format '%Y-%m-%d'. """
now = datetime.now().__str__() date = now.split(' ', 1)[0] year, month, day = date.split('-', 2) next_year = str(int(year)+1) return '-'.join((next_year, month, day))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _threaded_copy_data(instream, outstream): """Copy data from one stream to another in a separate thread. Wraps ``_copy_data()`` in a :class:`threading.Thread`. :type instream: :class:`io.BytesIO` or :class:`io.StringIO` :param instream: A byte stream to read from. :param file outstream: The file descriptor of a tmpfile to write to. """
copy_thread = threading.Thread(target=_copy_data, args=(instream, outstream)) copy_thread.setDaemon(True) log.debug('%r, %r, %r', copy_thread, instream, outstream) copy_thread.start() return copy_thread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_passphrase(stream, passphrase, encoding): """Write the passphrase from memory to the GnuPG process' stdin. :type stream: file, :class:`~io.BytesIO`, or :class:`~io.StringIO` :param stream: The input file descriptor to write the password to. :param str passphrase: The passphrase for the secret key material. :param str encoding: The data encoding expected by GnuPG. Usually, this is ``sys.getfilesystemencoding()``. """
passphrase = '%s\n' % passphrase passphrase = passphrase.encode(encoding) stream.write(passphrase) log.debug("Wrote passphrase on stdin.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign(self, data, **kwargs): """Create a signature for a message string or file. Note that this method is not for signing other keys. (In GnuPG's terms, what we all usually call 'keysigning' is actually termed operation, GnuPG differentiates between them, presumedly because these operations are also the same as the decryption operation. If the ``key_usage``s ``C (certification)``, ``S (sign)``, and ``E (encrypt)``, were all the same key, the key would "wear down" through frequent signing usage -- since signing data is usually done often -- meaning that the secret portion of the keypair, also used for decryption in this scenario, would have a statistically higher probability of an adversary obtaining an oracle for it (or for a portion of the rounds in the cipher algorithm, depending on the family of cryptanalytic attack used). In simpler terms: this function isn't for signing your friends' keys, it's for something like signing an email. :type data: :obj:`str` or :obj:`file` :param data: A string or file stream to sign. :param str default_key: The key to sign with. :param str passphrase: The passphrase to pipe to stdin. :param bool clearsign: If True, create a cleartext signature. :param bool detach: If True, create a detached signature. :param bool binary: If True, do not ascii armour the output. :param str digest_algo: The hash digest to use. Again, to see which hashes your GnuPG is capable of using, do: :command:`$ gpg --with-colons --list-config digestname`. The default, if unspecified, is ``'SHA512'``. """
if 'default_key' in kwargs: log.info("Signing message '%r' with keyid: %s" % (data, kwargs['default_key'])) else: log.warn("No 'default_key' given! Using first key on secring.") if hasattr(data, 'read'): result = self._sign_file(data, **kwargs) elif not _is_stream(data): stream = _make_binary_stream(data, self._encoding) result = self._sign_file(stream, **kwargs) stream.close() else: log.warn("Unable to sign message '%s' with type %s" % (data, type(data))) result = None return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(self, data): """Verify the signature on the contents of the string ``data``. """
f = _make_binary_stream(data, self._encoding) result = self.verify_file(f) f.close() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_file(self, file, sig_file=None): """Verify the signature on the contents of a file or file-like object. Can handle embedded signatures as well as detached signatures. If using detached signatures, the file containing the detached signature should be specified as the ``sig_file``. :param file file: A file descriptor object. :param str sig_file: A file containing the GPG signature data for ``file``. If given, ``file`` is verified via this detached signature. Its type will be checked with :func:`_util._is_file`. """
result = self._result_map['verify'](self) if sig_file is None: log.debug("verify_file(): Handling embedded signature") args = ["--verify"] proc = self._open_subprocess(args) writer = _util._threaded_copy_data(file, proc.stdin) self._collect_output(proc, result, writer, stdin=proc.stdin) else: if not _util._is_file(sig_file): log.debug("verify_file(): '%r' is not a file" % sig_file) return result log.debug('verify_file(): Handling detached verification') sig_fh = None try: sig_fh = open(sig_file, 'rb') args = ["--verify %s -" % sig_fh.name] proc = self._open_subprocess(args) writer = _util._threaded_copy_data(file, proc.stdin) self._collect_output(proc, result, writer, stdin=proc.stdin) finally: if sig_fh and not sig_fh.closed: sig_fh.close() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_keys(self, key_data): """ Import the key_data into our keyring. 'Must delete secret key first' 'ok' 'ok' """
## xxx need way to validate that key_data is actually a valid GPG key ## it might be possible to use --list-packets and parse the output result = self._result_map['import'](self) log.info('Importing: %r', key_data[:256]) data = _make_binary_stream(key_data, self._encoding) self._handle_io(['--import'], data, result, binary=True) data.close() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_keys(self, fingerprints, secret=False, subkeys=False): """Delete a key, or list of keys, from the current keyring. The keys must be referred to by their full fingerprints for GnuPG to delete them. If ``secret=True``, the corresponding secret keyring will be deleted from :obj:`.secring`. :type fingerprints: :obj:`str` or :obj:`list` or :obj:`tuple` :param fingerprints: A string, or a list/tuple of strings, representing the fingerprint(s) for the key(s) to delete. :param bool secret: If True, delete the corresponding secret key(s) also. (default: False) :param bool subkeys: If True, delete the secret subkey first, then the public key. (default: False) Same as: :command:`$gpg --delete-secret-and-public-key 0x12345678`. """
which = 'keys' if secret: which = 'secret-keys' if subkeys: which = 'secret-and-public-keys' if _is_list_or_tuple(fingerprints): fingerprints = ' '.join(fingerprints) args = ['--batch'] args.append("--delete-{0} {1}".format(which, fingerprints)) result = self._result_map['delete'](self) p = self._open_subprocess(args) self._collect_output(p, result, stdin=p.stdin) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_keys(self, keyids, secret=False, subkeys=False): """Export the indicated ``keyids``. :param str keyids: A keyid or fingerprint in any format that GnuPG will accept. :param bool secret: If True, export only the secret key. :param bool subkeys: If True, export the secret subkeys. """
which = '' if subkeys: which = '-secret-subkeys' elif secret: which = '-secret-keys' if _is_list_or_tuple(keyids): keyids = ' '.join(['%s' % k for k in keyids]) args = ["--armor"] args.append("--export{0} {1}".format(which, keyids)) p = self._open_subprocess(args) ## gpg --export produces no status-fd output; stdout will be empty in ## case of failure #stdout, stderr = p.communicate() result = self._result_map['export'](self) self._collect_output(p, result, stdin=p.stdin) log.debug('Exported:%s%r' % (os.linesep, result.fingerprints)) return result.data.decode(self._encoding, self._decode_errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_keys(self, secret=False): """List the keys currently in the keyring. The GnuPG option '--show-photos', according to the GnuPG manual, "does not work with --with-colons", but since we can't rely on all versions of GnuPG to explicitly handle this correctly, we should probably include it in the args. """
which = 'public-keys' if secret: which = 'secret-keys' args = [] args.append("--fixed-list-mode") args.append("--fingerprint") args.append("--with-colons") args.append("--list-options no-show-photos") args.append("--list-%s" % (which)) p = self._open_subprocess(args) # there might be some status thingumy here I should handle... (amk) # ...nope, unless you care about expired sigs or keys (stevegt) # Get the response information result = self._result_map['list'](self) self._collect_output(p, result, stdin=p.stdin) lines = result.data.decode(self._encoding, self._decode_errors).splitlines() self._parse_keys(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_packets(self, raw_data): """List the packet contents of a file."""
args = ["--list-packets"] result = self._result_map['packets'](self) self._handle_io(args, _make_binary_stream(raw_data, self._encoding), result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt(self, data, *recipients, **kwargs): """Encrypt the message contained in ``data`` to ``recipients``. :param str data: The file or bytestream to encrypt. :param str recipients: The recipients to encrypt to. Recipients must be specified keyID/fingerprint. Care should be taken in Python2.x to make sure that the given fingerprint is in fact a string and not a unicode object. Multiple recipients may be specified by doing ``GPG.encrypt(data, fpr1, fpr2, fpr3)`` etc. :param str default_key: The keyID/fingerprint of the key to use for signing. If given, ``data`` will be encrypted and signed. :param str passphrase: If given, and ``default_key`` is also given, use this passphrase to unlock the secret portion of the ``default_key`` to sign the encrypted ``data``. Otherwise, if ``default_key`` is not given, but ``symmetric=True``, then use this passphrase as the passphrase for symmetric encryption. Signing and symmetric encryption should *not* be combined when sending the ``data`` to other recipients, else the passphrase to the secret key would be shared with them. :param bool armor: If True, ascii armor the output; otherwise, the output will be in binary format. (Default: True) :param bool encrypt: If True, encrypt the ``data`` using the ``recipients`` public keys. (Default: True) :param bool symmetric: If True, encrypt the ``data`` to ``recipients`` using a symmetric key. See the ``passphrase`` parameter. Symmetric encryption and public key encryption can be used simultaneously, and will result in a ciphertext which is decryptable with either the symmetric ``passphrase`` or one of the corresponding private keys. :param bool always_trust: If True, ignore trust warnings on recipient keys. If False, display trust warnings. (default: True) :param str output: The output file to write to. If not specified, the encrypted output is returned, and thus should be stored as an object in Python. For example: 'The crow flies at midnight.' :param bool throw_keyids: If True, make all **recipients** keyids be zero'd out in packet information. This is the same as using **hidden_recipients** for all **recipients**. (Default: False). :param list hidden_recipients: A list of recipients that should have their keyids zero'd out in packet information. :param str cipher_algo: The cipher algorithm to use. To see available algorithms with your version of GnuPG, do: :command:`$ gpg --with-colons --list-config ciphername`. The default ``cipher_algo``, if unspecified, is ``'AES256'``. :param str digest_algo: The hash digest to use. Again, to see which hashes your GnuPG is capable of using, do: :command:`$ gpg --with-colons --list-config digestname`. The default, if unspecified, is ``'SHA512'``. :param str compress_algo: The compression algorithm to use. Can be one of ``'ZLIB'``, ``'BZIP2'``, ``'ZIP'``, or ``'Uncompressed'``. .. seealso:: :meth:`._encrypt` """
if _is_stream(data): stream = data else: stream = _make_binary_stream(data, self._encoding) result = self._encrypt(stream, recipients, **kwargs) stream.close() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt(self, message, **kwargs): """Decrypt the contents of a string or file-like object ``message``. :type message: file or str or :class:`io.BytesIO` :param message: A string or file-like object to decrypt. :param bool always_trust: Instruct GnuPG to ignore trust checks. :param str passphrase: The passphrase for the secret key used for decryption. :param str output: A filename to write the decrypted output to. """
stream = _make_binary_stream(message, self._encoding) result = self.decrypt_file(stream, **kwargs) stream.close() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt_file(self, filename, always_trust=False, passphrase=None, output=None): """Decrypt the contents of a file-like object ``filename`` . :param str filename: A file-like object to decrypt. :param bool always_trust: Instruct GnuPG to ignore trust checks. :param str passphrase: The passphrase for the secret key used for decryption. :param str output: A filename to write the decrypted output to. """
args = ["--decrypt"] if output: # write the output to a file with the specified name if os.path.exists(output): os.remove(output) # to avoid overwrite confirmation message args.append('--output %s' % output) if always_trust: args.append("--always-trust") result = self._result_map['crypt'](self) self._handle_io(args, filename, result, passphrase, binary=True) log.debug('decrypt result: %r', result.data) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_key_by_email(self, email, secret=False): """Find user's key based on their email address. :param str email: The email address to search for. :param bool secret: If True, search through secret keyring. """
for key in self.list_keys(secret=secret): for uid in key['uids']: if re.search(email, uid): return key raise LookupError("GnuPG public key for email %s not found!" % email)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_key_by_subkey(self, subkey): """Find a key by a fingerprint of one of its subkeys. :param str subkey: The fingerprint of the subkey to search for. """
for key in self.list_keys(): for sub in key['subkeys']: if sub[0] == subkey: return key raise LookupError( "GnuPG public key for subkey %s not found!" % subkey)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_keys(self, keyserver, *keyids): """Send keys to a keyserver."""
result = self._result_map['list'](self) log.debug('send_keys: %r', keyids) data = _util._make_binary_stream("", self._encoding) args = ['--keyserver', keyserver, '--send-keys'] args.extend(keyids) self._handle_io(args, data, result, binary=True) log.debug('send_keys result: %r', result.__dict__) data.close() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypted_to(self, raw_data): """Return the key to which raw_data is encrypted to."""
# TODO: make this support multiple keys. result = self._gpg.list_packets(raw_data) if not result.key: raise LookupError( "Content is not encrypted to a GnuPG key!") try: return self.find_key_by_keyid(result.key) except: return self.find_key_by_subkey(result.key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def imread(filename): ''' Like cv2.imread This function will make sure filename exists ''' im = cv2.imread(filename) if im is None: raise RuntimeError("file: '%s' not exists" % filename) return im
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find_all_template(im_source, im_search, threshold=0.5, maxcnt=0, rgb=False, bgremove=False): ''' Locate image position with cv2.templateFind Use pixel match to find pictures. Args: im_source(string): 图像、素材 im_search(string): 需要查找的图片 threshold: 阈值,当相识度小于该阈值的时候,就忽略掉 Returns: A tuple of found [(point, score), ...] Raises: IOError: when file read error ''' # method = cv2.TM_CCORR_NORMED # method = cv2.TM_SQDIFF_NORMED method = cv2.TM_CCOEFF_NORMED if rgb: s_bgr = cv2.split(im_search) # Blue Green Red i_bgr = cv2.split(im_source) weight = (0.3, 0.3, 0.4) resbgr = [0, 0, 0] for i in range(3): # bgr resbgr[i] = cv2.matchTemplate(i_bgr[i], s_bgr[i], method) res = resbgr[0]*weight[0] + resbgr[1]*weight[1] + resbgr[2]*weight[2] else: s_gray = cv2.cvtColor(im_search, cv2.COLOR_BGR2GRAY) i_gray = cv2.cvtColor(im_source, cv2.COLOR_BGR2GRAY) # 边界提取(来实现背景去除的功能) if bgremove: s_gray = cv2.Canny(s_gray, 100, 200) i_gray = cv2.Canny(i_gray, 100, 200) res = cv2.matchTemplate(i_gray, s_gray, method) w, h = im_search.shape[1], im_search.shape[0] result = [] while True: min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc if DEBUG: print('templmatch_value(thresh:%.1f) = %.3f' %(threshold, max_val)) # not show debug if max_val < threshold: break # calculator middle point middle_point = (top_left[0]+w/2, top_left[1]+h/2) result.append(dict( result=middle_point, rectangle=(top_left, (top_left[0], top_left[1] + h), (top_left[0] + w, top_left[1]), (top_left[0] + w, top_left[1] + h)), confidence=max_val )) if maxcnt and len(result) >= maxcnt: break # floodfill the already found area cv2.floodFill(res, None, max_loc, (-1000,), max_val-threshold+0.1, 1, flags=cv2.FLOODFILL_FIXED_RANGE) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find(im_source, im_search): ''' Only find maximum one object ''' r = find_all(im_source, im_search, maxcnt=1) return r[0] if r else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(self): """Creates context, when context is ready context_notify_cb is called"""
# Wrap callback methods in appropriate ctypefunc instances so # that the Pulseaudio C API can call them self._context_notify_cb = pa_context_notify_cb_t( self.context_notify_cb) self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb) self._update_cb = pa_context_subscribe_cb_t(self.update_cb) self._success_cb = pa_context_success_cb_t(self.success_cb) self._server_info_cb = pa_server_info_cb_t(self.server_info_cb) # Create the mainloop thread and set our context_notify_cb # method to be called when there's updates relating to the # connection to Pulseaudio _mainloop = pa_threaded_mainloop_new() _mainloop_api = pa_threaded_mainloop_get_api(_mainloop) context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii")) pa_context_set_state_callback(context, self._context_notify_cb, None) pa_context_connect(context, None, 0, None) pa_threaded_mainloop_start(_mainloop) self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100) self.sinks = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def server_info_cb(self, context, server_info_p, userdata): """Retrieves the default sink and calls request_update"""
server_info = server_info_p.contents self.request_update(context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def context_notify_cb(self, context, _): """Checks wether the context is ready -Queries server information (server_info_cb is called) -Subscribes to property changes on all sinks (update_cb is called) """
state = pa_context_get_state(context) if state == PA_CONTEXT_READY: pa_operation_unref( pa_context_get_server_info(context, self._server_info_cb, None)) pa_context_set_subscribe_callback(context, self._update_cb, None) pa_operation_unref(pa_context_subscribe( context, PA_SUBSCRIPTION_EVENT_CHANGE | PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SERVER, self._success_cb, None))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_cb(self, context, t, idx, userdata): """A sink property changed, calls request_update"""
if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVER: pa_operation_unref( pa_context_get_server_info(context, self._server_info_cb, None)) self.request_update(context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sink_info_cb(self, context, sink_info_p, _, __): """Updates self.output"""
if sink_info_p: sink_info = sink_info_p.contents volume_percent = round(100 * sink_info.volume.values[0] / 0x10000) volume_db = pa_sw_volume_to_dB(sink_info.volume.values[0]) self.currently_muted = sink_info.mute if volume_db == float('-Infinity'): volume_db = "-∞" else: volume_db = int(volume_db) muted = self.muted if sink_info.mute else self.unmuted if self.multi_colors and not sink_info.mute: color = self.get_gradient(volume_percent, self.colors) else: color = self.color_muted if sink_info.mute else self.color_unmuted if muted and self.format_muted is not None: output_format = self.format_muted else: output_format = self.format if self.bar_type == 'vertical': volume_bar = make_vertical_bar(volume_percent, self.vertical_bar_width) elif self.bar_type == 'horizontal': volume_bar = make_bar(volume_percent) else: raise Exception("bar_type must be 'vertical' or 'horizontal'") selected = "" dump = subprocess.check_output("pacmd dump".split(), universal_newlines=True) for line in dump.split("\n"): if line.startswith("set-default-sink"): default_sink = line.split()[1] if default_sink == self.current_sink: selected = self.format_selected self.output = { "color": color, "full_text": output_format.format( muted=muted, volume=volume_percent, db=volume_db, volume_bar=volume_bar, selected=selected), } self.send_output()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cycle_interface(self, increment=1): """Cycle through available interfaces in `increment` steps. Sign indicates direction."""
interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces] if self.interface in interfaces: next_index = (interfaces.index(self.interface) + increment) % len(interfaces) self.interface = interfaces[next_index] elif len(interfaces) > 0: self.interface = interfaces[0] if self.network_traffic: self.network_traffic.clear_counters() self.kbs_arr = [0.0] * self.graph_width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, seconds=300): """ Starts timer. If timer is already running it will increase remaining time instead. :param int seconds: Initial time. """
if self.state is TimerState.stopped: self.compare = time.time() + abs(seconds) self.state = TimerState.running elif self.state is TimerState.running: self.increase(seconds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def increase(self, seconds): """ Change remainig time value. :param int seconds: Seconds to add. Negative value substracts from remaining time. """
if self.state is TimerState.running: new_compare = self.compare + seconds if new_compare > time.time(): self.compare = new_compare
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Stop timer and execute ``on_reset`` if overflow occured. """
if self.state is not TimerState.stopped: if self.on_reset and self.state is TimerState.overflow: if callable(self.on_reset): self.on_reset() else: execute(self.on_reset) self.state = TimerState.stopped
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_line(self, message): """Unbuffered printing to stdout."""
self.out.write(message + "\n") self.out.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_line(self): """ Interrupted respecting reader for stdin. Raises EOFError if the end of stream has been reached """
try: line = self.inp.readline().strip() except KeyboardInterrupt: raise EOFError() # i3status sends EOF, or an empty line if not line: raise EOFError() return line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_treshold_interval(self): """ Current method is to compute average from all intervals. """
intervals = [m.interval for m in self.modules if hasattr(m, "interval")] if len(intervals) > 0: self.treshold_interval = round(sum(intervals) / len(intervals))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_signal_handler(self, signo, frame): """ This callback is called when SIGUSR1 signal is received. It updates outputs of all modules by calling their `run` method. Interval modules are updated in separate threads if their interval is above a certain treshold value. This treshold is computed by :func:`compute_treshold_interval` class method. The reasoning is that modules with larger intervals also usually take longer to refresh their output and that their output is not required in 'real time'. This also prevents possible lag when updating all modules in a row. """
if signo != signal.SIGUSR1: return for module in self.modules: if hasattr(module, "interval"): if module.interval > self.treshold_interval: thread = Thread(target=module.run) thread.start() else: module.run() else: module.run() self.async_refresh()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_line(self, line): """Parse a single line of JSON and write modified JSON back."""
prefix = "" # ignore comma at start of lines if line.startswith(","): line, prefix = line[1:], "," j = json.loads(line) yield j self.io.write_line(prefix + json.dumps(j))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_click(self, event): """ Override this method to do more interesting things with the event. """
DesktopNotification( title=event.title, body="{} until {}!".format(event.time_remaining, event.title), icon='dialog-information', urgency=1, timeout=0, ).display()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_urgent(self): """ Determine whether or not to set the urgent flag. If urgent_blink is set, toggles urgent flag on and off every second. """
if not self.current_event: return False now = datetime.now(tz=self.current_event.start.tzinfo) alert_time = now + timedelta(seconds=self.urgent_seconds) urgent = alert_time > self.current_event.start if urgent and self.urgent_blink: urgent = now.second % 2 == 0 and not self.urgent_acknowledged return urgent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init(self): ''' Use the location_code to perform a geolookup and find the closest station. If the location is a pws or icao station ID, no lookup will be peformed. ''' try: for no_lookup in ('pws', 'icao'): sid = self.location_code.partition(no_lookup + ':')[-1] if sid: self.station_id = self.location_code return except AttributeError: # Numeric or some other type, either way we'll just stringify # it below and perform a lookup. pass self.get_station_id()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_station_id(self): ''' Use geolocation to get the station ID ''' extra_opts = '/pws:0' if not self.use_pws else '' api_url = GEOLOOKUP_URL % (self.api_key, extra_opts, self.location_code) response = self.api_request(api_url) station_type = 'pws' if self.use_pws else 'airport' try: stations = response['location']['nearby_weather_stations'] nearest = stations[station_type]['station'][0] except (KeyError, IndexError): raise Exception( 'No locations matched location_code %s' % self.location_code) self.logger.error('nearest = %s', nearest) if self.use_pws: nearest_pws = nearest.get('id', '') if not nearest_pws: raise Exception('No id entry for nearest PWS') self.station_id = 'pws:%s' % nearest_pws else: nearest_airport = nearest.get('icao', '') if not nearest_airport: raise Exception('No icao entry for nearest airport') self.station_id = 'icao:%s' % nearest_airport
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_api_date(self): ''' Figure out the date to use for API requests. Assumes yesterday's date if between midnight and 10am Eastern time. Override this function in a subclass to change how the API date is calculated. ''' # NOTE: If you are writing your own function to get the date, make sure # to include the first if block below to allow for the ``date`` # parameter to hard-code a date. api_date = None if self.date is not None and not isinstance(self.date, datetime): try: api_date = datetime.strptime(self.date, '%Y-%m-%d') except (TypeError, ValueError): self.logger.warning('Invalid date \'%s\'', self.date) if api_date is None: utc_time = pytz.utc.localize(datetime.utcnow()) eastern = pytz.timezone('US/Eastern') api_date = eastern.normalize(utc_time.astimezone(eastern)) if api_date.hour < 10: # The scores on NHL.com change at 10am Eastern, if it's before # that time of day then we will use yesterday's date. api_date -= timedelta(days=1) self.date = api_date
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def handle_data(self, content): ''' Sometimes the weather data is set under an attribute of the "window" DOM object. Sometimes it appears as part of a javascript function. Catch either possibility. ''' if self.weather_data is not None: # We've already found weather data, no need to continue parsing return content = content.strip().rstrip(';') try: tag_text = self.get_starttag_text().lower() except AttributeError: tag_text = '' if tag_text.startswith('<script'): # Look for feed information embedded as a javascript variable begin = content.find('window.__data') if begin != -1: self.logger.debug('Located window.__data') # Look for end of JSON dict and end of javascript statement end = content.find('};', begin) if end == -1: self.logger.debug('Failed to locate end of javascript statement') else: # Strip the "window.__data=" from the beginning json_data = self.load_json( content[begin:end + 1].split('=', 1)[1].lstrip() ) if json_data is not None: def _find_weather_data(data): ''' Helper designed to minimize impact of potential structural changes to this data. ''' if isinstance(data, dict): if 'Observation' in data and 'DailyForecast' in data: return data else: for key in data: ret = _find_weather_data(data[key]) if ret is not None: return ret return None weather_data = _find_weather_data(json_data) if weather_data is None: self.logger.debug( 'Failed to locate weather data in the ' 'following data structure: %s', json_data ) else: self.weather_data = weather_data return for line in content.splitlines(): line = line.strip().rstrip(';') if line.startswith('var adaptorParams'): # Strip off the "var adaptorParams = " from the beginning, # and the javascript semicolon from the end. This will give # us JSON that we can load. weather_data = self.load_json(line.split('=', 1)[1].lstrip()) if weather_data is not None: self.weather_data = weather_data return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main_loop(self): """ Mainloop blocks so we thread it."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = int(getattr(self, 'port', 1738)) sock.bind(('127.0.0.1', port)) while True: data, addr = sock.recvfrom(512) color = data.decode().strip() self.color = self.colors.get(color, color)