repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
sixty-north/cosmic-ray | src/cosmic_ray/operators/zero_iteration_for_loop.py | ZeroIterationForLoop.mutate | def mutate(self, node, index):
"""Modify the For loop to evaluate to None"""
assert index == 0
assert isinstance(node, ForStmt)
empty_list = parso.parse(' []')
node.children[3] = empty_list
return node | python | def mutate(self, node, index):
"""Modify the For loop to evaluate to None"""
assert index == 0
assert isinstance(node, ForStmt)
empty_list = parso.parse(' []')
node.children[3] = empty_list
return node | [
"def",
"mutate",
"(",
"self",
",",
"node",
",",
"index",
")",
":",
"assert",
"index",
"==",
"0",
"assert",
"isinstance",
"(",
"node",
",",
"ForStmt",
")",
"empty_list",
"=",
"parso",
".",
"parse",
"(",
"' []'",
")",
"node",
".",
"children",
"[",
"3",... | Modify the For loop to evaluate to None | [
"Modify",
"the",
"For",
"loop",
"to",
"evaluate",
"to",
"None"
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/operators/zero_iteration_for_loop.py#L17-L24 | train | 203,600 |
sixty-north/cosmic-ray | src/cosmic_ray/plugins.py | get_operator | def get_operator(name):
"""Get an operator class from a provider plugin.
Attrs:
name: The name of the operator class.
Returns: The operator *class object* (i.e. not an instance).
"""
sep = name.index('/')
provider_name = name[:sep]
operator_name = name[sep + 1:]
provider = OPERATOR_PROVIDERS[provider_name]
return provider[operator_name] | python | def get_operator(name):
"""Get an operator class from a provider plugin.
Attrs:
name: The name of the operator class.
Returns: The operator *class object* (i.e. not an instance).
"""
sep = name.index('/')
provider_name = name[:sep]
operator_name = name[sep + 1:]
provider = OPERATOR_PROVIDERS[provider_name]
return provider[operator_name] | [
"def",
"get_operator",
"(",
"name",
")",
":",
"sep",
"=",
"name",
".",
"index",
"(",
"'/'",
")",
"provider_name",
"=",
"name",
"[",
":",
"sep",
"]",
"operator_name",
"=",
"name",
"[",
"sep",
"+",
"1",
":",
"]",
"provider",
"=",
"OPERATOR_PROVIDERS",
... | Get an operator class from a provider plugin.
Attrs:
name: The name of the operator class.
Returns: The operator *class object* (i.e. not an instance). | [
"Get",
"an",
"operator",
"class",
"from",
"a",
"provider",
"plugin",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/plugins.py#L27-L40 | train | 203,601 |
sixty-north/cosmic-ray | src/cosmic_ray/plugins.py | operator_names | def operator_names():
"""Get all operator names.
Returns: A sequence of operator names.
"""
return tuple('{}/{}'.format(provider_name, operator_name)
for provider_name, provider in OPERATOR_PROVIDERS.items()
for operator_name in provider) | python | def operator_names():
"""Get all operator names.
Returns: A sequence of operator names.
"""
return tuple('{}/{}'.format(provider_name, operator_name)
for provider_name, provider in OPERATOR_PROVIDERS.items()
for operator_name in provider) | [
"def",
"operator_names",
"(",
")",
":",
"return",
"tuple",
"(",
"'{}/{}'",
".",
"format",
"(",
"provider_name",
",",
"operator_name",
")",
"for",
"provider_name",
",",
"provider",
"in",
"OPERATOR_PROVIDERS",
".",
"items",
"(",
")",
"for",
"operator_name",
"in"... | Get all operator names.
Returns: A sequence of operator names. | [
"Get",
"all",
"operator",
"names",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/plugins.py#L43-L50 | train | 203,602 |
sixty-north/cosmic-ray | src/cosmic_ray/plugins.py | get_execution_engine | def get_execution_engine(name):
"""Get the execution engine by name."""
manager = driver.DriverManager(
namespace='cosmic_ray.execution_engines',
name=name,
invoke_on_load=True,
on_load_failure_callback=_log_extension_loading_failure,
)
return manager.driver | python | def get_execution_engine(name):
"""Get the execution engine by name."""
manager = driver.DriverManager(
namespace='cosmic_ray.execution_engines',
name=name,
invoke_on_load=True,
on_load_failure_callback=_log_extension_loading_failure,
)
return manager.driver | [
"def",
"get_execution_engine",
"(",
"name",
")",
":",
"manager",
"=",
"driver",
".",
"DriverManager",
"(",
"namespace",
"=",
"'cosmic_ray.execution_engines'",
",",
"name",
"=",
"name",
",",
"invoke_on_load",
"=",
"True",
",",
"on_load_failure_callback",
"=",
"_log... | Get the execution engine by name. | [
"Get",
"the",
"execution",
"engine",
"by",
"name",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/plugins.py#L78-L87 | train | 203,603 |
sixty-north/cosmic-ray | src/cosmic_ray/work_db.py | use_db | def use_db(path, mode=WorkDB.Mode.create):
"""
Open a DB in file `path` in mode `mode` as a context manager.
On exiting the context the DB will be automatically closed.
Args:
path: The path to the DB file.
mode: The mode in which to open the DB. See the `Mode` enum for
details.
Raises:
FileNotFoundError: If `mode` is `Mode.open` and `path` does not
exist.
"""
database = WorkDB(path, mode)
try:
yield database
finally:
database.close() | python | def use_db(path, mode=WorkDB.Mode.create):
"""
Open a DB in file `path` in mode `mode` as a context manager.
On exiting the context the DB will be automatically closed.
Args:
path: The path to the DB file.
mode: The mode in which to open the DB. See the `Mode` enum for
details.
Raises:
FileNotFoundError: If `mode` is `Mode.open` and `path` does not
exist.
"""
database = WorkDB(path, mode)
try:
yield database
finally:
database.close() | [
"def",
"use_db",
"(",
"path",
",",
"mode",
"=",
"WorkDB",
".",
"Mode",
".",
"create",
")",
":",
"database",
"=",
"WorkDB",
"(",
"path",
",",
"mode",
")",
"try",
":",
"yield",
"database",
"finally",
":",
"database",
".",
"close",
"(",
")"
] | Open a DB in file `path` in mode `mode` as a context manager.
On exiting the context the DB will be automatically closed.
Args:
path: The path to the DB file.
mode: The mode in which to open the DB. See the `Mode` enum for
details.
Raises:
FileNotFoundError: If `mode` is `Mode.open` and `path` does not
exist. | [
"Open",
"a",
"DB",
"in",
"file",
"path",
"in",
"mode",
"mode",
"as",
"a",
"context",
"manager",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/work_db.py#L265-L284 | train | 203,604 |
sixty-north/cosmic-ray | src/cosmic_ray/work_db.py | WorkDB.work_items | def work_items(self):
"""An iterable of all of WorkItems in the db.
This includes both WorkItems with and without results.
"""
cur = self._conn.cursor()
rows = cur.execute("SELECT * FROM work_items")
for row in rows:
yield _row_to_work_item(row) | python | def work_items(self):
"""An iterable of all of WorkItems in the db.
This includes both WorkItems with and without results.
"""
cur = self._conn.cursor()
rows = cur.execute("SELECT * FROM work_items")
for row in rows:
yield _row_to_work_item(row) | [
"def",
"work_items",
"(",
"self",
")",
":",
"cur",
"=",
"self",
".",
"_conn",
".",
"cursor",
"(",
")",
"rows",
"=",
"cur",
".",
"execute",
"(",
"\"SELECT * FROM work_items\"",
")",
"for",
"row",
"in",
"rows",
":",
"yield",
"_row_to_work_item",
"(",
"row"... | An iterable of all of WorkItems in the db.
This includes both WorkItems with and without results. | [
"An",
"iterable",
"of",
"all",
"of",
"WorkItems",
"in",
"the",
"db",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/work_db.py#L89-L97 | train | 203,605 |
sixty-north/cosmic-ray | src/cosmic_ray/work_db.py | WorkDB.clear | def clear(self):
"""Clear all work items from the session.
This removes any associated results as well.
"""
with self._conn:
self._conn.execute('DELETE FROM results')
self._conn.execute('DELETE FROM work_items') | python | def clear(self):
"""Clear all work items from the session.
This removes any associated results as well.
"""
with self._conn:
self._conn.execute('DELETE FROM results')
self._conn.execute('DELETE FROM work_items') | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"_conn",
":",
"self",
".",
"_conn",
".",
"execute",
"(",
"'DELETE FROM results'",
")",
"self",
".",
"_conn",
".",
"execute",
"(",
"'DELETE FROM work_items'",
")"
] | Clear all work items from the session.
This removes any associated results as well. | [
"Clear",
"all",
"work",
"items",
"from",
"the",
"session",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/work_db.py#L118-L125 | train | 203,606 |
sixty-north/cosmic-ray | src/cosmic_ray/work_db.py | WorkDB.pending_work_items | def pending_work_items(self):
"Iterable of all pending work items."
pending = self._conn.execute(
"SELECT * FROM work_items WHERE job_id NOT IN (SELECT job_id FROM results)"
)
return (_row_to_work_item(p) for p in pending) | python | def pending_work_items(self):
"Iterable of all pending work items."
pending = self._conn.execute(
"SELECT * FROM work_items WHERE job_id NOT IN (SELECT job_id FROM results)"
)
return (_row_to_work_item(p) for p in pending) | [
"def",
"pending_work_items",
"(",
"self",
")",
":",
"pending",
"=",
"self",
".",
"_conn",
".",
"execute",
"(",
"\"SELECT * FROM work_items WHERE job_id NOT IN (SELECT job_id FROM results)\"",
")",
"return",
"(",
"_row_to_work_item",
"(",
"p",
")",
"for",
"p",
"in",
... | Iterable of all pending work items. | [
"Iterable",
"of",
"all",
"pending",
"work",
"items",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/work_db.py#L165-L170 | train | 203,607 |
sixty-north/cosmic-ray | src/cosmic_ray/tools/xml.py | report_xml | def report_xml():
"""cr-xml
Usage: cr-xml <session-file>
Print an XML formatted report of test results for continuos integration systems
"""
arguments = docopt.docopt(report_xml.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
xml_elem = _create_xml_report(db)
xml_elem.write(
sys.stdout.buffer, encoding='utf-8', xml_declaration=True) | python | def report_xml():
"""cr-xml
Usage: cr-xml <session-file>
Print an XML formatted report of test results for continuos integration systems
"""
arguments = docopt.docopt(report_xml.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
xml_elem = _create_xml_report(db)
xml_elem.write(
sys.stdout.buffer, encoding='utf-8', xml_declaration=True) | [
"def",
"report_xml",
"(",
")",
":",
"arguments",
"=",
"docopt",
".",
"docopt",
"(",
"report_xml",
".",
"__doc__",
",",
"version",
"=",
"'cr-rate 1.0'",
")",
"with",
"use_db",
"(",
"arguments",
"[",
"'<session-file>'",
"]",
",",
"WorkDB",
".",
"Mode",
".",
... | cr-xml
Usage: cr-xml <session-file>
Print an XML formatted report of test results for continuos integration systems | [
"cr",
"-",
"xml"
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/tools/xml.py#L12-L23 | train | 203,608 |
sixty-north/cosmic-ray | src/cosmic_ray/commands/execute.py | execute | def execute(db_name):
"""Execute any pending work in the database stored in `db_name`,
recording the results.
This looks for any work in `db_name` which has no results, schedules it to
be executed, and records any results that arrive.
"""
try:
with use_db(db_name, mode=WorkDB.Mode.open) as work_db:
_update_progress(work_db)
config = work_db.get_config()
engine = get_execution_engine(config.execution_engine_name)
def on_task_complete(job_id, work_result):
work_db.set_result(job_id, work_result)
_update_progress(work_db)
log.info("Job %s complete", job_id)
log.info("Beginning execution")
engine(
work_db.pending_work_items,
config,
on_task_complete=on_task_complete)
log.info("Execution finished")
except FileNotFoundError as exc:
raise FileNotFoundError(
str(exc).replace('Requested file', 'Corresponding database',
1)) from exc | python | def execute(db_name):
"""Execute any pending work in the database stored in `db_name`,
recording the results.
This looks for any work in `db_name` which has no results, schedules it to
be executed, and records any results that arrive.
"""
try:
with use_db(db_name, mode=WorkDB.Mode.open) as work_db:
_update_progress(work_db)
config = work_db.get_config()
engine = get_execution_engine(config.execution_engine_name)
def on_task_complete(job_id, work_result):
work_db.set_result(job_id, work_result)
_update_progress(work_db)
log.info("Job %s complete", job_id)
log.info("Beginning execution")
engine(
work_db.pending_work_items,
config,
on_task_complete=on_task_complete)
log.info("Execution finished")
except FileNotFoundError as exc:
raise FileNotFoundError(
str(exc).replace('Requested file', 'Corresponding database',
1)) from exc | [
"def",
"execute",
"(",
"db_name",
")",
":",
"try",
":",
"with",
"use_db",
"(",
"db_name",
",",
"mode",
"=",
"WorkDB",
".",
"Mode",
".",
"open",
")",
"as",
"work_db",
":",
"_update_progress",
"(",
"work_db",
")",
"config",
"=",
"work_db",
".",
"get_conf... | Execute any pending work in the database stored in `db_name`,
recording the results.
This looks for any work in `db_name` which has no results, schedules it to
be executed, and records any results that arrive. | [
"Execute",
"any",
"pending",
"work",
"in",
"the",
"database",
"stored",
"in",
"db_name",
"recording",
"the",
"results",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/commands/execute.py#L33-L61 | train | 203,609 |
sixty-north/cosmic-ray | src/cosmic_ray/ast.py | get_ast | def get_ast(module_path, python_version):
"""Get the AST for the code in a file.
Args:
module_path: pathlib.Path to the file containing the code.
python_version: Python version as a "MAJ.MIN" string.
Returns: The parso parse tree for the code in `module_path`.
"""
with module_path.open(mode='rt', encoding='utf-8') as handle:
source = handle.read()
return parso.parse(source, version=python_version) | python | def get_ast(module_path, python_version):
"""Get the AST for the code in a file.
Args:
module_path: pathlib.Path to the file containing the code.
python_version: Python version as a "MAJ.MIN" string.
Returns: The parso parse tree for the code in `module_path`.
"""
with module_path.open(mode='rt', encoding='utf-8') as handle:
source = handle.read()
return parso.parse(source, version=python_version) | [
"def",
"get_ast",
"(",
"module_path",
",",
"python_version",
")",
":",
"with",
"module_path",
".",
"open",
"(",
"mode",
"=",
"'rt'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"handle",
":",
"source",
"=",
"handle",
".",
"read",
"(",
")",
"return",
"p... | Get the AST for the code in a file.
Args:
module_path: pathlib.Path to the file containing the code.
python_version: Python version as a "MAJ.MIN" string.
Returns: The parso parse tree for the code in `module_path`. | [
"Get",
"the",
"AST",
"for",
"the",
"code",
"in",
"a",
"file",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/ast.py#L31-L43 | train | 203,610 |
sixty-north/cosmic-ray | src/cosmic_ray/ast.py | is_none | def is_none(node):
"Determine if a node is the `None` keyword."
return isinstance(node, parso.python.tree.Keyword) and node.value == 'None' | python | def is_none(node):
"Determine if a node is the `None` keyword."
return isinstance(node, parso.python.tree.Keyword) and node.value == 'None' | [
"def",
"is_none",
"(",
"node",
")",
":",
"return",
"isinstance",
"(",
"node",
",",
"parso",
".",
"python",
".",
"tree",
".",
"Keyword",
")",
"and",
"node",
".",
"value",
"==",
"'None'"
] | Determine if a node is the `None` keyword. | [
"Determine",
"if",
"a",
"node",
"is",
"the",
"None",
"keyword",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/ast.py#L46-L48 | train | 203,611 |
sixty-north/cosmic-ray | src/cosmic_ray/ast.py | Visitor.walk | def walk(self, node):
"Walk a parse tree, calling visit for each node."
node = self.visit(node)
if node is None:
return None
if isinstance(node, parso.tree.BaseNode):
walked = map(self.walk, node.children)
node.children = [child for child in walked if child is not None]
return node | python | def walk(self, node):
"Walk a parse tree, calling visit for each node."
node = self.visit(node)
if node is None:
return None
if isinstance(node, parso.tree.BaseNode):
walked = map(self.walk, node.children)
node.children = [child for child in walked if child is not None]
return node | [
"def",
"walk",
"(",
"self",
",",
"node",
")",
":",
"node",
"=",
"self",
".",
"visit",
"(",
"node",
")",
"if",
"node",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"node",
",",
"parso",
".",
"tree",
".",
"BaseNode",
")",
":",
"wal... | Walk a parse tree, calling visit for each node. | [
"Walk",
"a",
"parse",
"tree",
"calling",
"visit",
"for",
"each",
"node",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/ast.py#L13-L24 | train | 203,612 |
sixty-north/cosmic-ray | src/cosmic_ray/tools/survival_rate.py | format_survival_rate | def format_survival_rate():
"""cr-rate
Usage: cr-rate <session-file>
Calculate the survival rate of a session.
"""
arguments = docopt.docopt(
format_survival_rate.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
rate = survival_rate(db)
print('{:.2f}'.format(rate)) | python | def format_survival_rate():
"""cr-rate
Usage: cr-rate <session-file>
Calculate the survival rate of a session.
"""
arguments = docopt.docopt(
format_survival_rate.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
rate = survival_rate(db)
print('{:.2f}'.format(rate)) | [
"def",
"format_survival_rate",
"(",
")",
":",
"arguments",
"=",
"docopt",
".",
"docopt",
"(",
"format_survival_rate",
".",
"__doc__",
",",
"version",
"=",
"'cr-rate 1.0'",
")",
"with",
"use_db",
"(",
"arguments",
"[",
"'<session-file>'",
"]",
",",
"WorkDB",
".... | cr-rate
Usage: cr-rate <session-file>
Calculate the survival rate of a session. | [
"cr",
"-",
"rate"
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/tools/survival_rate.py#L8-L20 | train | 203,613 |
sixty-north/cosmic-ray | src/cosmic_ray/tools/survival_rate.py | survival_rate | def survival_rate(work_db):
"""Calcuate the survival rate for the results in a WorkDB.
"""
kills = sum(r.is_killed for _, r in work_db.results)
num_results = work_db.num_results
if not num_results:
return 0
return (1 - kills / num_results) * 100 | python | def survival_rate(work_db):
"""Calcuate the survival rate for the results in a WorkDB.
"""
kills = sum(r.is_killed for _, r in work_db.results)
num_results = work_db.num_results
if not num_results:
return 0
return (1 - kills / num_results) * 100 | [
"def",
"survival_rate",
"(",
"work_db",
")",
":",
"kills",
"=",
"sum",
"(",
"r",
".",
"is_killed",
"for",
"_",
",",
"r",
"in",
"work_db",
".",
"results",
")",
"num_results",
"=",
"work_db",
".",
"num_results",
"if",
"not",
"num_results",
":",
"return",
... | Calcuate the survival rate for the results in a WorkDB. | [
"Calcuate",
"the",
"survival",
"rate",
"for",
"the",
"results",
"in",
"a",
"WorkDB",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/tools/survival_rate.py#L23-L32 | train | 203,614 |
sixty-north/cosmic-ray | src/cosmic_ray/tools/html.py | report_html | def report_html():
"""cr-html
Usage: cr-html <session-file>
Print an HTML formatted report of test results.
"""
arguments = docopt.docopt(report_html.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
doc = _generate_html_report(db)
print(doc.getvalue()) | python | def report_html():
"""cr-html
Usage: cr-html <session-file>
Print an HTML formatted report of test results.
"""
arguments = docopt.docopt(report_html.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
doc = _generate_html_report(db)
print(doc.getvalue()) | [
"def",
"report_html",
"(",
")",
":",
"arguments",
"=",
"docopt",
".",
"docopt",
"(",
"report_html",
".",
"__doc__",
",",
"version",
"=",
"'cr-rate 1.0'",
")",
"with",
"use_db",
"(",
"arguments",
"[",
"'<session-file>'",
"]",
",",
"WorkDB",
".",
"Mode",
"."... | cr-html
Usage: cr-html <session-file>
Print an HTML formatted report of test results. | [
"cr",
"-",
"html"
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/tools/html.py#L12-L23 | train | 203,615 |
sixty-north/cosmic-ray | src/cosmic_ray/tools/report.py | report | def report():
"""cr-report
Usage: cr-report [--show-output] [--show-diff] [--show-pending] <session-file>
Print a nicely formatted report of test results and some basic statistics.
options:
--show-output Display output of test executions
--show-diff Display diff of mutants
--show-pending Display results for incomplete tasks
"""
arguments = docopt.docopt(report.__doc__, version='cr-format 0.1')
show_pending = arguments['--show-pending']
show_output = arguments['--show-output']
show_diff = arguments['--show-diff']
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
for work_item, result in db.completed_work_items:
print('{} {} {} {}'.format(work_item.job_id, work_item.module_path,
work_item.operator_name,
work_item.occurrence))
print('worker outcome: {}, test outcome: {}'.format(
result.worker_outcome, result.test_outcome))
if show_output:
print('=== OUTPUT ===')
print(result.output)
print('==============')
if show_diff:
print('=== DIFF ===')
print(result.diff)
print('============')
if show_pending:
for work_item in db.pending_work_items:
print('{} {} {} {}'.format(
work_item.job_id, work_item.module_path,
work_item.operator_name, work_item.occurrence))
num_items = db.num_work_items
num_complete = db.num_results
print('total jobs: {}'.format(num_items))
if num_complete > 0:
print('complete: {} ({:.2f}%)'.format(
num_complete, num_complete / num_items * 100))
print('survival rate: {:.2f}%'.format(survival_rate(db)))
else:
print('no jobs completed') | python | def report():
"""cr-report
Usage: cr-report [--show-output] [--show-diff] [--show-pending] <session-file>
Print a nicely formatted report of test results and some basic statistics.
options:
--show-output Display output of test executions
--show-diff Display diff of mutants
--show-pending Display results for incomplete tasks
"""
arguments = docopt.docopt(report.__doc__, version='cr-format 0.1')
show_pending = arguments['--show-pending']
show_output = arguments['--show-output']
show_diff = arguments['--show-diff']
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
for work_item, result in db.completed_work_items:
print('{} {} {} {}'.format(work_item.job_id, work_item.module_path,
work_item.operator_name,
work_item.occurrence))
print('worker outcome: {}, test outcome: {}'.format(
result.worker_outcome, result.test_outcome))
if show_output:
print('=== OUTPUT ===')
print(result.output)
print('==============')
if show_diff:
print('=== DIFF ===')
print(result.diff)
print('============')
if show_pending:
for work_item in db.pending_work_items:
print('{} {} {} {}'.format(
work_item.job_id, work_item.module_path,
work_item.operator_name, work_item.occurrence))
num_items = db.num_work_items
num_complete = db.num_results
print('total jobs: {}'.format(num_items))
if num_complete > 0:
print('complete: {} ({:.2f}%)'.format(
num_complete, num_complete / num_items * 100))
print('survival rate: {:.2f}%'.format(survival_rate(db)))
else:
print('no jobs completed') | [
"def",
"report",
"(",
")",
":",
"arguments",
"=",
"docopt",
".",
"docopt",
"(",
"report",
".",
"__doc__",
",",
"version",
"=",
"'cr-format 0.1'",
")",
"show_pending",
"=",
"arguments",
"[",
"'--show-pending'",
"]",
"show_output",
"=",
"arguments",
"[",
"'--s... | cr-report
Usage: cr-report [--show-output] [--show-diff] [--show-pending] <session-file>
Print a nicely formatted report of test results and some basic statistics.
options:
--show-output Display output of test executions
--show-diff Display diff of mutants
--show-pending Display results for incomplete tasks | [
"cr",
"-",
"report"
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/tools/report.py#L9-L62 | train | 203,616 |
sixty-north/cosmic-ray | src/cosmic_ray/commands/new_config.py | new_config | def new_config():
"""Prompt user for config variables and generate new config.
Returns: A new ConfigDict.
"""
config = ConfigDict()
config["module-path"] = qprompt.ask_str(
"Top-level module path",
blk=False,
vld=os.path.exists,
hlp=MODULE_PATH_HELP)
python_version = qprompt.ask_str(
'Python version (blank for auto detection)',
vld=_validate_python_version,
hlp=PYTHON_VERSION_HELP)
config['python-version'] = python_version
timeout = qprompt.ask_str(
'Test execution timeout (seconds)',
vld=float,
blk=False,
hlp="The number of seconds to let a test run before terminating it.")
config['timeout'] = float(timeout)
config['excluded-modules'] = []
config["test-command"] = qprompt.ask_str(
"Test command",
blk=False,
hlp=TEST_COMMAND_HELP)
menu = qprompt.Menu()
for at_pos, engine_name in enumerate(execution_engine_names()):
menu.add(str(at_pos), engine_name)
config["execution-engine"] = ConfigDict()
config['execution-engine']['name'] = menu.show(header="Execution engine", returns="desc")
config["cloning"] = ConfigDict()
config['cloning']['method'] = 'copy'
config['cloning']['commands'] = []
return config | python | def new_config():
"""Prompt user for config variables and generate new config.
Returns: A new ConfigDict.
"""
config = ConfigDict()
config["module-path"] = qprompt.ask_str(
"Top-level module path",
blk=False,
vld=os.path.exists,
hlp=MODULE_PATH_HELP)
python_version = qprompt.ask_str(
'Python version (blank for auto detection)',
vld=_validate_python_version,
hlp=PYTHON_VERSION_HELP)
config['python-version'] = python_version
timeout = qprompt.ask_str(
'Test execution timeout (seconds)',
vld=float,
blk=False,
hlp="The number of seconds to let a test run before terminating it.")
config['timeout'] = float(timeout)
config['excluded-modules'] = []
config["test-command"] = qprompt.ask_str(
"Test command",
blk=False,
hlp=TEST_COMMAND_HELP)
menu = qprompt.Menu()
for at_pos, engine_name in enumerate(execution_engine_names()):
menu.add(str(at_pos), engine_name)
config["execution-engine"] = ConfigDict()
config['execution-engine']['name'] = menu.show(header="Execution engine", returns="desc")
config["cloning"] = ConfigDict()
config['cloning']['method'] = 'copy'
config['cloning']['commands'] = []
return config | [
"def",
"new_config",
"(",
")",
":",
"config",
"=",
"ConfigDict",
"(",
")",
"config",
"[",
"\"module-path\"",
"]",
"=",
"qprompt",
".",
"ask_str",
"(",
"\"Top-level module path\"",
",",
"blk",
"=",
"False",
",",
"vld",
"=",
"os",
".",
"path",
".",
"exists... | Prompt user for config variables and generate new config.
Returns: A new ConfigDict. | [
"Prompt",
"user",
"for",
"config",
"variables",
"and",
"generate",
"new",
"config",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/commands/new_config.py#L61-L102 | train | 203,617 |
sixty-north/cosmic-ray | src/cosmic_ray/commands/init.py | init | def init(module_paths, work_db, config):
"""Clear and initialize a work-db with work items.
Any existing data in the work-db will be cleared and replaced with entirely
new work orders. In particular, this means that any results in the db are
removed.
Args:
module_paths: iterable of pathlib.Paths of modules to mutate.
work_db: A `WorkDB` instance into which the work orders will be saved.
config: The configuration for the new session.
"""
operator_names = cosmic_ray.plugins.operator_names()
work_db.set_config(config=config)
work_db.clear()
for module_path in module_paths:
module_ast = get_ast(
module_path, python_version=config.python_version)
for op_name in operator_names:
operator = get_operator(op_name)(config.python_version)
visitor = WorkDBInitVisitor(module_path, op_name, work_db,
operator)
visitor.walk(module_ast)
apply_interceptors(work_db, config.sub('interceptors').get('enabled', ())) | python | def init(module_paths, work_db, config):
"""Clear and initialize a work-db with work items.
Any existing data in the work-db will be cleared and replaced with entirely
new work orders. In particular, this means that any results in the db are
removed.
Args:
module_paths: iterable of pathlib.Paths of modules to mutate.
work_db: A `WorkDB` instance into which the work orders will be saved.
config: The configuration for the new session.
"""
operator_names = cosmic_ray.plugins.operator_names()
work_db.set_config(config=config)
work_db.clear()
for module_path in module_paths:
module_ast = get_ast(
module_path, python_version=config.python_version)
for op_name in operator_names:
operator = get_operator(op_name)(config.python_version)
visitor = WorkDBInitVisitor(module_path, op_name, work_db,
operator)
visitor.walk(module_ast)
apply_interceptors(work_db, config.sub('interceptors').get('enabled', ())) | [
"def",
"init",
"(",
"module_paths",
",",
"work_db",
",",
"config",
")",
":",
"operator_names",
"=",
"cosmic_ray",
".",
"plugins",
".",
"operator_names",
"(",
")",
"work_db",
".",
"set_config",
"(",
"config",
"=",
"config",
")",
"work_db",
".",
"clear",
"("... | Clear and initialize a work-db with work items.
Any existing data in the work-db will be cleared and replaced with entirely
new work orders. In particular, this means that any results in the db are
removed.
Args:
module_paths: iterable of pathlib.Paths of modules to mutate.
work_db: A `WorkDB` instance into which the work orders will be saved.
config: The configuration for the new session. | [
"Clear",
"and",
"initialize",
"a",
"work",
"-",
"db",
"with",
"work",
"items",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/commands/init.py#L47-L74 | train | 203,618 |
sixty-north/cosmic-ray | src/cosmic_ray/commands/init.py | apply_interceptors | def apply_interceptors(work_db, enabled_interceptors):
"""Apply each registered interceptor to the WorkDB."""
names = (name for name in interceptor_names() if name in enabled_interceptors)
for name in names:
interceptor = get_interceptor(name)
interceptor(work_db) | python | def apply_interceptors(work_db, enabled_interceptors):
"""Apply each registered interceptor to the WorkDB."""
names = (name for name in interceptor_names() if name in enabled_interceptors)
for name in names:
interceptor = get_interceptor(name)
interceptor(work_db) | [
"def",
"apply_interceptors",
"(",
"work_db",
",",
"enabled_interceptors",
")",
":",
"names",
"=",
"(",
"name",
"for",
"name",
"in",
"interceptor_names",
"(",
")",
"if",
"name",
"in",
"enabled_interceptors",
")",
"for",
"name",
"in",
"names",
":",
"interceptor"... | Apply each registered interceptor to the WorkDB. | [
"Apply",
"each",
"registered",
"interceptor",
"to",
"the",
"WorkDB",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/commands/init.py#L77-L82 | train | 203,619 |
sixty-north/cosmic-ray | src/cosmic_ray/operators/comparison_operator_replacement.py | _allowed | def _allowed(to_op, from_op, rhs):
"Determine if a mutation from `from_op` to `to_op` is allowed given a particular `rhs` node."
if is_none(rhs):
return to_op in _RHS_IS_NONE_OPS.get(from_op, ())
if is_number(rhs):
return to_op in _RHS_IS_INTEGER_OPS
return True | python | def _allowed(to_op, from_op, rhs):
"Determine if a mutation from `from_op` to `to_op` is allowed given a particular `rhs` node."
if is_none(rhs):
return to_op in _RHS_IS_NONE_OPS.get(from_op, ())
if is_number(rhs):
return to_op in _RHS_IS_INTEGER_OPS
return True | [
"def",
"_allowed",
"(",
"to_op",
",",
"from_op",
",",
"rhs",
")",
":",
"if",
"is_none",
"(",
"rhs",
")",
":",
"return",
"to_op",
"in",
"_RHS_IS_NONE_OPS",
".",
"get",
"(",
"from_op",
",",
"(",
")",
")",
"if",
"is_number",
"(",
"rhs",
")",
":",
"ret... | Determine if a mutation from `from_op` to `to_op` is allowed given a particular `rhs` node. | [
"Determine",
"if",
"a",
"mutation",
"from",
"from_op",
"to",
"to_op",
"is",
"allowed",
"given",
"a",
"particular",
"rhs",
"node",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/operators/comparison_operator_replacement.py#L97-L105 | train | 203,620 |
sixty-north/cosmic-ray | src/cosmic_ray/worker.py | worker | def worker(module_path,
python_version,
operator_name,
occurrence,
test_command,
timeout):
"""Mutate the OCCURRENCE-th site for OPERATOR_NAME in MODULE_PATH, run the
tests, and report the results.
This is fundamentally the single-mutation-and-test-run process
implementation.
There are three high-level ways that a worker can finish. First, it could
fail exceptionally, meaning that some uncaught exception made its way from
some part of the operation to terminate the function. This function will
intercept all exceptions and return it in a non-exceptional structure.
Second, the mutation testing machinery may determine that there is no
OCCURENCE-th instance for OPERATOR_NAME in the module under test. In this
case there is no way to report a test result (i.e. killed, survived, or
incompetent) so a special value is returned indicating that no mutation is
possible.
Finally, and hopefully normally, the worker will find that it can run a
test. It will do so and report back the result - killed, survived, or
incompetent - in a structured way.
Args:
module_name: The path to the module to mutate
python_version: The version of Python to use when interpreting the code in `module_path`.
A string of the form "MAJOR.MINOR", e.g. "3.6" for Python 3.6.x.
operator_name: The name of the operator plugin to use
occurrence: The occurrence of the operator to apply
test_command: The command to execute to run the tests
timeout: The maximum amount of time (seconds) to let the tests run
Returns: A WorkResult
Raises: This will generally not raise any exceptions. Rather, exceptions
will be reported using the 'exception' result-type in the return value.
"""
try:
operator_class = cosmic_ray.plugins.get_operator(operator_name)
operator = operator_class(python_version)
with cosmic_ray.mutating.use_mutation(module_path, operator,
occurrence) as (original_code,
mutated_code):
if mutated_code is None:
return WorkResult(worker_outcome=WorkerOutcome.NO_TEST)
test_outcome, output = run_tests(test_command, timeout)
diff = _make_diff(original_code, mutated_code, module_path)
return WorkResult(
output=output,
diff='\n'.join(diff),
test_outcome=test_outcome,
worker_outcome=WorkerOutcome.NORMAL)
except Exception: # noqa # pylint: disable=broad-except
return WorkResult(
output=traceback.format_exc(),
test_outcome=TestOutcome.INCOMPETENT,
worker_outcome=WorkerOutcome.EXCEPTION) | python | def worker(module_path,
python_version,
operator_name,
occurrence,
test_command,
timeout):
"""Mutate the OCCURRENCE-th site for OPERATOR_NAME in MODULE_PATH, run the
tests, and report the results.
This is fundamentally the single-mutation-and-test-run process
implementation.
There are three high-level ways that a worker can finish. First, it could
fail exceptionally, meaning that some uncaught exception made its way from
some part of the operation to terminate the function. This function will
intercept all exceptions and return it in a non-exceptional structure.
Second, the mutation testing machinery may determine that there is no
OCCURENCE-th instance for OPERATOR_NAME in the module under test. In this
case there is no way to report a test result (i.e. killed, survived, or
incompetent) so a special value is returned indicating that no mutation is
possible.
Finally, and hopefully normally, the worker will find that it can run a
test. It will do so and report back the result - killed, survived, or
incompetent - in a structured way.
Args:
module_name: The path to the module to mutate
python_version: The version of Python to use when interpreting the code in `module_path`.
A string of the form "MAJOR.MINOR", e.g. "3.6" for Python 3.6.x.
operator_name: The name of the operator plugin to use
occurrence: The occurrence of the operator to apply
test_command: The command to execute to run the tests
timeout: The maximum amount of time (seconds) to let the tests run
Returns: A WorkResult
Raises: This will generally not raise any exceptions. Rather, exceptions
will be reported using the 'exception' result-type in the return value.
"""
try:
operator_class = cosmic_ray.plugins.get_operator(operator_name)
operator = operator_class(python_version)
with cosmic_ray.mutating.use_mutation(module_path, operator,
occurrence) as (original_code,
mutated_code):
if mutated_code is None:
return WorkResult(worker_outcome=WorkerOutcome.NO_TEST)
test_outcome, output = run_tests(test_command, timeout)
diff = _make_diff(original_code, mutated_code, module_path)
return WorkResult(
output=output,
diff='\n'.join(diff),
test_outcome=test_outcome,
worker_outcome=WorkerOutcome.NORMAL)
except Exception: # noqa # pylint: disable=broad-except
return WorkResult(
output=traceback.format_exc(),
test_outcome=TestOutcome.INCOMPETENT,
worker_outcome=WorkerOutcome.EXCEPTION) | [
"def",
"worker",
"(",
"module_path",
",",
"python_version",
",",
"operator_name",
",",
"occurrence",
",",
"test_command",
",",
"timeout",
")",
":",
"try",
":",
"operator_class",
"=",
"cosmic_ray",
".",
"plugins",
".",
"get_operator",
"(",
"operator_name",
")",
... | Mutate the OCCURRENCE-th site for OPERATOR_NAME in MODULE_PATH, run the
tests, and report the results.
This is fundamentally the single-mutation-and-test-run process
implementation.
There are three high-level ways that a worker can finish. First, it could
fail exceptionally, meaning that some uncaught exception made its way from
some part of the operation to terminate the function. This function will
intercept all exceptions and return it in a non-exceptional structure.
Second, the mutation testing machinery may determine that there is no
OCCURENCE-th instance for OPERATOR_NAME in the module under test. In this
case there is no way to report a test result (i.e. killed, survived, or
incompetent) so a special value is returned indicating that no mutation is
possible.
Finally, and hopefully normally, the worker will find that it can run a
test. It will do so and report back the result - killed, survived, or
incompetent - in a structured way.
Args:
module_name: The path to the module to mutate
python_version: The version of Python to use when interpreting the code in `module_path`.
A string of the form "MAJOR.MINOR", e.g. "3.6" for Python 3.6.x.
operator_name: The name of the operator plugin to use
occurrence: The occurrence of the operator to apply
test_command: The command to execute to run the tests
timeout: The maximum amount of time (seconds) to let the tests run
Returns: A WorkResult
Raises: This will generally not raise any exceptions. Rather, exceptions
will be reported using the 'exception' result-type in the return value. | [
"Mutate",
"the",
"OCCURRENCE",
"-",
"th",
"site",
"for",
"OPERATOR_NAME",
"in",
"MODULE_PATH",
"run",
"the",
"tests",
"and",
"report",
"the",
"results",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/worker.py#L14-L80 | train | 203,621 |
sixty-north/cosmic-ray | src/cosmic_ray/progress.py | report_progress | def report_progress(stream=None):
"""Report progress from any currently installed reporters.
Args:
stream: The text stream (default: sys.stderr) to which
progress will be reported.
"""
if stream is None:
stream = sys.stderr
for reporter in _reporters:
reporter(stream) | python | def report_progress(stream=None):
"""Report progress from any currently installed reporters.
Args:
stream: The text stream (default: sys.stderr) to which
progress will be reported.
"""
if stream is None:
stream = sys.stderr
for reporter in _reporters:
reporter(stream) | [
"def",
"report_progress",
"(",
"stream",
"=",
"None",
")",
":",
"if",
"stream",
"is",
"None",
":",
"stream",
"=",
"sys",
".",
"stderr",
"for",
"reporter",
"in",
"_reporters",
":",
"reporter",
"(",
"stream",
")"
] | Report progress from any currently installed reporters.
Args:
stream: The text stream (default: sys.stderr) to which
progress will be reported. | [
"Report",
"progress",
"from",
"any",
"currently",
"installed",
"reporters",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/progress.py#L58-L68 | train | 203,622 |
sixty-north/cosmic-ray | src/cosmic_ray/progress.py | reports_progress | def reports_progress(reporter):
"""A decorator factory to mark functions which report progress.
Args:
reporter: A zero-argument callable to report progress.
The callable provided should have the means to both
retrieve and display current progress information.
"""
def decorator(func): # pylint: disable=missing-docstring
@wraps(func)
def wrapper(*args, **kwargs): # pylint: disable=missing-docstring
with progress_reporter(reporter):
return func(*args, **kwargs)
return wrapper
return decorator | python | def reports_progress(reporter):
"""A decorator factory to mark functions which report progress.
Args:
reporter: A zero-argument callable to report progress.
The callable provided should have the means to both
retrieve and display current progress information.
"""
def decorator(func): # pylint: disable=missing-docstring
@wraps(func)
def wrapper(*args, **kwargs): # pylint: disable=missing-docstring
with progress_reporter(reporter):
return func(*args, **kwargs)
return wrapper
return decorator | [
"def",
"reports_progress",
"(",
"reporter",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"# pylint: disable=missing-docstring",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=... | A decorator factory to mark functions which report progress.
Args:
reporter: A zero-argument callable to report progress.
The callable provided should have the means to both
retrieve and display current progress information. | [
"A",
"decorator",
"factory",
"to",
"mark",
"functions",
"which",
"report",
"progress",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/progress.py#L85-L102 | train | 203,623 |
sixty-north/cosmic-ray | scripts/cosmic_ray_tooling.py | tags | 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) | python | 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) | [
"def",
"tags",
"(",
")",
":",
"result",
"=",
"[",
"t",
".",
"decode",
"(",
"'ascii'",
")",
"for",
"t",
"in",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'tag'",
"]",
")",
".",
"split",
"(",
"b\"\\n\"",
")",
"]",
"assert",
"len",
"... | Get a set of tags for the current git repo. | [
"Get",
"a",
"set",
"of",
"tags",
"for",
"the",
"current",
"git",
"repo",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/scripts/cosmic_ray_tooling.py#L19-L25 | train | 203,624 |
sixty-north/cosmic-ray | scripts/cosmic_ray_tooling.py | create_tag_and_push | 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'
]) | python | 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'
]) | [
"def",
"create_tag_and_push",
"(",
"version",
")",
":",
"assert",
"version",
"not",
"in",
"tags",
"(",
")",
"git",
"(",
"'config'",
",",
"'user.name'",
",",
"'Travis CI on behalf of Austin Bingham'",
")",
"git",
"(",
"'config'",
",",
"'user.email'",
",",
"'austi... | Create a git tag for `version` and push it to origin. | [
"Create",
"a",
"git",
"tag",
"for",
"version",
"and",
"push",
"it",
"to",
"origin",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/scripts/cosmic_ray_tooling.py#L28-L46 | train | 203,625 |
sixty-north/cosmic-ray | plugins/execution-engines/celery4/cosmic_ray_celery4_engine/worker.py | worker_task | 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 | python | 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 | [
"def",
"worker_task",
"(",
"work_item",
",",
"config",
")",
":",
"global",
"_workspace",
"_ensure_workspace",
"(",
"config",
")",
"result",
"=",
"worker",
"(",
"work_item",
".",
"module_path",
",",
"config",
".",
"python_version",
",",
"work_item",
".",
"opera... | 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 | [
"The",
"celery",
"task",
"which",
"performs",
"a",
"single",
"mutation",
"and",
"runs",
"a",
"test",
"suite",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/plugins/execution-engines/celery4/cosmic_ray_celery4_engine/worker.py#L25-L48 | train | 203,626 |
sixty-north/cosmic-ray | plugins/execution-engines/celery4/cosmic_ray_celery4_engine/worker.py | execute_work_items | 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
) | python | 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
) | [
"def",
"execute_work_items",
"(",
"work_items",
",",
"config",
")",
":",
"return",
"celery",
".",
"group",
"(",
"worker_task",
".",
"s",
"(",
"work_item",
",",
"config",
")",
"for",
"work_item",
"in",
"work_items",
")"
] | 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. | [
"Execute",
"a",
"suite",
"of",
"tests",
"for",
"a",
"given",
"set",
"of",
"work",
"items",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/plugins/execution-engines/celery4/cosmic_ray_celery4_engine/worker.py#L66-L78 | train | 203,627 |
sixty-north/cosmic-ray | src/cosmic_ray/cloning.py | cloned_workspace | 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() | python | 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() | [
"def",
"cloned_workspace",
"(",
"clone_config",
",",
"chdir",
"=",
"True",
")",
":",
"workspace",
"=",
"ClonedWorkspace",
"(",
"clone_config",
")",
"original_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"chdir",
":",
"os",
".",
"chdir",
"(",
"workspace"... | 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. | [
"Create",
"a",
"cloned",
"workspace",
"and",
"yield",
"it",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/cloning.py#L19-L41 | train | 203,628 |
sixty-north/cosmic-ray | src/cosmic_ray/cloning.py | clone_with_git | 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) | python | 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) | [
"def",
"clone_with_git",
"(",
"repo_uri",
",",
"dest_path",
")",
":",
"log",
".",
"info",
"(",
"'Cloning git repo %s to %s'",
",",
"repo_uri",
",",
"dest_path",
")",
"git",
".",
"Repo",
".",
"clone_from",
"(",
"repo_uri",
",",
"dest_path",
",",
"depth",
"=",... | 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. | [
"Create",
"a",
"clone",
"by",
"cloning",
"a",
"git",
"repository",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/cloning.py#L117-L125 | train | 203,629 |
sixty-north/cosmic-ray | src/cosmic_ray/cloning.py | clone_with_copy | 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) | python | 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) | [
"def",
"clone_with_copy",
"(",
"src_path",
",",
"dest_path",
")",
":",
"log",
".",
"info",
"(",
"'Cloning directory tree %s to %s'",
",",
"src_path",
",",
"dest_path",
")",
"shutil",
".",
"copytree",
"(",
"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. | [
"Clone",
"a",
"directory",
"try",
"by",
"copying",
"it",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/cloning.py#L128-L136 | train | 203,630 |
sixty-north/cosmic-ray | src/cosmic_ray/cloning.py | _build_env | 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 | python | 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 | [
"def",
"_build_env",
"(",
"venv_dir",
")",
":",
"# 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... | 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. | [
"Create",
"a",
"new",
"virtual",
"environment",
"in",
"venv_dir",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/cloning.py#L139-L162 | train | 203,631 |
sixty-north/cosmic-ray | src/cosmic_ray/cloning.py | ClonedWorkspace.replace_variables | 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) | python | 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) | [
"def",
"replace_variables",
"(",
"self",
",",
"text",
")",
":",
"variables",
"=",
"{",
"'python-executable'",
":",
"str",
"(",
"self",
".",
"_venv_path",
"/",
"'bin'",
"/",
"'python'",
")",
"}",
"return",
"text",
".",
"format",
"(",
"*",
"*",
"variables"... | 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. | [
"Replace",
"variable",
"placeholders",
"in",
"text",
"with",
"values",
"from",
"the",
"virtual",
"env",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/cloning.py#L95-L109 | train | 203,632 |
sixty-north/cosmic-ray | src/cosmic_ray/cloning.py | ClonedWorkspace.cleanup | def cleanup(self):
"Remove the directory containin the clone and virtual environment."
log.info('Removing temp dir %s', self._tempdir.name)
self._tempdir.cleanup() | python | def cleanup(self):
"Remove the directory containin the clone and virtual environment."
log.info('Removing temp dir %s', self._tempdir.name)
self._tempdir.cleanup() | [
"def",
"cleanup",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Removing temp dir %s'",
",",
"self",
".",
"_tempdir",
".",
"name",
")",
"self",
".",
"_tempdir",
".",
"cleanup",
"(",
")"
] | Remove the directory containin the clone and virtual environment. | [
"Remove",
"the",
"directory",
"containin",
"the",
"clone",
"and",
"virtual",
"environment",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/cloning.py#L111-L114 | train | 203,633 |
sixty-north/cosmic-ray | src/cosmic_ray/work_item.py | WorkResult.as_dict | 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,
} | python | 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,
} | [
"def",
"as_dict",
"(",
"self",
")",
":",
"return",
"{",
"'output'",
":",
"self",
".",
"output",
",",
"'test_outcome'",
":",
"self",
".",
"test_outcome",
",",
"'worker_outcome'",
":",
"self",
".",
"worker_outcome",
",",
"'diff'",
":",
"self",
".",
"diff",
... | Get the WorkResult as a dict. | [
"Get",
"the",
"WorkResult",
"as",
"a",
"dict",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/work_item.py#L67-L74 | train | 203,634 |
sixty-north/cosmic-ray | src/cosmic_ray/work_item.py | WorkItem.as_dict | 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,
} | python | 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,
} | [
"def",
"as_dict",
"(",
"self",
")",
":",
"return",
"{",
"'module_path'",
":",
"str",
"(",
"self",
".",
"module_path",
")",
",",
"'operator_name'",
":",
"self",
".",
"operator_name",
",",
"'occurrence'",
":",
"self",
".",
"occurrence",
",",
"'start_pos'",
"... | Get fields as a dict. | [
"Get",
"fields",
"as",
"a",
"dict",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/work_item.py#L145-L155 | train | 203,635 |
sixty-north/cosmic-ray | src/cosmic_ray/interceptors/spor.py | intercept | 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,
),
) | python | 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,
),
) | [
"def",
"intercept",
"(",
"work_db",
")",
":",
"@",
"lru_cache",
"(",
")",
"def",
"file_contents",
"(",
"file_path",
")",
":",
"\"A simple cache of file contents.\"",
"with",
"file_path",
".",
"open",
"(",
"mode",
"=",
"\"rt\"",
")",
"as",
"handle",
":",
"ret... | 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. | [
"Look",
"for",
"WorkItems",
"in",
"work_db",
"that",
"should",
"not",
"be",
"mutated",
"due",
"to",
"spor",
"metadata",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/interceptors/spor.py#L14-L63 | train | 203,636 |
sixty-north/cosmic-ray | src/cosmic_ray/interceptors/spor.py | _line_and_col_to_offset | 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)) | python | 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)) | [
"def",
"_line_and_col_to_offset",
"(",
"lines",
",",
"line",
",",
"col",
")",
":",
"offset",
"=",
"0",
"for",
"index",
",",
"contents",
"in",
"enumerate",
"(",
"lines",
",",
"1",
")",
":",
"if",
"index",
"==",
"line",
":",
"return",
"offset",
"+",
"c... | 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. | [
"Figure",
"out",
"the",
"offset",
"into",
"a",
"file",
"for",
"a",
"particular",
"line",
"and",
"col",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/interceptors/spor.py#L66-L90 | train | 203,637 |
sixty-north/cosmic-ray | src/cosmic_ray/interceptors/spor.py | _item_in_context | 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) | python | 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) | [
"def",
"_item_in_context",
"(",
"lines",
",",
"item",
",",
"context",
")",
":",
"start_offset",
"=",
"_line_and_col_to_offset",
"(",
"lines",
",",
"item",
".",
"start_pos",
"[",
"0",
"]",
",",
"item",
".",
"start_pos",
"[",
"1",
"]",
")",
"stop_offset",
... | 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. | [
"Determines",
"if",
"a",
"WorkItem",
"falls",
"within",
"an",
"anchor",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/interceptors/spor.py#L93-L105 | train | 203,638 |
sixty-north/cosmic-ray | src/cosmic_ray/mutating.py | use_mutation | 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() | python | 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() | [
"def",
"use_mutation",
"(",
"module_path",
",",
"operator",
",",
"occurrence",
")",
":",
"original_code",
",",
"mutated_code",
"=",
"apply_mutation",
"(",
"module_path",
",",
"operator",
",",
"occurrence",
")",
"try",
":",
"yield",
"original_code",
",",
"mutated... | 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`. | [
"A",
"context",
"manager",
"that",
"applies",
"a",
"mutation",
"for",
"the",
"duration",
"of",
"a",
"with",
"-",
"block",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/mutating.py#L9-L30 | train | 203,639 |
sixty-north/cosmic-ray | src/cosmic_ray/mutating.py | apply_mutation | 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 | python | 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 | [
"def",
"apply_mutation",
"(",
"module_path",
",",
"operator",
",",
"occurrence",
")",
":",
"module_ast",
"=",
"get_ast",
"(",
"module_path",
",",
"python_version",
"=",
"operator",
".",
"python_version",
")",
"original_code",
"=",
"module_ast",
".",
"get_code",
... | 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`. | [
"Apply",
"a",
"specific",
"mutation",
"to",
"a",
"file",
"on",
"disk",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/mutating.py#L33-L56 | train | 203,640 |
isislovecruft/python-gnupg | setup.py | get_requirements | 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 | python | 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 | [
"def",
"get_requirements",
"(",
")",
":",
"requirements_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'requirements.txt'",
")",
"requirements",
"=",
"[",
"]",
"links",
"=",
"[",
"]",
"try",
":",
"with",
"open",
... | 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. | [
"Extract",
"the",
"list",
"of",
"requirements",
"from",
"our",
"requirements",
".",
"txt",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/setup.py#L55-L93 | train | 203,641 |
isislovecruft/python-gnupg | examples/make-8192-bit-key.py | createBatchfile | 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 | python | 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 | [
"def",
"createBatchfile",
"(",
"keyparams",
"=",
"allparams",
")",
":",
"useparams",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"keyparams",
".",
"items",
"(",
")",
":",
"if",
"value",
":",
"useparams",
".",
"update",
"(",
"{",
"key",
":",
"val... | 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. | [
"Create",
"the",
"batchfile",
"for",
"our",
"new",
"key",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/examples/make-8192-bit-key.py#L124-L140 | train | 203,642 |
isislovecruft/python-gnupg | examples/make-8192-bit-key.py | exportNewKey | 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) | python | 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) | [
"def",
"exportNewKey",
"(",
"fingerprint",
")",
":",
"log",
".",
"info",
"(",
"\"Exporting key: %s\"",
"%",
"fingerprint",
")",
"keyfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"gpg",
".",
"homedir",
",",
"fingerprint",
"+",
"'-8192-bit-key'",
")",
"+",
... | Export the new keys into .asc files.
:param str fingerprint: A full key fingerprint. | [
"Export",
"the",
"new",
"keys",
"into",
".",
"asc",
"files",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/examples/make-8192-bit-key.py#L178-L197 | train | 203,643 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | _check_keyserver | 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 | python | 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 | [
"def",
"_check_keyserver",
"(",
"location",
")",
":",
"protocols",
"=",
"[",
"'hkp://'",
",",
"'hkps://'",
",",
"'http://'",
",",
"'https://'",
",",
"'ldap://'",
",",
"'mailto:'",
"]",
"## xxx feels like i´m forgetting one...",
"for",
"proto",
"in",
"protocols",
"... | 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. | [
"Check",
"that",
"a",
"given",
"keyserver",
"is",
"a",
"known",
"protocol",
"and",
"does",
"not",
"contain",
"shell",
"escape",
"characters",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L49-L75 | train | 203,644 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | _check_preferences | 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 | python | 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 | [
"def",
"_check_preferences",
"(",
"prefs",
",",
"pref_type",
"=",
"None",
")",
":",
"if",
"prefs",
"is",
"None",
":",
"return",
"cipher",
"=",
"frozenset",
"(",
"[",
"'AES256'",
",",
"'AES192'",
",",
"'AES128'",
",",
"'CAMELLIA256'",
",",
"'CAMELLIA192'",
... | 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 | [
"Check",
"cipher",
"digest",
"and",
"compression",
"preference",
"settings",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L77-L125 | train | 203,645 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | _hyphenate | 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 | python | 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 | [
"def",
"_hyphenate",
"(",
"input",
",",
"add_prefix",
"=",
"False",
")",
":",
"ret",
"=",
"'--'",
"if",
"add_prefix",
"else",
"''",
"ret",
"+=",
"input",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"return",
"ret"
] | 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. | [
"Change",
"underscores",
"to",
"hyphens",
"so",
"that",
"object",
"attributes",
"can",
"be",
"easily",
"tranlated",
"to",
"GPG",
"option",
"names",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L143-L154 | train | 203,646 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | _is_allowed | 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 | python | 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 | [
"def",
"_is_allowed",
"(",
"input",
")",
":",
"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 tha... | 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. | [
"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",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L156-L221 | train | 203,647 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | _is_string | 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) | python | 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) | [
"def",
"_is_string",
"(",
"thing",
")",
":",
"if",
"_util",
".",
"_py3k",
":",
"return",
"isinstance",
"(",
"thing",
",",
"str",
")",
"else",
":",
"return",
"isinstance",
"(",
"thing",
",",
"basestring",
")"
] | 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. | [
"Python",
"character",
"arrays",
"are",
"a",
"mess",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L233-L244 | train | 203,648 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | _sanitise_list | 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 | python | 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 | [
"def",
"_sanitise_list",
"(",
"arg_list",
")",
":",
"if",
"isinstance",
"(",
"arg_list",
",",
"list",
")",
":",
"for",
"arg",
"in",
"arg_list",
":",
"safe_arg",
"=",
"_sanitise",
"(",
"arg",
")",
"if",
"safe_arg",
"!=",
"\"\"",
":",
"yield",
"safe_arg"
] | 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. | [
"A",
"generator",
"for",
"iterating",
"through",
"a",
"list",
"of",
"gpg",
"options",
"and",
"sanitising",
"them",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L460-L474 | train | 203,649 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | _get_options_group | 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] | python | 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] | [
"def",
"_get_options_group",
"(",
"group",
"=",
"None",
")",
":",
"#: These expect a hexidecimal keyid as their argument, and can be parsed",
"#: with :func:`_is_hex`.",
"hex_options",
"=",
"frozenset",
"(",
"[",
"'--check-sigs'",
",",
"'--default-key'",
",",
"'--default-recipi... | Get a specific group of options which are allowed. | [
"Get",
"a",
"specific",
"group",
"of",
"options",
"which",
"are",
"allowed",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L476-L610 | train | 203,650 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | _get_all_gnupg_options | 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 | python | 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 | [
"def",
"_get_all_gnupg_options",
"(",
")",
":",
"three_hundred_eighteen",
"=",
"(",
"\"\"\"\n--allow-freeform-uid --multifile\n--allow-multiple-messages --no\n--allow-multisig-verification --no-allow-freeform-uid\n--allow-non-selfsigned-uid --no-allow-multiple-message... | 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`` | [
"Get",
"all",
"GnuPG",
"options",
"and",
"flags",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L612-L807 | train | 203,651 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | nodata | 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 | python | 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 | [
"def",
"nodata",
"(",
"status_code",
")",
":",
"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'",
":",
"'Sig... | Translate NODATA status codes from GnuPG to messages. | [
"Translate",
"NODATA",
"status",
"codes",
"from",
"GnuPG",
"to",
"messages",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L809-L818 | train | 203,652 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | progress | 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 | python | 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 | [
"def",
"progress",
"(",
"status_code",
")",
":",
"lookup",
"=",
"{",
"'pk_dsa'",
":",
"'DSA key generation'",
",",
"'pk_elg'",
":",
"'Elgamal key generation'",
",",
"'primegen'",
":",
"'Prime generation'",
",",
"'need_entropy'",
":",
"'Waiting for new entropy in the RNG... | Translate PROGRESS status codes from GnuPG to messages. | [
"Translate",
"PROGRESS",
"status",
"codes",
"from",
"GnuPG",
"to",
"messages",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L820-L833 | train | 203,653 |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | KeyExpirationInterface._clean_key_expiration_option | 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) | python | 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) | [
"def",
"_clean_key_expiration_option",
"(",
"self",
")",
":",
"allowed_entry",
"=",
"re",
".",
"findall",
"(",
"'^(\\d+)(|w|m|y)$'",
",",
"self",
".",
"_expiration_time",
")",
"if",
"not",
"allowed_entry",
":",
"raise",
"UsageError",
"(",
"\"Key expiration option: %... | validates the expiration option supplied | [
"validates",
"the",
"expiration",
"option",
"supplied"
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L844-L848 | train | 203,654 |
isislovecruft/python-gnupg | pretty_bad_protocol/_trust.py | _create_trustdb | 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) | python | 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) | [
"def",
"_create_trustdb",
"(",
"cls",
")",
":",
"trustdb",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"homedir",
",",
"'trustdb.gpg'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"trustdb",
")",
":",
"log",
".",
"info",
"(",... | Create the trustdb file in our homedir, if it doesn't exist. | [
"Create",
"the",
"trustdb",
"file",
"in",
"our",
"homedir",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_trust.py#L33-L40 | train | 203,655 |
isislovecruft/python-gnupg | pretty_bad_protocol/_trust.py | export_ownertrust | 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() | python | 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() | [
"def",
"export_ownertrust",
"(",
"cls",
",",
"trustdb",
"=",
"None",
")",
":",
"if",
"trustdb",
"is",
"None",
":",
"trustdb",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"homedir",
",",
"'trustdb.gpg'",
")",
"try",
":",
"os",
".",
"rename",... | 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. | [
"Export",
"ownertrust",
"to",
"a",
"trustdb",
"file",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_trust.py#L42-L63 | train | 203,656 |
isislovecruft/python-gnupg | pretty_bad_protocol/_trust.py | import_ownertrust | 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() | python | 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() | [
"def",
"import_ownertrust",
"(",
"cls",
",",
"trustdb",
"=",
"None",
")",
":",
"if",
"trustdb",
"is",
"None",
":",
"trustdb",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"homedir",
",",
"'trustdb.gpg'",
")",
"import_proc",
"=",
"cls",
".",
... | 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. | [
"Import",
"ownertrust",
"from",
"a",
"trustdb",
"file",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_trust.py#L65-L83 | train | 203,657 |
isislovecruft/python-gnupg | pretty_bad_protocol/_trust.py | fix_trustdb | 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() | python | 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() | [
"def",
"fix_trustdb",
"(",
"cls",
",",
"trustdb",
"=",
"None",
")",
":",
"if",
"trustdb",
"is",
"None",
":",
"trustdb",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"homedir",
",",
"'trustdb.gpg'",
")",
"export_proc",
"=",
"cls",
".",
"_open... | 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. | [
"Attempt",
"to",
"repair",
"a",
"broken",
"trustdb",
".",
"gpg",
"file",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_trust.py#L85-L112 | train | 203,658 |
isislovecruft/python-gnupg | pretty_bad_protocol/_logger.py | status | 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) | python | 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) | [
"def",
"status",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"isEnabledFor",
"(",
"GNUPG_STATUS_LEVEL",
")",
":",
"self",
".",
"_log",
"(",
"GNUPG_STATUS_LEVEL",
",",
"message",
",",
"args",
",",... | LogRecord for GnuPG internal status messages. | [
"LogRecord",
"for",
"GnuPG",
"internal",
"status",
"messages",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_logger.py#L42-L45 | train | 203,659 |
isislovecruft/python-gnupg | pretty_bad_protocol/_logger.py | create_logger | 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 | python | 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 | [
"def",
"create_logger",
"(",
"level",
"=",
"logging",
".",
"NOTSET",
")",
":",
"_test",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'pretty_bad_protocol'",
")",
",",
"'test'",
... | 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.
==== ======== ======================================== | [
"Create",
"a",
"logger",
"for",
"python",
"-",
"gnupg",
"at",
"a",
"specific",
"message",
"level",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_logger.py#L48-L99 | train | 203,660 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGMeta._find_agent | 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 | python | 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 | [
"def",
"_find_agent",
"(",
"cls",
")",
":",
"if",
"not",
"psutil",
":",
"return",
"False",
"this_process",
"=",
"psutil",
".",
"Process",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"ownership_match",
"=",
"False",
"if",
"_util",
".",
"_running_windows",
":... | 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. | [
"Discover",
"if",
"a",
"gpg",
"-",
"agent",
"process",
"for",
"the",
"current",
"euid",
"is",
"running",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L82-L139 | train | 203,661 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGBase.default_preference_list | 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 | python | 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 | [
"def",
"default_preference_list",
"(",
"self",
",",
"prefs",
")",
":",
"prefs",
"=",
"_check_preferences",
"(",
"prefs",
")",
"if",
"prefs",
"is",
"not",
"None",
":",
"self",
".",
"_prefs",
"=",
"prefs"
] | Set the default preference list.
:param str prefs: A string containing the default preferences for
ciphers, digests, and compression algorithms. | [
"Set",
"the",
"default",
"preference",
"list",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L352-L360 | train | 203,662 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGBase._homedir_setter | 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 | python | 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 | [
"def",
"_homedir_setter",
"(",
"self",
",",
"directory",
")",
":",
"if",
"not",
"directory",
":",
"log",
".",
"debug",
"(",
"\"GPGBase._homedir_setter(): Using default homedir: '%s'\"",
"%",
"_util",
".",
"_conf",
")",
"directory",
"=",
"_util",
".",
"_conf",
"h... | 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. | [
"Set",
"the",
"directory",
"to",
"use",
"as",
"GnuPG",
"s",
"homedir",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L410-L451 | train | 203,663 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGBase._generated_keys_setter | 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 | python | 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 | [
"def",
"_generated_keys_setter",
"(",
"self",
",",
"directory",
")",
":",
"if",
"not",
"directory",
":",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"homedir",
",",
"'generated-keys'",
")",
"log",
".",
"debug",
"(",
"\"GPGBase._gene... | 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. | [
"Set",
"the",
"directory",
"for",
"storing",
"generated",
"keys",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L463-L503 | train | 203,664 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGBase._make_args | 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 | python | 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 | [
"def",
"_make_args",
"(",
"self",
",",
"args",
",",
"passphrase",
"=",
"False",
")",
":",
"## see TODO file, tag :io:makeargs:",
"cmd",
"=",
"[",
"self",
".",
"binary",
",",
"'--no-options --no-emit-version --no-tty --status-fd 2'",
"]",
"if",
"self",
".",
"homedir"... | 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. | [
"Make",
"a",
"list",
"of",
"command",
"line",
"elements",
"for",
"GPG",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L535-L592 | train | 203,665 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGBase._open_subprocess | 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) | python | 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) | [
"def",
"_open_subprocess",
"(",
"self",
",",
"args",
"=",
"None",
",",
"passphrase",
"=",
"False",
")",
":",
"## see http://docs.python.org/2/library/subprocess.html#converting-an\\",
"## -argument-sequence-to-a-string-on-windows",
"cmd",
"=",
"shlex",
".",
"split",
"(",... | 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. | [
"Open",
"a",
"pipe",
"to",
"a",
"GPG",
"subprocess",
"and",
"return",
"the",
"file",
"objects",
"for",
"communicating",
"with",
"it",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L594-L634 | train | 203,666 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGBase._read_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`.
"""
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)) | python | 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)) | [
"def",
"_read_data",
"(",
"self",
",",
"stream",
",",
"result",
")",
":",
"chunks",
"=",
"[",
"]",
"log",
".",
"debug",
"(",
"\"Reading data from stream %r...\"",
"%",
"stream",
".",
"__repr__",
"(",
")",
")",
"while",
"True",
":",
"data",
"=",
"stream",... | 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`. | [
"Incrementally",
"read",
"from",
"stream",
"and",
"store",
"read",
"data",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L695-L718 | train | 203,667 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGBase._handle_io | 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 | python | 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 | [
"def",
"_handle_io",
"(",
"self",
",",
"args",
",",
"file",
",",
"result",
",",
"passphrase",
"=",
"False",
",",
"binary",
"=",
"False",
")",
":",
"p",
"=",
"self",
".",
"_open_subprocess",
"(",
"args",
",",
"passphrase",
")",
"if",
"not",
"binary",
... | Handle a call to GPG - pass input data, collect output data. | [
"Handle",
"a",
"call",
"to",
"GPG",
"-",
"pass",
"input",
"data",
"collect",
"output",
"data",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L782-L793 | train | 203,668 |
isislovecruft/python-gnupg | pretty_bad_protocol/_meta.py | GPGBase._sign_file | 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 | python | 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 | [
"def",
"_sign_file",
"(",
"self",
",",
"file",
",",
"default_key",
"=",
"None",
",",
"passphrase",
"=",
"None",
",",
"clearsign",
"=",
"True",
",",
"detach",
"=",
"False",
",",
"binary",
"=",
"False",
",",
"digest_algo",
"=",
"'SHA512'",
")",
":",
"log... | 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'``. | [
"Create",
"a",
"signature",
"for",
"a",
"file",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L816-L879 | train | 203,669 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | find_encodings | 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 | python | 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 | [
"def",
"find_encodings",
"(",
"enc",
"=",
"None",
",",
"system",
"=",
"False",
")",
":",
"if",
"not",
"enc",
":",
"enc",
"=",
"'utf-8'",
"if",
"system",
":",
"if",
"getattr",
"(",
"sys",
".",
"stdin",
",",
"'encoding'",
",",
"None",
")",
"is",
"Non... | 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. | [
"Find",
"functions",
"for",
"encoding",
"translations",
"for",
"a",
"specific",
"codec",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L136-L168 | train | 203,670 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | author_info | 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) | python | 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) | [
"def",
"author_info",
"(",
"name",
",",
"contact",
"=",
"None",
",",
"public_key",
"=",
"None",
")",
":",
"return",
"Storage",
"(",
"name",
"=",
"name",
",",
"contact",
"=",
"contact",
",",
"public_key",
"=",
"public_key",
")"
] | 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. | [
"Easy",
"object",
"-",
"oriented",
"representation",
"of",
"contributor",
"info",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L213-L221 | train | 203,671 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _copy_data | 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) | python | 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) | [
"def",
"_copy_data",
"(",
"instream",
",",
"outstream",
")",
":",
"sent",
"=",
"0",
"while",
"True",
":",
"if",
"(",
"(",
"_py3k",
"and",
"isinstance",
"(",
"instream",
",",
"str",
")",
")",
"or",
"(",
"not",
"_py3k",
"and",
"isinstance",
"(",
"instr... | 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. | [
"Copy",
"data",
"from",
"one",
"stream",
"to",
"another",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L223-L308 | train | 203,672 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _create_if_necessary | 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 | python | 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 | [
"def",
"_create_if_necessary",
"(",
"directory",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"directory",
")",
":",
"log",
".",
"debug",
"(",
"\"Got non-absolute path: %s\"",
"%",
"directory",
")",
"directory",
"=",
"os",
".",
"path",
".",... | 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. | [
"Create",
"the",
"specified",
"directory",
"if",
"necessary",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L310-L332 | train | 203,673 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | create_uid_email | 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 | python | 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 | [
"def",
"create_uid_email",
"(",
"username",
"=",
"None",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"hostname",
":",
"hostname",
"=",
"hostname",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"if",
"not",
"username",
":",
"try",
":",
"username",
"=",... | 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>. | [
"Create",
"an",
"email",
"address",
"suitable",
"for",
"a",
"UID",
"on",
"a",
"GnuPG",
"key",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L334-L365 | train | 203,674 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _deprefix | 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 | python | 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 | [
"def",
"_deprefix",
"(",
"line",
",",
"prefix",
",",
"callback",
"=",
"None",
")",
":",
"try",
":",
"assert",
"line",
".",
"upper",
"(",
")",
".",
"startswith",
"(",
"u''",
".",
"join",
"(",
"prefix",
")",
".",
"upper",
"(",
")",
")",
"except",
"... | 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. | [
"Remove",
"the",
"prefix",
"string",
"from",
"the",
"beginning",
"of",
"line",
"if",
"it",
"exists",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L367-L393 | train | 203,675 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _find_binary | 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 | python | 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 | [
"def",
"_find_binary",
"(",
"binary",
"=",
"None",
")",
":",
"found",
"=",
"None",
"if",
"binary",
"is",
"not",
"None",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"binary",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"binary",
")",
"... | 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. | [
"Find",
"the",
"absolute",
"path",
"to",
"the",
"GnuPG",
"binary",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L395-L433 | train | 203,676 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _is_gpg1 | 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 | python | 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 | [
"def",
"_is_gpg1",
"(",
"version",
")",
":",
"(",
"major",
",",
"minor",
",",
"micro",
")",
"=",
"_match_version_string",
"(",
"version",
")",
"if",
"major",
"==",
"1",
":",
"return",
"True",
"return",
"False"
] | Returns True if using GnuPG version 1.x.
:param tuple version: A tuple of three integers indication major, minor,
and micro version numbers. | [
"Returns",
"True",
"if",
"using",
"GnuPG",
"version",
"1",
".",
"x",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L516-L525 | train | 203,677 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _is_gpg2 | 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 | python | 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 | [
"def",
"_is_gpg2",
"(",
"version",
")",
":",
"(",
"major",
",",
"minor",
",",
"micro",
")",
"=",
"_match_version_string",
"(",
"version",
")",
"if",
"major",
"==",
"2",
":",
"return",
"True",
"return",
"False"
] | Returns True if using GnuPG version 2.x.
:param tuple version: A tuple of three integers indication major, minor,
and micro version numbers. | [
"Returns",
"True",
"if",
"using",
"GnuPG",
"version",
"2",
".",
"x",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L527-L536 | train | 203,678 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _make_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.
"""
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 | python | 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 | [
"def",
"_make_passphrase",
"(",
"length",
"=",
"None",
",",
"save",
"=",
"False",
",",
"file",
"=",
"None",
")",
":",
"if",
"not",
"length",
":",
"length",
"=",
"40",
"passphrase",
"=",
"_make_random_string",
"(",
"length",
")",
"if",
"save",
":",
"rui... | 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. | [
"Create",
"a",
"passphrase",
"and",
"write",
"it",
"to",
"a",
"file",
"that",
"only",
"the",
"user",
"can",
"read",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L560-L594 | train | 203,679 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _make_random_string | 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)) | python | 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)) | [
"def",
"_make_random_string",
"(",
"length",
")",
":",
"chars",
"=",
"string",
".",
"ascii_lowercase",
"+",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"for",... | Returns a random lowercase, uppercase, alphanumerical string.
:param int length: The length in bytes of the string to generate. | [
"Returns",
"a",
"random",
"lowercase",
"uppercase",
"alphanumerical",
"string",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L596-L602 | train | 203,680 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _match_version_string | 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) | python | 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) | [
"def",
"_match_version_string",
"(",
"version",
")",
":",
"matched",
"=",
"_VERSION_STRING_REGEX",
".",
"match",
"(",
"version",
")",
"g",
"=",
"matched",
".",
"groups",
"(",
")",
"major",
",",
"minor",
",",
"micro",
"=",
"g",
"[",
"0",
"]",
",",
"g",
... | 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)``. | [
"Sort",
"a",
"binary",
"version",
"string",
"into",
"major",
"minor",
"and",
"micro",
"integers",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L604-L631 | train | 203,681 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _next_year | 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)) | python | 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)) | [
"def",
"_next_year",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"__str__",
"(",
")",
"date",
"=",
"now",
".",
"split",
"(",
"' '",
",",
"1",
")",
"[",
"0",
"]",
"year",
",",
"month",
",",
"day",
"=",
"date",
".",
"split... | Get the date of today plus one year.
:rtype: str
:returns: The date of this day next year, in the format '%Y-%m-%d'. | [
"Get",
"the",
"date",
"of",
"today",
"plus",
"one",
"year",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L633-L643 | train | 203,682 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _threaded_copy_data | 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 | python | 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 | [
"def",
"_threaded_copy_data",
"(",
"instream",
",",
"outstream",
")",
":",
"copy_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"_copy_data",
",",
"args",
"=",
"(",
"instream",
",",
"outstream",
")",
")",
"copy_thread",
".",
"setDaemon",
"(",
... | 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",
"data",
"from",
"one",
"stream",
"to",
"another",
"in",
"a",
"separate",
"thread",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L658-L672 | train | 203,683 |
isislovecruft/python-gnupg | pretty_bad_protocol/_util.py | _write_passphrase | 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.") | python | 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.") | [
"def",
"_write_passphrase",
"(",
"stream",
",",
"passphrase",
",",
"encoding",
")",
":",
"passphrase",
"=",
"'%s\\n'",
"%",
"passphrase",
"passphrase",
"=",
"passphrase",
".",
"encode",
"(",
"encoding",
")",
"stream",
".",
"write",
"(",
"passphrase",
")",
"l... | 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()``. | [
"Write",
"the",
"passphrase",
"from",
"memory",
"to",
"the",
"GnuPG",
"process",
"stdin",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L727-L739 | train | 203,684 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.sign | 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'``.
"""
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 | python | 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'``.
"""
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",
")",
":",
"if",
"'default_key'",
"in",
"kwargs",
":",
"log",
".",
"info",
"(",
"\"Signing message '%r' with keyid: %s\"",
"%",
"(",
"data",
",",
"kwargs",
"[",
"'default_key'",
"]",
")",
"... | 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'``. | [
"Create",
"a",
"signature",
"for",
"a",
"message",
"string",
"or",
"file",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L215-L263 | train | 203,685 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.verify | 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
"""
f = _make_binary_stream(data, self._encoding)
result = self.verify_file(f)
f.close()
return result | python | 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
"""
f = _make_binary_stream(data, self._encoding)
result = self.verify_file(f)
f.close()
return result | [
"def",
"verify",
"(",
"self",
",",
"data",
")",
":",
"f",
"=",
"_make_binary_stream",
"(",
"data",
",",
"self",
".",
"_encoding",
")",
"result",
"=",
"self",
".",
"verify_file",
"(",
"f",
")",
"f",
".",
"close",
"(",
")",
"return",
"result"
] | 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 | [
"Verify",
"the",
"signature",
"on",
"the",
"contents",
"of",
"the",
"string",
"data",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L265-L283 | train | 203,686 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.verify_file | 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 | python | 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 | [
"def",
"verify_file",
"(",
"self",
",",
"file",
",",
"sig_file",
"=",
"None",
")",
":",
"result",
"=",
"self",
".",
"_result_map",
"[",
"'verify'",
"]",
"(",
"self",
")",
"if",
"sig_file",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"\"verify_file(): ... | 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`. | [
"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",
... | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L285-L321 | train | 203,687 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.import_keys | 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
"""
## 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 | python | 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
"""
## 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",
")",
":",
"## 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'",
"]",
"(",
... | 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 | [
"Import",
"the",
"key_data",
"into",
"our",
"keyring",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L323-L367 | train | 203,688 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.delete_keys | 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 | python | 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 | [
"def",
"delete_keys",
"(",
"self",
",",
"fingerprints",
",",
"secret",
"=",
"False",
",",
"subkeys",
"=",
"False",
")",
":",
"which",
"=",
"'keys'",
"if",
"secret",
":",
"which",
"=",
"'secret-keys'",
"if",
"subkeys",
":",
"which",
"=",
"'secret-and-public... | 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`. | [
"Delete",
"a",
"key",
"or",
"list",
"of",
"keys",
"from",
"the",
"current",
"keyring",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L387-L421 | train | 203,689 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.export_keys | 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) | python | 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) | [
"def",
"export_keys",
"(",
"self",
",",
"keyids",
",",
"secret",
"=",
"False",
",",
"subkeys",
"=",
"False",
")",
":",
"which",
"=",
"''",
"if",
"subkeys",
":",
"which",
"=",
"'-secret-subkeys'",
"elif",
"secret",
":",
"which",
"=",
"'-secret-keys'",
"if... | 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. | [
"Export",
"the",
"indicated",
"keyids",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L423-L450 | train | 203,690 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.list_keys | 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
"""
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 | python | 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
"""
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",
")",
":",
"which",
"=",
"'public-keys'",
"if",
"secret",
":",
"which",
"=",
"'secret-keys'",
"args",
"=",
"[",
"]",
"args",
".",
"append",
"(",
"\"--fixed-list-mode\"",
")",
"args",
".",
"appe... | 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 | [
"List",
"the",
"keys",
"currently",
"in",
"the",
"keyring",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L452-L494 | train | 203,691 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.list_packets | 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 | python | 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 | [
"def",
"list_packets",
"(",
"self",
",",
"raw_data",
")",
":",
"args",
"=",
"[",
"\"--list-packets\"",
"]",
"result",
"=",
"self",
".",
"_result_map",
"[",
"'packets'",
"]",
"(",
"self",
")",
"self",
".",
"_handle_io",
"(",
"args",
",",
"_make_binary_strea... | List the packet contents of a file. | [
"List",
"the",
"packet",
"contents",
"of",
"a",
"file",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L496-L502 | train | 203,692 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.encrypt | 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`
"""
if _is_stream(data):
stream = data
else:
stream = _make_binary_stream(data, self._encoding)
result = self._encrypt(stream, recipients, **kwargs)
stream.close()
return result | python | 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`
"""
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",
")",
":",
"if",
"_is_stream",
"(",
"data",
")",
":",
"stream",
"=",
"data",
"else",
":",
"stream",
"=",
"_make_binary_stream",
"(",
"data",
",",
"self",
".",... | 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` | [
"Encrypt",
"the",
"message",
"contained",
"in",
"data",
"to",
"recipients",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L982-L1073 | train | 203,693 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.decrypt | 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 | python | 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 | [
"def",
"decrypt",
"(",
"self",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"stream",
"=",
"_make_binary_stream",
"(",
"message",
",",
"self",
".",
"_encoding",
")",
"result",
"=",
"self",
".",
"decrypt_file",
"(",
"stream",
",",
"*",
"*",
"kwarg... | 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. | [
"Decrypt",
"the",
"contents",
"of",
"a",
"string",
"or",
"file",
"-",
"like",
"object",
"message",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L1075-L1087 | train | 203,694 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPG.decrypt_file | 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 | python | 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 | [
"def",
"decrypt_file",
"(",
"self",
",",
"filename",
",",
"always_trust",
"=",
"False",
",",
"passphrase",
"=",
"None",
",",
"output",
"=",
"None",
")",
":",
"args",
"=",
"[",
"\"--decrypt\"",
"]",
"if",
"output",
":",
"# write the output to a file with the sp... | 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. | [
"Decrypt",
"the",
"contents",
"of",
"a",
"file",
"-",
"like",
"object",
"filename",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L1089-L1108 | train | 203,695 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPGUtilities.find_key_by_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.
"""
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) | python | 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) | [
"def",
"find_key_by_email",
"(",
"self",
",",
"email",
",",
"secret",
"=",
"False",
")",
":",
"for",
"key",
"in",
"self",
".",
"list_keys",
"(",
"secret",
"=",
"secret",
")",
":",
"for",
"uid",
"in",
"key",
"[",
"'uids'",
"]",
":",
"if",
"re",
".",... | 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. | [
"Find",
"user",
"s",
"key",
"based",
"on",
"their",
"email",
"address",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L1117-L1127 | train | 203,696 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPGUtilities.find_key_by_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.
"""
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) | python | 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) | [
"def",
"find_key_by_subkey",
"(",
"self",
",",
"subkey",
")",
":",
"for",
"key",
"in",
"self",
".",
"list_keys",
"(",
")",
":",
"for",
"sub",
"in",
"key",
"[",
"'subkeys'",
"]",
":",
"if",
"sub",
"[",
"0",
"]",
"==",
"subkey",
":",
"return",
"key",... | Find a key by a fingerprint of one of its subkeys.
:param str subkey: The fingerprint of the subkey to search for. | [
"Find",
"a",
"key",
"by",
"a",
"fingerprint",
"of",
"one",
"of",
"its",
"subkeys",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L1129-L1139 | train | 203,697 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPGUtilities.send_keys | 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 | python | 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 | [
"def",
"send_keys",
"(",
"self",
",",
"keyserver",
",",
"*",
"keyids",
")",
":",
"result",
"=",
"self",
".",
"_result_map",
"[",
"'list'",
"]",
"(",
"self",
")",
"log",
".",
"debug",
"(",
"'send_keys: %r'",
",",
"keyids",
")",
"data",
"=",
"_util",
"... | Send keys to a keyserver. | [
"Send",
"keys",
"to",
"a",
"keyserver",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L1141-L1151 | train | 203,698 |
isislovecruft/python-gnupg | pretty_bad_protocol/gnupg.py | GPGUtilities.encrypted_to | 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) | python | 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) | [
"def",
"encrypted_to",
"(",
"self",
",",
"raw_data",
")",
":",
"# TODO: make this support multiple keys.",
"result",
"=",
"self",
".",
"_gpg",
".",
"list_packets",
"(",
"raw_data",
")",
"if",
"not",
"result",
".",
"key",
":",
"raise",
"LookupError",
"(",
"\"Co... | Return the key to which raw_data is encrypted to. | [
"Return",
"the",
"key",
"to",
"which",
"raw_data",
"is",
"encrypted",
"to",
"."
] | 784571449032e811587249743e183fc5e908a673 | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L1153-L1163 | train | 203,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.