code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
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 | def nodata(status_code) | Translate NODATA status codes from GnuPG to messages. | 7.895945 | 5.962525 | 1.324262 |
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 | def progress(status_code) | Translate PROGRESS status codes from GnuPG to messages. | 12.900661 | 11.484227 | 1.123337 |
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) | def _clean_key_expiration_option(self) | validates the expiration option supplied | 6.296867 | 5.617819 | 1.120874 |
deselect_sub_key = "key 0\n"
_input = self._main_key_command()
for sub_key_number in range(1, sub_keys_number + 1):
_input += self._sub_key_command(sub_key_number) + deselect_sub_key
return "%ssave\n" % _input | def gpg_interactive_input(self, sub_keys_number) | processes series of inputs normally supplied on --edit-key but passed through stdin
this ensures that no other --edit-key command is actually passing through. | 5.420354 | 5.526022 | 0.980878 |
if key in ("USERID_HINT", "NEED_PASSPHRASE",
"GET_HIDDEN", "SIGEXPIRED", "KEYEXPIRED",
"GOOD_PASSPHRASE", "GOT_IT", "GET_LINE"):
pass
elif key in ("BAD_PASSPHRASE", "MISSING_PASSPHRASE"):
self.status = key.replace("_", " ").lower()
else:
self.status = 'failed'
raise ValueError("Unknown status message: %r" % key) | def _handle_status(self, key, value) | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. | 6.536693 | 5.771779 | 1.132526 |
if key in ("GOOD_PASSPHRASE"):
pass
elif key == "KEY_CONSIDERED":
self.status = key.replace("_", " ").lower()
elif key == "KEY_NOT_CREATED":
self.status = 'key not created'
elif key == "KEY_CREATED":
(self.type, self.fingerprint) = value.split()
self.status = 'key created'
elif key == "NODATA":
self.status = nodata(value)
elif key == "PROGRESS":
self.status = progress(value.split(' ', 1)[0])
elif key == "PINENTRY_LAUNCHED":
log.warn(("GnuPG has just attempted to launch whichever pinentry "
"program you have configured, in order to obtain the "
"passphrase for this key. If you did not use the "
"`passphrase=` parameter, please try doing so. Otherwise, "
"see Issues #122 and #137:"
"\nhttps://github.com/isislovecruft/python-gnupg/issues/122"
"\nhttps://github.com/isislovecruft/python-gnupg/issues/137"))
self.status = 'key not created'
elif (key.startswith("TRUST_") or
key.startswith("PKA_TRUST_") or
key == "NEWSIG"):
pass
else:
raise ValueError("Unknown status message: %r" % key)
if self.type in ('B', 'P'):
self.primary_created = True
if self.type in ('B', 'S'):
self.subkey_created = True | def _handle_status(self, key, value) | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. | 4.434901 | 4.167984 | 1.06404 |
if key in ("DELETE_PROBLEM", "KEY_CONSIDERED"):
self.status = self.problem_reason.get(value, "Unknown error: %r"
% value)
else:
raise ValueError("Unknown status message: %r" % key) | def _handle_status(self, key, value) | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. | 8.194096 | 7.613044 | 1.076323 |
if key in (
"USERID_HINT",
"NEED_PASSPHRASE",
"BAD_PASSPHRASE",
"GOOD_PASSPHRASE",
"MISSING_PASSPHRASE",
"PINENTRY_LAUNCHED",
"BEGIN_SIGNING",
"CARDCTRL",
"INV_SGNR",
"SIGEXPIRED",
"KEY_CONSIDERED",
):
self.status = key.replace("_", " ").lower()
elif key == "SIG_CREATED":
(self.sig_type, self.sig_algo, self.sig_hash_algo,
self.what, self.timestamp, self.fingerprint) = value.split()
elif key == "KEYEXPIRED":
self.status = "skipped signing key, key expired"
if (value is not None) and (len(value) > 0):
self.status += " on {}".format(str(value))
elif key == "KEYREVOKED":
self.status = "skipped signing key, key revoked"
if (value is not None) and (len(value) > 0):
self.status += " on {}".format(str(value))
elif key == "NODATA":
self.status = nodata(value)
elif key == "PROGRESS":
self.status = progress(value.split(' ', 1)[0])
else:
raise ValueError("Unknown status message: %r" % key) | def _handle_status(self, key, value) | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. | 4.192704 | 3.817339 | 1.098332 |
if key == "IMPORTED":
# this duplicates info we already see in import_ok & import_problem
pass
elif key == "PINENTRY_LAUNCHED":
log.warn(("GnuPG has just attempted to launch whichever pinentry "
"program you have configured, in order to obtain the "
"passphrase for this key. If you did not use the "
"`passphrase=` parameter, please try doing so. Otherwise, "
"see Issues #122 and #137:"
"\nhttps://github.com/isislovecruft/python-gnupg/issues/122"
"\nhttps://github.com/isislovecruft/python-gnupg/issues/137"))
elif key == "KEY_CONSIDERED":
self.results.append({
'status': key.replace("_", " ").lower(),
})
elif key == "NODATA":
self.results.append({'fingerprint': None,
'status': 'No valid data found'})
elif key == "IMPORT_OK":
reason, fingerprint = value.split()
reasons = []
for code, text in self._ok_reason.items():
if int(reason) == int(code):
reasons.append(text)
reasontext = '\n'.join(reasons) + "\n"
self.results.append({'fingerprint': fingerprint,
'status': reasontext})
self.fingerprints.append(fingerprint)
elif key == "IMPORT_PROBLEM":
try:
reason, fingerprint = value.split()
except:
reason = value
fingerprint = '<unknown>'
self.results.append({'fingerprint': fingerprint,
'status': self._problem_reason[reason]})
elif key == "IMPORT_RES":
import_res = value.split()
for x in self.counts.keys():
self.counts[x] = int(import_res.pop(0))
elif key == "KEYEXPIRED":
res = {'fingerprint': None,
'status': 'Key expired'}
self.results.append(res)
## Accoring to docs/DETAILS L859, SIGEXPIRED is obsolete:
## "Removed on 2011-02-04. This is deprecated in favor of KEYEXPIRED."
elif key == "SIGEXPIRED":
res = {'fingerprint': None,
'status': 'Signature expired'}
self.results.append(res)
else:
raise ValueError("Unknown status message: %r" % key) | def _handle_status(self, key, value) | Parse a status code from the attached GnuPG process.
:raises ValueError: if the status message is unknown. | 4.31721 | 4.266048 | 1.011993 |
informational_keys = ["KEY_CONSIDERED"]
if key in ("EXPORTED"):
self.fingerprints.append(value)
elif key == "EXPORT_RES":
export_res = value.split()
for x in self.counts.keys():
self.counts[x] += int(export_res.pop(0))
elif key not in informational_keys:
raise ValueError("Unknown status message: %r" % key) | def _handle_status(self, key, value) | Parse a status code from the attached GnuPG process.
:raises ValueError: if the status message is unknown. | 6.696549 | 6.059785 | 1.10508 |
if key in (
"ENC_TO",
"USERID_HINT",
"GOODMDC",
"END_DECRYPTION",
"BEGIN_SIGNING",
"NO_SECKEY",
"ERROR",
"NODATA",
"CARDCTRL",
):
# in the case of ERROR, this is because a more specific error
# message will have come first
pass
elif key in (
"NEED_PASSPHRASE",
"BAD_PASSPHRASE",
"GOOD_PASSPHRASE",
"MISSING_PASSPHRASE",
"DECRYPTION_FAILED",
"KEY_NOT_CREATED",
"KEY_CONSIDERED",
):
self.status = key.replace("_", " ").lower()
elif key == "NEED_TRUSTDB":
self._gpg._create_trustdb()
elif key == "NEED_PASSPHRASE_SYM":
self.status = 'need symmetric passphrase'
elif key == "BEGIN_DECRYPTION":
self.status = 'decryption incomplete'
elif key == "BEGIN_ENCRYPTION":
self.status = 'encryption incomplete'
elif key == "DECRYPTION_OKAY":
self.status = 'decryption ok'
self.ok = True
elif key == "END_ENCRYPTION":
self.status = 'encryption ok'
self.ok = True
elif key == "INV_RECP":
self.status = 'invalid recipient'
elif key == "KEYEXPIRED":
self.status = 'key expired'
elif key == "KEYREVOKED":
self.status = 'key revoked'
elif key == "SIG_CREATED":
self.status = 'sig created'
elif key == "SIGEXPIRED":
self.status = 'sig expired'
elif key == "PLAINTEXT":
fmt, dts = value.split(' ', 1)
if dts.find(' ') > 0:
self.data_timestamp, self.data_filename = dts.split(' ', 1)
else:
self.data_timestamp = dts
## GnuPG gives us a hex byte for an ascii char corresponding to
## the data format of the resulting plaintext,
## i.e. '62'→'b':= binary data
self.data_format = chr(int(str(fmt), 16))
else:
super(Crypt, self)._handle_status(key, value) | def _handle_status(self, key, value) | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. | 4.265494 | 4.068177 | 1.048502 |
if key in (
'NO_SECKEY',
'BEGIN_DECRYPTION',
'DECRYPTION_FAILED',
'END_DECRYPTION',
'GOOD_PASSPHRASE',
'BAD_PASSPHRASE',
'KEY_CONSIDERED'
):
pass
elif key == 'NODATA':
self.status = nodata(value)
elif key == 'ENC_TO':
key, _, _ = value.split()
if not self.key:
self.key = key
self.encrypted_to.append(key)
elif key in ('NEED_PASSPHRASE', 'MISSING_PASSPHRASE'):
self.need_passphrase = True
elif key == 'NEED_PASSPHRASE_SYM':
self.need_passphrase_sym = True
elif key == 'USERID_HINT':
self.userid_hint = value.strip().split()
else:
raise ValueError("Unknown status message: %r" % key) | def _handle_status(self, key, value) | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. | 4.043957 | 3.76417 | 1.074329 |
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) | def _create_trustdb(cls) | Create the trustdb file in our homedir, if it doesn't exist. | 5.998693 | 5.060924 | 1.185296 |
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() | 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. | 3.796358 | 3.701059 | 1.025749 |
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() | 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. | 4.514048 | 4.421579 | 1.020913 |
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() | 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. | 3.937736 | 3.745649 | 1.051283 |
if self.isEnabledFor(GNUPG_STATUS_LEVEL):
self._log(GNUPG_STATUS_LEVEL, message, args, **kwargs) | def status(self, message, *args, **kwargs) | LogRecord for GnuPG internal status messages. | 4.920499 | 3.067068 | 1.604301 |
_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 | 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.
==== ======== ======================================== | 4.206477 | 4.202444 | 1.00096 |
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 | 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. | 6.439504 | 5.40417 | 1.191581 |
prefs = _check_preferences(prefs)
if prefs is not None:
self._prefs = prefs | 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. | 6.067231 | 11.395315 | 0.532432 |
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 | 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. | 4.00358 | 3.656259 | 1.094994 |
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 | 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. | 4.017617 | 3.410245 | 1.178102 |
proc = self._open_subprocess(["--list-config", "--with-colons"])
result = self._result_map['list'](self)
self._read_data(proc.stdout, result)
if proc.returncode:
raise RuntimeError("Error invoking gpg: %s" % result.data)
else:
try:
proc.terminate()
except OSError:
log.error(("Could neither invoke nor terminate a gpg process... "
"Are you sure you specified the corrent (and full) "
"path to the gpg binary?"))
version_line = result.data.partition(b':version:')[2].decode()
if not version_line:
raise RuntimeError("Got invalid version line from gpg: %s\n" % result.data)
self.binary_version = version_line.split('\n')[0]
if not _VERSION_RE.match(self.binary_version):
raise RuntimeError("Got invalid version line from gpg: %s\n" % self.binary_version)
log.debug("Using GnuPG version %s" % self.binary_version) | def _check_sane_and_get_gpg_version(self) | Check that everything runs alright, and grab the gpg binary's
version number while we're at it, storing it as :data:`binary_version`.
:raises RuntimeError: if we cannot invoke the gpg binary. | 4.556135 | 4.168549 | 1.092979 |
## 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 | 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. | 4.527373 | 3.970004 | 1.140395 |
## 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) | 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. | 3.05962 | 3.278361 | 0.933277 |
# All of the userland messages (i.e. not status-fd lines) we're not
# interested in passing to our logger
userland_messages_to_ignore = []
if self.ignore_homedir_permissions:
userland_messages_to_ignore.append('unsafe ownership on homedir')
lines = []
while True:
line = stream.readline()
if len(line) == 0:
break
lines.append(line)
line = line.rstrip()
if line.startswith('[GNUPG:]'):
line = _util._deprefix(line, '[GNUPG:] ', log.status)
keyword, value = _util._separate_keyword(line)
result._handle_status(keyword, value)
elif line.startswith('gpg:'):
line = _util._deprefix(line, 'gpg: ')
keyword, value = _util._separate_keyword(line)
# Silence warnings from gpg we're supposed to ignore
ignore = any(msg in value for msg in userland_messages_to_ignore)
if not ignore:
# Log gpg's userland messages at our own levels:
if keyword.upper().startswith("WARNING"):
log.warn("%s" % value)
elif keyword.upper().startswith("FATAL"):
log.critical("%s" % value)
# Handle the gpg2 error where a missing trustdb.gpg is,
# for some stupid reason, considered fatal:
if value.find("trustdb.gpg") and value.find("No such file"):
result._handle_status('NEED_TRUSTDB', '')
else:
if self.verbose:
log.info("%s" % line)
else:
log.debug("%s" % line)
result.stderr = ''.join(lines) | def _read_response(self, stream, result) | Reads all the stderr output from GPG, taking notice only of lines
that begin with the magic [GNUPG:] prefix.
Calls methods on the response object for each valid token found, with
the arg being the remainder of the status line.
:param stream: A byte-stream, file handle, or a
:data:`subprocess.PIPE` for parsing the status codes
from the GnuPG process.
:param result: The result parser class from :mod:`~gnupg._parsers` ―
the ``handle_status()`` method of that class will be
called in order to parse the output of ``stream``. | 5.304786 | 5.001405 | 1.060659 |
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)) | 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`. | 3.52972 | 3.698728 | 0.954307 |
string_levels = ('basic', 'advanced', 'expert', 'guru')
if verbose is True:
# The caller wants logging, but we need a valid --debug-level
# for gpg. Default to "basic", and warn about the ambiguity.
verbose = 'basic'
if (isinstance(verbose, str) and not (verbose in string_levels)):
verbose = 'basic'
self.verbose = verbose | def _set_verbose(self, verbose) | Check and set our :data:`verbose` attribute.
The debug-level must be a string or an integer. If it is one of
the allowed strings, GnuPG will translate it internally to it's
corresponding integer level:
basic = 1-2
advanced = 3-5
expert = 6-8
guru = 9+
If it's not one of the recognised string levels, then then
entire argument is ignored by GnuPG. :(
To fix that stupid behaviour, if they wanted debugging but typo'd
the string level (or specified ``verbose=True``), we'll default to
'basic' logging. | 10.266981 | 5.679311 | 1.807786 |
stderr = codecs.getreader(self._encoding)(process.stderr)
rr = threading.Thread(target=self._read_response,
args=(stderr, result))
rr.setDaemon(True)
log.debug('stderr reader: %r', rr)
rr.start()
stdout = process.stdout
dr = threading.Thread(target=self._read_data, args=(stdout, result))
dr.setDaemon(True)
log.debug('stdout reader: %r', dr)
dr.start()
dr.join()
rr.join()
if writer is not None:
writer.join()
process.wait()
if stdin is not None:
try:
stdin.close()
except IOError:
pass
stderr.close()
stdout.close() | def _collect_output(self, process, result, writer=None, stdin=None) | Drain the subprocesses output streams, writing the collected output
to the result. If a writer thread (writing to the subprocess) is given,
make sure it's joined before returning. If a stdin stream is given,
close it before returning. | 2.403223 | 2.431922 | 0.988199 |
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 | def _handle_io(self, args, file, result, passphrase=False, binary=False) | Handle a call to GPG - pass input data, collect output data. | 4.845301 | 4.366901 | 1.109551 |
if not keyserver:
keyserver = self.keyserver
args = ['--keyserver {0}'.format(keyserver),
'--recv-keys {0}'.format(keyids)]
log.info('Requesting keys from %s: %s' % (keyserver, keyids))
result = self._result_map['import'](self)
proc = self._open_subprocess(args)
self._collect_output(proc, result)
log.debug('recv_keys result: %r', result.__dict__)
return result | def _recv_keys(self, keyids, keyserver=None) | Import keys from a keyserver.
:param str keyids: A space-delimited string containing the keyids to
request.
:param str keyserver: The keyserver to request the ``keyids`` from;
defaults to `gnupg.GPG.keyserver`. | 4.290201 | 3.813545 | 1.12499 |
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 | 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'``. | 4.661099 | 4.480354 | 1.040342 |
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 | 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. | 3.796697 | 3.89031 | 0.975937 |
return Storage(name=name, contact=contact, public_key=public_key) | 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. | 4.335358 | 7.110463 | 0.609715 |
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) | 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. | 2.7803 | 2.869308 | 0.96898 |
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 | 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. | 2.591017 | 2.497246 | 1.03755 |
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 | 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>. | 2.530854 | 2.554622 | 0.990696 |
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 | 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. | 3.106347 | 3.086264 | 1.006507 |
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 | 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. | 3.138721 | 3.118532 | 1.006474 |
try:
statinfo = os.lstat(filename)
log.debug("lstat(%r) with type=%s gave us %r"
% (repr(filename), type(filename), repr(statinfo)))
if not (statinfo.st_size > 0):
raise ValueError("'%s' appears to be an empty file!" % filename)
except OSError as oserr:
log.error(oserr)
if filename == '-':
log.debug("Got '-' for filename, assuming sys.stdin...")
return True
except (ValueError, TypeError, IOError) as err:
log.error(err)
else:
return True
return False | def _is_file(filename) | Check that the size of the thing which is supposed to be a filename has
size greater than zero, without following symbolic links or using
:func:os.path.isfile.
:param filename: An object to check.
:rtype: bool
:returns: True if **filename** is file-like, False otherwise. | 4.000475 | 3.861776 | 1.035916 |
if (_py3k and isinstance(thing, str)):
return True
if (not _py3k and isinstance(thing, basestring)):
return True
return False | def _is_string(thing) | Check that **thing** is a string. The definition of the latter depends
upon the Python version.
:param thing: The thing to check if it's a string.
:rtype: bool
:returns: ``True`` if **thing** is string (or unicode in Python2). | 2.918587 | 3.707083 | 0.7873 |
(major, minor, micro) = _match_version_string(version)
if major == 1:
return True
return False | 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. | 4.392936 | 5.166538 | 0.850267 |
(major, minor, micro) = _match_version_string(version)
if major == 2:
return True
return False | 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. | 4.430084 | 5.217242 | 0.849124 |
if _py3k:
if isinstance(thing, str):
thing = thing.encode(encoding)
else:
if type(thing) is not str:
thing = thing.encode(encoding)
try:
rv = BytesIO(thing)
except NameError:
rv = StringIO(thing)
return rv | def _make_binary_stream(thing, encoding=None, armor=True) | Encode **thing**, then make it stream/file-like.
:param thing: The thing to turn into a encoded stream.
:rtype: ``io.BytesIO`` or ``io.StringIO``.
:returns: The encoded **thing**, wrapped in an ``io.BytesIO`` (if
available), otherwise wrapped in a ``io.StringIO``. | 2.858113 | 3.059508 | 0.934174 |
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 | 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. | 3.58361 | 3.688363 | 0.971599 |
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
return ''.join(random.choice(chars) for x in range(length)) | def _make_random_string(length) | Returns a random lowercase, uppercase, alphanumerical string.
:param int length: The length in bytes of the string to generate. | 1.978542 | 2.459332 | 0.804504 |
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) | 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)``. | 4.782375 | 4.305005 | 1.110887 |
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)) | 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'. | 2.92544 | 3.229725 | 0.905786 |
try:
first, rest = line.split(None, 1)
except ValueError:
first = line.strip()
rest = ''
return first, rest | def _separate_keyword(line) | Split the line, and return (first_word, the_rest). | 2.825452 | 2.330987 | 1.212127 |
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 | 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. | 2.463227 | 3.035826 | 0.811386 |
def _can_allow(p):
if not os.access(p, flags):
return False
if abspath_only and not os.path.abspath(p):
log.warn('Ignoring %r (path is not absolute)', p)
return False
if disallow_symlinks and os.path.islink(p):
log.warn('Ignoring %r (path is a symlink)', p)
return False
return True
result = []
exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep))
path = os.environ.get('PATH', None)
if path is None:
return []
for p in os.environ.get('PATH', '').split(os.pathsep):
p = os.path.join(p, executable)
if _can_allow(p):
result.append(p)
for e in exts:
pext = p + e
if _can_allow(pext):
result.append(pext)
return result | def _which(executable, flags=os.X_OK, abspath_only=False, disallow_symlinks=False) | Borrowed from Twisted's :mod:twisted.python.proutils .
Search PATH for executable files with the given name.
On newer versions of MS-Windows, the PATHEXT environment variable will be
set to the list of file extensions for files considered executable. This
will normally include things like ".EXE". This fuction will also find files
with the given name ending with any of these extensions.
On MS-Windows the only flag that has any meaning is os.F_OK. Any other
flags will be ignored.
Note: This function does not help us prevent an attacker who can already
manipulate the environment's PATH settings from placing malicious code
higher in the PATH. It also does happily follows links.
:param str name: The name for which to search.
:param int flags: Arguments to L{os.access}.
:rtype: list
:returns: A list of the full paths to files found, in the order in which
they were found. | 1.787406 | 1.914029 | 0.933845 |
passphrase = '%s\n' % passphrase
passphrase = passphrase.encode(encoding)
stream.write(passphrase)
log.debug("Wrote passphrase on stdin.") | 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()``. | 4.730275 | 6.073846 | 0.778794 |
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 | 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
'certification'...) Even though they are cryptographically the same
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'``. | 3.966774 | 3.811745 | 1.040671 |
f = _make_binary_stream(data, self._encoding)
result = self.verify_file(f)
f.close()
return result | def verify(self, data) | Verify the signature on the contents of the string ``data``.
>>> gpg = GPG(homedir="doctests")
>>> input = gpg.gen_key_input(Passphrase='foo')
>>> key = gpg.gen_key(input)
>>> assert key
>>> sig = gpg.sign('hello',keyid=key.fingerprint,passphrase='bar')
>>> assert not sig
>>> sig = gpg.sign('hello',keyid=key.fingerprint,passphrase='foo')
>>> assert sig
>>> verify = gpg.verify(sig.data)
>>> assert verify | 6.039328 | 13.570437 | 0.445036 |
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 | 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`. | 3.309353 | 3.076411 | 1.075719 |
## 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 | def import_keys(self, key_data) | Import the key_data into our keyring.
>>> import shutil
>>> shutil.rmtree("doctests")
>>> gpg = gnupg.GPG(homedir="doctests")
>>> inpt = gpg.gen_key_input()
>>> key1 = gpg.gen_key(inpt)
>>> print1 = str(key1.fingerprint)
>>> pubkey1 = gpg.export_keys(print1)
>>> seckey1 = gpg.export_keys(print1,secret=True)
>>> key2 = gpg.gen_key(inpt)
>>> print2 = key2.fingerprint
>>> seckeys = gpg.list_keys(secret=True)
>>> pubkeys = gpg.list_keys()
>>> assert print1 in seckeys.fingerprints
>>> assert print1 in pubkeys.fingerprints
>>> str(gpg.delete_keys(print1))
'Must delete secret key first'
>>> str(gpg.delete_keys(print1,secret=True))
'ok'
>>> str(gpg.delete_keys(print1))
'ok'
>>> pubkeys = gpg.list_keys()
>>> assert not print1 in pubkeys.fingerprints
>>> result = gpg.import_keys(pubkey1)
>>> pubkeys = gpg.list_keys()
>>> seckeys = gpg.list_keys(secret=True)
>>> assert not print1 in seckeys.fingerprints
>>> assert print1 in pubkeys.fingerprints
>>> result = gpg.import_keys(seckey1)
>>> assert result
>>> seckeys = gpg.list_keys(secret=True)
>>> assert print1 in seckeys.fingerprints | 10.667503 | 12.086448 | 0.8826 |
if keyids:
keys = ' '.join([key for key in keyids])
return self._recv_keys(keys, **kwargs)
else:
log.error("No keyids requested for --recv-keys!") | def recv_keys(self, *keyids, **kwargs) | Import keys from a keyserver.
>>> gpg = gnupg.GPG(homedir="doctests")
>>> key = gpg.recv_keys('3FF0DB166A7476EA', keyserver='hkp://pgp.mit.edu')
>>> assert key
:param str keyids: Each ``keyids`` argument should be a string
containing a keyid to request.
:param str keyserver: The keyserver to request the ``keyids`` from;
defaults to `gnupg.GPG.keyserver`. | 5.10892 | 6.784304 | 0.75305 |
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 | 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`. | 4.565198 | 4.50813 | 1.012659 |
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) | 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. | 5.923381 | 6.088512 | 0.972878 |
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 | 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.
>>> import shutil
>>> shutil.rmtree("doctests")
>>> gpg = GPG(homedir="doctests")
>>> input = gpg.gen_key_input()
>>> result = gpg.gen_key(input)
>>> print1 = result.fingerprint
>>> result = gpg.gen_key(input)
>>> print2 = result.fingerprint
>>> pubkeys = gpg.list_keys()
>>> assert print1 in pubkeys.fingerprints
>>> assert print2 in pubkeys.fingerprints | 11.56079 | 11.120138 | 1.039626 |
args = ["--list-packets"]
result = self._result_map['packets'](self)
self._handle_io(args, _make_binary_stream(raw_data, self._encoding),
result)
return result | def list_packets(self, raw_data) | List the packet contents of a file. | 11.554087 | 9.781471 | 1.181222 |
args = []
input_command = ""
if passphrase:
passphrase_arg = "--passphrase-fd 0"
input_command = "%s\n" % passphrase
args.append(passphrase_arg)
if default_key:
args.append(str("--default-key %s" % default_key))
args.extend(["--command-fd 0", "--sign-key %s" % keyid])
p = self._open_subprocess(args)
result = self._result_map['signing'](self)
confirm_command = "%sy\n" % input_command
p.stdin.write(b(confirm_command))
self._collect_output(p, result, stdin=p.stdin)
return result | def sign_key(self, keyid, default_key=None, passphrase=None) | sign (an imported) public key - keyid, with default secret key
>>> import gnupg
>>> gpg = gnupg.GPG(homedir="doctests")
>>> key_input = gpg.gen_key_input()
>>> key = gpg.gen_key(key_input)
>>> gpg.sign_key(key['fingerprint'])
>>> gpg.list_sigs(key['fingerprint'])
:param str keyid: key shortID, longID, fingerprint or email_address
:param str passphrase: passphrase used when creating the key, leave None otherwise
:returns: The result giving status of the key signing...
success can be verified by gpg.list_sigs(keyid) | 4.700129 | 5.111473 | 0.919525 |
passphrase = passphrase.encode(self._encoding) if passphrase else passphrase
try:
sub_keys_number = len(self.list_sigs(keyid)[0]['subkeys']) if expire_subkeys else 0
except IndexError:
sub_keys_number = 0
expiration_input = KeyExpirationInterface(expiration_time, passphrase).gpg_interactive_input(sub_keys_number)
args = ["--command-fd 0", "--edit-key %s" % keyid]
p = self._open_subprocess(args)
p.stdin.write(b(expiration_input))
result = self._result_map['expire'](self)
p.stdin.write(b(expiration_input))
self._collect_output(p, result, stdin=p.stdin)
return result | def expire(self, keyid, expiration_time='1y', passphrase=None, expire_subkeys=True) | Changes GnuPG key expiration by passing in new time period (from now) through
subprocess's stdin
>>> import gnupg
>>> gpg = gnupg.GPG(homedir="doctests")
>>> key_input = gpg.gen_key_input()
>>> key = gpg.gen_key(key_input)
>>> gpg.expire(key.fingerprint, '2w', 'good passphrase')
:param str keyid: key shortID, longID, email_address or fingerprint
:param str expiration_time: 0 or number of days (d), or weeks (*w) , or months (*m)
or years (*y) for when to expire the key, from today.
:param str passphrase: passphrase used when creating the key, leave None otherwise
:param bool expire_subkeys: to indicate whether the subkeys will also change the
expiration time by the same period -- default is True
:returns: The result giving status of the change in expiration...
the new expiration date can be obtained by .list_keys() | 5.777278 | 5.32908 | 1.084104 |
args = ["--gen-key --cert-digest-algo SHA512 --batch"]
key = self._result_map['generate'](self)
f = _make_binary_stream(input, self._encoding)
self._handle_io(args, f, key, binary=True)
f.close()
fpr = str(key.fingerprint)
if len(fpr) == 20:
for d in map(lambda x: os.path.dirname(x),
[self.temp_keyring, self.temp_secring]):
if not os.path.exists(d):
os.makedirs(d)
if self.temp_keyring:
if os.path.isfile(self.temp_keyring):
prefix = os.path.join(self.temp_keyring, fpr)
try: os.rename(self.temp_keyring, prefix+".pubring")
except OSError as ose: log.error(str(ose))
if self.temp_secring:
if os.path.isfile(self.temp_secring):
prefix = os.path.join(self.temp_secring, fpr)
try: os.rename(self.temp_secring, prefix+".secring")
except OSError as ose: log.error(str(ose))
log.info("Key created. Fingerprint: %s" % fpr)
key.keyring = self.temp_keyring
key.secring = self.temp_secring
self.temp_keyring = None
self.temp_secring = None
return key | def gen_key(self, input) | Generate a GnuPG key through batch file key generation. See
:meth:`GPG.gen_key_input()` for creating the control input.
>>> import gnupg
>>> gpg = gnupg.GPG(homedir="doctests")
>>> key_input = gpg.gen_key_input()
>>> key = gpg.gen_key(key_input)
>>> assert key.fingerprint
:param dict input: A dictionary of parameters and values for the new
key.
:returns: The result mapping with details of the new key, which is a
:class:`GenKey <gnupg._parsers.GenKey>` object. | 3.043027 | 3.167966 | 0.960562 |
if _is_stream(data):
stream = data
else:
stream = _make_binary_stream(data, self._encoding)
result = self._encrypt(stream, recipients, **kwargs)
stream.close()
return result | 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:
>>> import shutil
>>> import gnupg
>>> if os.path.exists("doctests"):
... shutil.rmtree("doctests")
>>> gpg = gnupg.GPG(homedir="doctests")
>>> key_settings = gpg.gen_key_input(key_type='RSA',
... key_length=1024,
... key_usage='ESCA',
... passphrase='foo')
>>> key = gpg.gen_key(key_settings)
>>> message = "The crow flies at midnight."
>>> encrypted = str(gpg.encrypt(message, key.fingerprint))
>>> assert encrypted != message
>>> assert not encrypted.isspace()
>>> decrypted = str(gpg.decrypt(encrypted, passphrase='foo'))
>>> assert not decrypted.isspace()
>>> decrypted
'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` | 3.989209 | 5.81985 | 0.685449 |
stream = _make_binary_stream(message, self._encoding)
result = self.decrypt_file(stream, **kwargs)
stream.close()
return result | 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. | 5.194645 | 7.585572 | 0.684806 |
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 | 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. | 5.649669 | 6.499151 | 0.869293 |
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) | 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. | 4.653064 | 5.796973 | 0.802671 |
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) | 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. | 4.651116 | 5.027787 | 0.925082 |
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 | def send_keys(self, keyserver, *keyids) | Send keys to a keyserver. | 5.953388 | 5.807807 | 1.025066 |
# 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) | def encrypted_to(self, raw_data) | Return the key to which raw_data is encrypted to. | 6.407442 | 5.436964 | 1.178496 |
'''
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 | def imread(filename) | Like cv2.imread
This function will make sure filename exists | 6.508479 | 4.065651 | 1.600845 |
'''
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 | 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 | 2.675823 | 2.070674 | 1.292247 |
'''
SIFT特征点匹配
'''
res = find_all_sift(im_source, im_search, min_match_count, maxcnt=1)
if not res:
return None
return res[0] | def find_sift(im_source, im_search, min_match_count=4) | SIFT特征点匹配 | 5.02276 | 3.793426 | 1.324069 |
'''
优先Template,之后Sift
@ return [(x,y), ...]
'''
result = find_all_template(im_source, im_search, maxcnt=maxcnt)
if not result:
result = find_all_sift(im_source, im_search, maxcnt=maxcnt)
if not result:
return []
return [match["result"] for match in result] | def find_all(im_source, im_search, maxcnt=0) | 优先Template,之后Sift
@ return [(x,y), ...] | 4.45151 | 2.39245 | 1.860649 |
'''
Only find maximum one object
'''
r = find_all(im_source, im_search, maxcnt=1)
return r[0] if r else None | def find(im_source, im_search) | Only find maximum one object | 8.209268 | 4.932034 | 1.664479 |
'''
Return the brightness of an image
Args:
im(numpy): image
Returns:
float, average brightness of an image
'''
im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(im_hsv)
height, weight = v.shape[:2]
total_bright = 0
for i in v:
total_bright = total_bright+sum(i)
return float(total_bright)/(height*weight) | def brightness(im) | Return the brightness of an image
Args:
im(numpy): image
Returns:
float, average brightness of an image | 3.033175 | 2.309552 | 1.313318 |
# 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 = [] | def init(self) | Creates context, when context is ready context_notify_cb is called | 3.821655 | 3.549864 | 1.076564 |
pa_operation_unref(pa_context_get_sink_info_by_name(
context, self.current_sink.encode(), self._sink_info_cb, None)) | def request_update(self, context) | Requests a sink info update (sink_info_cb is called) | 15.479854 | 7.470736 | 2.072065 |
server_info = server_info_p.contents
self.request_update(context) | def server_info_cb(self, context, server_info_p, userdata) | Retrieves the default sink and calls request_update | 6.470315 | 4.091315 | 1.581476 |
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)) | 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) | 4.543924 | 3.822752 | 1.188653 |
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) | def update_cb(self, context, t, idx, userdata) | A sink property changed, calls request_update | 11.881598 | 9.825113 | 1.209309 |
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() | def sink_info_cb(self, context, sink_info_p, _, __) | Updates self.output | 3.060088 | 3.043795 | 1.005353 |
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 | def cycle_interface(self, increment=1) | Cycle through available interfaces in `increment` steps. Sign indicates direction. | 3.356675 | 3.226325 | 1.040402 |
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) | def start(self, seconds=300) | Starts timer.
If timer is already running it will increase remaining time instead.
:param int seconds: Initial time. | 4.553836 | 4.776514 | 0.953381 |
if self.state is TimerState.running:
new_compare = self.compare + seconds
if new_compare > time.time():
self.compare = new_compare | def increase(self, seconds) | Change remainig time value.
:param int seconds: Seconds to add. Negative value substracts from
remaining time. | 6.118583 | 7.228311 | 0.846475 |
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 | def reset(self) | Stop timer and execute ``on_reset`` if overflow occured. | 4.194522 | 2.707352 | 1.549308 |
self.out.write(message + "\n")
self.out.flush() | def write_line(self, message) | Unbuffered printing to stdout. | 4.975848 | 3.52053 | 1.413381 |
try:
line = self.inp.readline().strip()
except KeyboardInterrupt:
raise EOFError()
# i3status sends EOF, or an empty line
if not line:
raise EOFError()
return line | def read_line(self) | Interrupted respecting reader for stdin.
Raises EOFError if the end of stream has been reached | 6.23041 | 5.873477 | 1.06077 |
intervals = [m.interval for m in self.modules if hasattr(m, "interval")]
if len(intervals) > 0:
self.treshold_interval = round(sum(intervals) / len(intervals)) | def compute_treshold_interval(self) | Current method is to compute average from all intervals. | 3.721128 | 3.084003 | 1.20659 |
self.refresh_cond.acquire()
self.refresh_cond.notify()
self.refresh_cond.release() | def async_refresh(self) | Calling this method will send the status line to i3bar immediately
without waiting for timeout (1s by default). | 4.969924 | 3.161588 | 1.571971 |
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() | 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. | 3.960344 | 2.734186 | 1.448455 |
if signo != signal.SIGUSR2:
return
self.stopped = not self.stopped
if self.stopped:
[m.suspend() for m in IntervalModule.managers.values()]
else:
[m.resume() for m in IntervalModule.managers.values()] | def suspend_signal_handler(self, signo, frame) | By default, i3bar sends SIGSTOP to all children when it is not visible (for example, the screen
sleeps or you enter full screen mode). This stops the i3pystatus process and all threads within it.
For some modules, this is not desirable. Thankfully, the i3bar protocol supports setting the "stop_signal"
and "cont_signal" key/value pairs in the header to allow sending a custom signal when these events occur.
Here we use SIGUSR2 for both "stop_signal" and "cont_signal" and maintain a toggle to determine whether
we have just been stopped or continued. When we have been stopped, notify the IntervalModule managers
that they should suspend any module that does not set the keep_alive flag to a truthy value, and when we
have been continued, notify the IntervalModule managers that they can resume execution of all modules. | 3.94277 | 2.866084 | 1.375665 |
for line in self.io.read():
with self.parse_line(line) as j:
yield j | def read(self) | Iterate over all JSON input (Generator) | 10.726652 | 7.371303 | 1.455191 |
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)) | def parse_line(self, line) | Parse a single line of JSON and write modified JSON back. | 6.793827 | 5.907598 | 1.150015 |
event_dict = dict(
title=self.title,
remaining=self.time_remaining,
humanize_remaining=self.humanize_time_remaining,
)
def is_formatter(x):
return inspect.ismethod(x) and hasattr(x, 'formatter') and getattr(x, 'formatter')
for method_name, method in inspect.getmembers(self, is_formatter):
event_dict[method_name] = method()
return event_dict | def formatters(self) | Build a dictionary containing all those key/value pairs that will be exposed to the user via formatters. | 3.470017 | 3.172069 | 1.093929 |
DesktopNotification(
title=event.title,
body="{} until {}!".format(event.time_remaining, event.title),
icon='dialog-information',
urgency=1,
timeout=0,
).display() | def on_click(self, event) | Override this method to do more interesting things with the event. | 10.921949 | 10.046347 | 1.087156 |
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 | 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. | 3.60591 | 3.115206 | 1.157519 |
'''
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() | 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. | 10.966524 | 4.50094 | 2.436496 |
'''
If configured to do so, make an API request to retrieve the forecast
data for the configured/queried weather station, and return the low and
high temperatures. Otherwise, return two empty strings.
'''
no_data = ('', '')
if self.forecast:
query_url = STATION_QUERY_URL % (self.api_key,
'forecast',
self.station_id)
try:
response = self.api_request(query_url)['forecast']
response = response['simpleforecast']['forecastday'][0]
except (KeyError, IndexError, TypeError):
self.logger.error(
'No forecast data found for %s', self.station_id)
self.data['update_error'] = self.update_error
return no_data
unit = 'celsius' if self.units == 'metric' else 'fahrenheit'
low_temp = response.get('low', {}).get(unit, '')
high_temp = response.get('high', {}).get(unit, '')
return low_temp, high_temp
else:
return no_data | def get_forecast(self) | If configured to do so, make an API request to retrieve the forecast
data for the configured/queried weather station, and return the low and
high temperatures. Otherwise, return two empty strings. | 3.439421 | 2.382342 | 1.443714 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.