id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
15,200 | SwissDataScienceCenter/renku-python | brew.py | find_release | def find_release(package, releases, dependencies=None):
"""Return the best release."""
dependencies = dependencies if dependencies is not None else {}
for release in releases:
url = release['url']
old_priority = dependencies.get(package, {}).get('priority', 0)
for suffix, priority in SUFFIXES.items():
if url.endswith(suffix):
if old_priority < priority:
sha256 = release['digests']['sha256']
dependencies[package] = {
'package': package,
'url': url,
'sha256': sha256,
'priority': priority,
}
return dependencies[package] | python | def find_release(package, releases, dependencies=None):
dependencies = dependencies if dependencies is not None else {}
for release in releases:
url = release['url']
old_priority = dependencies.get(package, {}).get('priority', 0)
for suffix, priority in SUFFIXES.items():
if url.endswith(suffix):
if old_priority < priority:
sha256 = release['digests']['sha256']
dependencies[package] = {
'package': package,
'url': url,
'sha256': sha256,
'priority': priority,
}
return dependencies[package] | [
"def",
"find_release",
"(",
"package",
",",
"releases",
",",
"dependencies",
"=",
"None",
")",
":",
"dependencies",
"=",
"dependencies",
"if",
"dependencies",
"is",
"not",
"None",
"else",
"{",
"}",
"for",
"release",
"in",
"releases",
":",
"url",
"=",
"rele... | Return the best release. | [
"Return",
"the",
"best",
"release",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/brew.py#L83-L101 |
15,201 | SwissDataScienceCenter/renku-python | renku/cli/_graph.py | _safe_path | def _safe_path(filepath, can_be_cwl=False):
"""Check if the path should be used in output."""
# Should not be in ignore paths.
if filepath in {'.gitignore', '.gitattributes'}:
return False
# Ignore everything in .renku ...
if filepath.startswith('.renku'):
# ... unless it can be a CWL.
if can_be_cwl and filepath.endswith('.cwl'):
return True
return False
return True | python | def _safe_path(filepath, can_be_cwl=False):
# Should not be in ignore paths.
if filepath in {'.gitignore', '.gitattributes'}:
return False
# Ignore everything in .renku ...
if filepath.startswith('.renku'):
# ... unless it can be a CWL.
if can_be_cwl and filepath.endswith('.cwl'):
return True
return False
return True | [
"def",
"_safe_path",
"(",
"filepath",
",",
"can_be_cwl",
"=",
"False",
")",
":",
"# Should not be in ignore paths.",
"if",
"filepath",
"in",
"{",
"'.gitignore'",
",",
"'.gitattributes'",
"}",
":",
"return",
"False",
"# Ignore everything in .renku ...",
"if",
"filepath... | Check if the path should be used in output. | [
"Check",
"if",
"the",
"path",
"should",
"be",
"used",
"in",
"output",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_graph.py#L62-L75 |
15,202 | SwissDataScienceCenter/renku-python | renku/cli/_format/datasets.py | tabular | def tabular(client, datasets):
"""Format datasets with a tabular output."""
from renku.models._tabulate import tabulate
click.echo(
tabulate(
datasets,
headers=OrderedDict((
('short_id', 'id'),
('name', None),
('created', None),
('authors_csv', 'authors'),
)),
)
) | python | def tabular(client, datasets):
from renku.models._tabulate import tabulate
click.echo(
tabulate(
datasets,
headers=OrderedDict((
('short_id', 'id'),
('name', None),
('created', None),
('authors_csv', 'authors'),
)),
)
) | [
"def",
"tabular",
"(",
"client",
",",
"datasets",
")",
":",
"from",
"renku",
".",
"models",
".",
"_tabulate",
"import",
"tabulate",
"click",
".",
"echo",
"(",
"tabulate",
"(",
"datasets",
",",
"headers",
"=",
"OrderedDict",
"(",
"(",
"(",
"'short_id'",
"... | Format datasets with a tabular output. | [
"Format",
"datasets",
"with",
"a",
"tabular",
"output",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/datasets.py#L26-L40 |
15,203 | SwissDataScienceCenter/renku-python | renku/cli/_format/datasets.py | jsonld | def jsonld(client, datasets):
"""Format datasets as JSON-LD."""
from renku.models._json import dumps
from renku.models._jsonld import asjsonld
data = [
asjsonld(
dataset,
basedir=os.path.relpath(
'.', start=str(dataset.__reference__.parent)
)
) for dataset in datasets
]
click.echo(dumps(data, indent=2)) | python | def jsonld(client, datasets):
from renku.models._json import dumps
from renku.models._jsonld import asjsonld
data = [
asjsonld(
dataset,
basedir=os.path.relpath(
'.', start=str(dataset.__reference__.parent)
)
) for dataset in datasets
]
click.echo(dumps(data, indent=2)) | [
"def",
"jsonld",
"(",
"client",
",",
"datasets",
")",
":",
"from",
"renku",
".",
"models",
".",
"_json",
"import",
"dumps",
"from",
"renku",
".",
"models",
".",
"_jsonld",
"import",
"asjsonld",
"data",
"=",
"[",
"asjsonld",
"(",
"dataset",
",",
"basedir"... | Format datasets as JSON-LD. | [
"Format",
"datasets",
"as",
"JSON",
"-",
"LD",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/datasets.py#L43-L56 |
15,204 | SwissDataScienceCenter/renku-python | renku/cli/_ascii.py | _format_sha1 | def _format_sha1(graph, node):
"""Return formatted text with the submodule information."""
try:
submodules = node.submodules
if submodules:
submodule = ':'.join(submodules)
return click.style(submodule, fg='green') + '@' + click.style(
node.commit.hexsha[:8], fg='yellow'
)
except KeyError:
pass
return click.style(node.commit.hexsha[:8], fg='yellow') | python | def _format_sha1(graph, node):
try:
submodules = node.submodules
if submodules:
submodule = ':'.join(submodules)
return click.style(submodule, fg='green') + '@' + click.style(
node.commit.hexsha[:8], fg='yellow'
)
except KeyError:
pass
return click.style(node.commit.hexsha[:8], fg='yellow') | [
"def",
"_format_sha1",
"(",
"graph",
",",
"node",
")",
":",
"try",
":",
"submodules",
"=",
"node",
".",
"submodules",
"if",
"submodules",
":",
"submodule",
"=",
"':'",
".",
"join",
"(",
"submodules",
")",
"return",
"click",
".",
"style",
"(",
"submodule"... | Return formatted text with the submodule information. | [
"Return",
"formatted",
"text",
"with",
"the",
"submodule",
"information",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_ascii.py#L34-L46 |
15,205 | SwissDataScienceCenter/renku-python | renku/models/cwl/command_line_tool.py | convert_arguments | def convert_arguments(value):
"""Convert arguments from various input formats."""
if isinstance(value, (list, tuple)):
return [
CommandLineBinding(**item) if isinstance(item, dict) else item
for item in value
]
return shlex.split(value) | python | def convert_arguments(value):
if isinstance(value, (list, tuple)):
return [
CommandLineBinding(**item) if isinstance(item, dict) else item
for item in value
]
return shlex.split(value) | [
"def",
"convert_arguments",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"CommandLineBinding",
"(",
"*",
"*",
"item",
")",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
"... | Convert arguments from various input formats. | [
"Convert",
"arguments",
"from",
"various",
"input",
"formats",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/cwl/command_line_tool.py#L40-L47 |
15,206 | SwissDataScienceCenter/renku-python | renku/cli/__init__.py | cli | def cli(ctx, path, renku_home, use_external_storage):
"""Check common Renku commands used in various situations."""
ctx.obj = LocalClient(
path=path,
renku_home=renku_home,
use_external_storage=use_external_storage,
) | python | def cli(ctx, path, renku_home, use_external_storage):
ctx.obj = LocalClient(
path=path,
renku_home=renku_home,
use_external_storage=use_external_storage,
) | [
"def",
"cli",
"(",
"ctx",
",",
"path",
",",
"renku_home",
",",
"use_external_storage",
")",
":",
"ctx",
".",
"obj",
"=",
"LocalClient",
"(",
"path",
"=",
"path",
",",
"renku_home",
"=",
"renku_home",
",",
"use_external_storage",
"=",
"use_external_storage",
... | Check common Renku commands used in various situations. | [
"Check",
"common",
"Renku",
"commands",
"used",
"in",
"various",
"situations",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/__init__.py#L188-L194 |
15,207 | SwissDataScienceCenter/renku-python | renku/cli/update.py | update | def update(client, revision, no_output, siblings, paths):
"""Update existing files by rerunning their outdated workflow."""
graph = Graph(client)
outputs = graph.build(revision=revision, can_be_cwl=no_output, paths=paths)
outputs = {node for node in outputs if graph.need_update(node)}
if not outputs:
click.secho(
'All files were generated from the latest inputs.', fg='green'
)
sys.exit(0)
# Check or extend siblings of outputs.
outputs = siblings(graph, outputs)
output_paths = {node.path for node in outputs if _safe_path(node.path)}
# Get all clean nodes.
input_paths = {node.path for node in graph.nodes} - output_paths
# Store the generated workflow used for updating paths.
import yaml
output_file = client.workflow_path / '{0}.cwl'.format(uuid.uuid4().hex)
workflow = graph.ascwl(
input_paths=input_paths,
output_paths=output_paths,
outputs=outputs,
)
# Make sure all inputs are pulled from a storage.
client.pull_paths_from_storage(
*(path for _, path in workflow.iter_input_files(client.workflow_path))
)
with output_file.open('w') as f:
f.write(
yaml.dump(
ascwl(
workflow,
filter=lambda _, x: x is not None,
basedir=client.workflow_path,
),
default_flow_style=False
)
)
from ._cwl import execute
execute(client, output_file, output_paths=output_paths) | python | def update(client, revision, no_output, siblings, paths):
graph = Graph(client)
outputs = graph.build(revision=revision, can_be_cwl=no_output, paths=paths)
outputs = {node for node in outputs if graph.need_update(node)}
if not outputs:
click.secho(
'All files were generated from the latest inputs.', fg='green'
)
sys.exit(0)
# Check or extend siblings of outputs.
outputs = siblings(graph, outputs)
output_paths = {node.path for node in outputs if _safe_path(node.path)}
# Get all clean nodes.
input_paths = {node.path for node in graph.nodes} - output_paths
# Store the generated workflow used for updating paths.
import yaml
output_file = client.workflow_path / '{0}.cwl'.format(uuid.uuid4().hex)
workflow = graph.ascwl(
input_paths=input_paths,
output_paths=output_paths,
outputs=outputs,
)
# Make sure all inputs are pulled from a storage.
client.pull_paths_from_storage(
*(path for _, path in workflow.iter_input_files(client.workflow_path))
)
with output_file.open('w') as f:
f.write(
yaml.dump(
ascwl(
workflow,
filter=lambda _, x: x is not None,
basedir=client.workflow_path,
),
default_flow_style=False
)
)
from ._cwl import execute
execute(client, output_file, output_paths=output_paths) | [
"def",
"update",
"(",
"client",
",",
"revision",
",",
"no_output",
",",
"siblings",
",",
"paths",
")",
":",
"graph",
"=",
"Graph",
"(",
"client",
")",
"outputs",
"=",
"graph",
".",
"build",
"(",
"revision",
"=",
"revision",
",",
"can_be_cwl",
"=",
"no_... | Update existing files by rerunning their outdated workflow. | [
"Update",
"existing",
"files",
"by",
"rerunning",
"their",
"outdated",
"workflow",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/update.py#L143-L190 |
15,208 | SwissDataScienceCenter/renku-python | renku/cli/_config.py | config_path | def config_path(path=None, final=False):
"""Return config path."""
if final and path:
return path
if path is None:
path = default_config_dir()
try:
os.makedirs(path)
except OSError as e: # pragma: no cover
if e.errno != errno.EEXIST:
raise
return os.path.join(path, 'config.yml') | python | def config_path(path=None, final=False):
if final and path:
return path
if path is None:
path = default_config_dir()
try:
os.makedirs(path)
except OSError as e: # pragma: no cover
if e.errno != errno.EEXIST:
raise
return os.path.join(path, 'config.yml') | [
"def",
"config_path",
"(",
"path",
"=",
"None",
",",
"final",
"=",
"False",
")",
":",
"if",
"final",
"and",
"path",
":",
"return",
"path",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"default_config_dir",
"(",
")",
"try",
":",
"os",
".",
"makedirs"... | Return config path. | [
"Return",
"config",
"path",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_config.py#L48-L60 |
15,209 | SwissDataScienceCenter/renku-python | renku/cli/_config.py | read_config | def read_config(path=None, final=False):
"""Read Renku configuration."""
try:
with open(config_path(path, final=final), 'r') as configfile:
return yaml.safe_load(configfile) or {}
except FileNotFoundError:
return {} | python | def read_config(path=None, final=False):
try:
with open(config_path(path, final=final), 'r') as configfile:
return yaml.safe_load(configfile) or {}
except FileNotFoundError:
return {} | [
"def",
"read_config",
"(",
"path",
"=",
"None",
",",
"final",
"=",
"False",
")",
":",
"try",
":",
"with",
"open",
"(",
"config_path",
"(",
"path",
",",
"final",
"=",
"final",
")",
",",
"'r'",
")",
"as",
"configfile",
":",
"return",
"yaml",
".",
"sa... | Read Renku configuration. | [
"Read",
"Renku",
"configuration",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_config.py#L63-L69 |
15,210 | SwissDataScienceCenter/renku-python | renku/cli/_config.py | write_config | def write_config(config, path, final=False):
"""Write Renku configuration."""
with open(config_path(path, final=final), 'w+') as configfile:
yaml.dump(config, configfile, default_flow_style=False) | python | def write_config(config, path, final=False):
with open(config_path(path, final=final), 'w+') as configfile:
yaml.dump(config, configfile, default_flow_style=False) | [
"def",
"write_config",
"(",
"config",
",",
"path",
",",
"final",
"=",
"False",
")",
":",
"with",
"open",
"(",
"config_path",
"(",
"path",
",",
"final",
"=",
"final",
")",
",",
"'w+'",
")",
"as",
"configfile",
":",
"yaml",
".",
"dump",
"(",
"config",
... | Write Renku configuration. | [
"Write",
"Renku",
"configuration",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_config.py#L72-L75 |
15,211 | SwissDataScienceCenter/renku-python | renku/cli/_config.py | with_config | def with_config(f):
"""Add config to function."""
# keep it.
@click.pass_context
def new_func(ctx, *args, **kwargs):
# Invoked with custom config:
if 'config' in kwargs:
return ctx.invoke(f, *args, **kwargs)
if ctx.obj is None:
ctx.obj = {}
config = ctx.obj['config']
project_enabled = not ctx.obj.get('no_project', False)
project_config_path = get_project_config_path()
if project_enabled and project_config_path:
project_config = read_config(project_config_path)
config['project'] = project_config
result = ctx.invoke(f, config, *args, **kwargs)
project_config = config.pop('project', None)
if project_config:
if not project_config_path:
raise RuntimeError('Invalid config update')
write_config(project_config, path=project_config_path)
write_config(config, path=ctx.obj['config_path'])
if project_config is not None:
config['project'] = project_config
return result
return update_wrapper(new_func, f) | python | def with_config(f):
# keep it.
@click.pass_context
def new_func(ctx, *args, **kwargs):
# Invoked with custom config:
if 'config' in kwargs:
return ctx.invoke(f, *args, **kwargs)
if ctx.obj is None:
ctx.obj = {}
config = ctx.obj['config']
project_enabled = not ctx.obj.get('no_project', False)
project_config_path = get_project_config_path()
if project_enabled and project_config_path:
project_config = read_config(project_config_path)
config['project'] = project_config
result = ctx.invoke(f, config, *args, **kwargs)
project_config = config.pop('project', None)
if project_config:
if not project_config_path:
raise RuntimeError('Invalid config update')
write_config(project_config, path=project_config_path)
write_config(config, path=ctx.obj['config_path'])
if project_config is not None:
config['project'] = project_config
return result
return update_wrapper(new_func, f) | [
"def",
"with_config",
"(",
"f",
")",
":",
"# keep it.",
"@",
"click",
".",
"pass_context",
"def",
"new_func",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Invoked with custom config:",
"if",
"'config'",
"in",
"kwargs",
":",
"return",... | Add config to function. | [
"Add",
"config",
"to",
"function",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_config.py#L88-L120 |
15,212 | SwissDataScienceCenter/renku-python | renku/cli/_config.py | create_project_config_path | def create_project_config_path(
path, mode=0o777, parents=False, exist_ok=False
):
"""Create new project configuration folder."""
# FIXME check default directory mode
project_path = Path(path).absolute().joinpath(RENKU_HOME)
project_path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
return str(project_path) | python | def create_project_config_path(
path, mode=0o777, parents=False, exist_ok=False
):
# FIXME check default directory mode
project_path = Path(path).absolute().joinpath(RENKU_HOME)
project_path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
return str(project_path) | [
"def",
"create_project_config_path",
"(",
"path",
",",
"mode",
"=",
"0o777",
",",
"parents",
"=",
"False",
",",
"exist_ok",
"=",
"False",
")",
":",
"# FIXME check default directory mode",
"project_path",
"=",
"Path",
"(",
"path",
")",
".",
"absolute",
"(",
")"... | Create new project configuration folder. | [
"Create",
"new",
"project",
"configuration",
"folder",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_config.py#L131-L138 |
15,213 | SwissDataScienceCenter/renku-python | renku/cli/_config.py | get_project_config_path | def get_project_config_path(path=None):
"""Return project configuration folder if exist."""
project_path = Path(path or '.').absolute().joinpath(RENKU_HOME)
if project_path.exists() and project_path.is_dir():
return str(project_path) | python | def get_project_config_path(path=None):
project_path = Path(path or '.').absolute().joinpath(RENKU_HOME)
if project_path.exists() and project_path.is_dir():
return str(project_path) | [
"def",
"get_project_config_path",
"(",
"path",
"=",
"None",
")",
":",
"project_path",
"=",
"Path",
"(",
"path",
"or",
"'.'",
")",
".",
"absolute",
"(",
")",
".",
"joinpath",
"(",
"RENKU_HOME",
")",
"if",
"project_path",
".",
"exists",
"(",
")",
"and",
... | Return project configuration folder if exist. | [
"Return",
"project",
"configuration",
"folder",
"if",
"exist",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_config.py#L141-L145 |
15,214 | SwissDataScienceCenter/renku-python | renku/cli/_config.py | find_project_config_path | def find_project_config_path(path=None):
"""Find project config path."""
path = Path(path) if path else Path.cwd()
abspath = path.absolute()
project_path = get_project_config_path(abspath)
if project_path:
return project_path
for parent in abspath.parents:
project_path = get_project_config_path(parent)
if project_path:
return project_path | python | def find_project_config_path(path=None):
path = Path(path) if path else Path.cwd()
abspath = path.absolute()
project_path = get_project_config_path(abspath)
if project_path:
return project_path
for parent in abspath.parents:
project_path = get_project_config_path(parent)
if project_path:
return project_path | [
"def",
"find_project_config_path",
"(",
"path",
"=",
"None",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"if",
"path",
"else",
"Path",
".",
"cwd",
"(",
")",
"abspath",
"=",
"path",
".",
"absolute",
"(",
")",
"project_path",
"=",
"get_project_config_... | Find project config path. | [
"Find",
"project",
"config",
"path",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_config.py#L148-L160 |
15,215 | SwissDataScienceCenter/renku-python | renku/models/provenance/activities.py | _nodes | def _nodes(output, parent=None):
"""Yield nodes from entities."""
# NOTE refactor so all outputs behave the same
entity = getattr(output, 'entity', output)
if isinstance(entity, Collection):
for member in entity.members:
if parent is not None:
member = attr.evolve(member, parent=parent)
yield from _nodes(member)
yield output
else:
yield output | python | def _nodes(output, parent=None):
# NOTE refactor so all outputs behave the same
entity = getattr(output, 'entity', output)
if isinstance(entity, Collection):
for member in entity.members:
if parent is not None:
member = attr.evolve(member, parent=parent)
yield from _nodes(member)
yield output
else:
yield output | [
"def",
"_nodes",
"(",
"output",
",",
"parent",
"=",
"None",
")",
":",
"# NOTE refactor so all outputs behave the same",
"entity",
"=",
"getattr",
"(",
"output",
",",
"'entity'",
",",
"output",
")",
"if",
"isinstance",
"(",
"entity",
",",
"Collection",
")",
":"... | Yield nodes from entities. | [
"Yield",
"nodes",
"from",
"entities",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/provenance/activities.py#L35-L47 |
15,216 | SwissDataScienceCenter/renku-python | renku/models/cwl/_ascwl.py | mapped | def mapped(cls, key='id', **kwargs):
"""Create list of instances from a mapping."""
kwargs.setdefault('metadata', {})
kwargs['metadata']['jsonldPredicate'] = {'mapSubject': key}
kwargs.setdefault('default', attr.Factory(list))
def converter(value):
"""Convert mapping to a list of instances."""
if isinstance(value, dict):
result = []
for k, v in iteritems(value):
if not hasattr(cls, 'from_cwl'):
vv = dict(v)
vv[key] = k
else:
vv = attr.evolve(cls.from_cwl(v), **{key: k})
result.append(vv)
else:
result = value
def fix_keys(data):
"""Fix names of keys."""
for a in fields(cls):
a_name = a.name.rstrip('_')
if a_name in data:
yield a.name, data[a_name]
return [
cls(**{kk: vv
for kk, vv in fix_keys(v)}) if not isinstance(v, cls) else v
for v in result
]
kwargs['converter'] = converter
return attr.ib(**kwargs) | python | def mapped(cls, key='id', **kwargs):
kwargs.setdefault('metadata', {})
kwargs['metadata']['jsonldPredicate'] = {'mapSubject': key}
kwargs.setdefault('default', attr.Factory(list))
def converter(value):
"""Convert mapping to a list of instances."""
if isinstance(value, dict):
result = []
for k, v in iteritems(value):
if not hasattr(cls, 'from_cwl'):
vv = dict(v)
vv[key] = k
else:
vv = attr.evolve(cls.from_cwl(v), **{key: k})
result.append(vv)
else:
result = value
def fix_keys(data):
"""Fix names of keys."""
for a in fields(cls):
a_name = a.name.rstrip('_')
if a_name in data:
yield a.name, data[a_name]
return [
cls(**{kk: vv
for kk, vv in fix_keys(v)}) if not isinstance(v, cls) else v
for v in result
]
kwargs['converter'] = converter
return attr.ib(**kwargs) | [
"def",
"mapped",
"(",
"cls",
",",
"key",
"=",
"'id'",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'metadata'",
",",
"{",
"}",
")",
"kwargs",
"[",
"'metadata'",
"]",
"[",
"'jsonldPredicate'",
"]",
"=",
"{",
"'mapSubject'",
":... | Create list of instances from a mapping. | [
"Create",
"list",
"of",
"instances",
"from",
"a",
"mapping",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/cwl/_ascwl.py#L74-L108 |
15,217 | SwissDataScienceCenter/renku-python | renku/models/cwl/_ascwl.py | CWLClass.from_cwl | def from_cwl(cls, data, __reference__=None):
"""Return an instance from CWL data."""
class_name = data.get('class', None)
cls = cls.registry.get(class_name, cls)
if __reference__:
with with_reference(__reference__):
self = cls(
**{k: v
for k, v in iteritems(data) if k != 'class'}
)
else:
self = cls(**{k: v for k, v in iteritems(data) if k != 'class'})
return self | python | def from_cwl(cls, data, __reference__=None):
class_name = data.get('class', None)
cls = cls.registry.get(class_name, cls)
if __reference__:
with with_reference(__reference__):
self = cls(
**{k: v
for k, v in iteritems(data) if k != 'class'}
)
else:
self = cls(**{k: v for k, v in iteritems(data) if k != 'class'})
return self | [
"def",
"from_cwl",
"(",
"cls",
",",
"data",
",",
"__reference__",
"=",
"None",
")",
":",
"class_name",
"=",
"data",
".",
"get",
"(",
"'class'",
",",
"None",
")",
"cls",
"=",
"cls",
".",
"registry",
".",
"get",
"(",
"class_name",
",",
"cls",
")",
"i... | Return an instance from CWL data. | [
"Return",
"an",
"instance",
"from",
"CWL",
"data",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/cwl/_ascwl.py#L48-L61 |
15,218 | SwissDataScienceCenter/renku-python | renku/cli/runner.py | template | def template(client, force):
"""Render templated configuration files."""
import pkg_resources
# create the templated files
for tpl_file in CI_TEMPLATES:
tpl_path = client.path / tpl_file
with pkg_resources.resource_stream(__name__, tpl_file) as tpl:
content = tpl.read()
if not force and tpl_path.exists():
click.confirm(
'Do you want to override "{tpl_file}"'.format(
tpl_file=tpl_file
),
abort=True,
)
with tpl_path.open('wb') as dest:
dest.write(content) | python | def template(client, force):
import pkg_resources
# create the templated files
for tpl_file in CI_TEMPLATES:
tpl_path = client.path / tpl_file
with pkg_resources.resource_stream(__name__, tpl_file) as tpl:
content = tpl.read()
if not force and tpl_path.exists():
click.confirm(
'Do you want to override "{tpl_file}"'.format(
tpl_file=tpl_file
),
abort=True,
)
with tpl_path.open('wb') as dest:
dest.write(content) | [
"def",
"template",
"(",
"client",
",",
"force",
")",
":",
"import",
"pkg_resources",
"# create the templated files",
"for",
"tpl_file",
"in",
"CI_TEMPLATES",
":",
"tpl_path",
"=",
"client",
".",
"path",
"/",
"tpl_file",
"with",
"pkg_resources",
".",
"resource_stre... | Render templated configuration files. | [
"Render",
"templated",
"configuration",
"files",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/runner.py#L44-L63 |
15,219 | SwissDataScienceCenter/renku-python | renku/cli/runner.py | rerun | def rerun(client, run, job):
"""Re-run existing workflow or tool using CWL runner."""
from renku.models.provenance import ProcessRun
activity = client.process_commmit()
if not isinstance(activity, ProcessRun):
click.secho('No tool was found.', fg='red', file=sys.stderr)
return
try:
args = ['cwl-runner', activity.path]
if job:
job_file = tempfile.NamedTemporaryFile(
suffix='.yml', dir=os.getcwd(), delete=False
)
args.append(job_file.name)
with job_file as fp:
yaml.dump(yaml.safe_load(job), stream=fp, encoding='utf-8')
if run:
return call(args, cwd=os.getcwd())
finally:
if job:
os.unlink(job_file.name) | python | def rerun(client, run, job):
from renku.models.provenance import ProcessRun
activity = client.process_commmit()
if not isinstance(activity, ProcessRun):
click.secho('No tool was found.', fg='red', file=sys.stderr)
return
try:
args = ['cwl-runner', activity.path]
if job:
job_file = tempfile.NamedTemporaryFile(
suffix='.yml', dir=os.getcwd(), delete=False
)
args.append(job_file.name)
with job_file as fp:
yaml.dump(yaml.safe_load(job), stream=fp, encoding='utf-8')
if run:
return call(args, cwd=os.getcwd())
finally:
if job:
os.unlink(job_file.name) | [
"def",
"rerun",
"(",
"client",
",",
"run",
",",
"job",
")",
":",
"from",
"renku",
".",
"models",
".",
"provenance",
"import",
"ProcessRun",
"activity",
"=",
"client",
".",
"process_commmit",
"(",
")",
"if",
"not",
"isinstance",
"(",
"activity",
",",
"Pro... | Re-run existing workflow or tool using CWL runner. | [
"Re",
"-",
"run",
"existing",
"workflow",
"or",
"tool",
"using",
"CWL",
"runner",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/runner.py#L77-L101 |
15,220 | SwissDataScienceCenter/renku-python | renku/cli/rerun.py | _format_default | def _format_default(client, value):
"""Format default values."""
if isinstance(value, File):
return os.path.relpath(
str((client.workflow_path / value.path).resolve())
)
return value | python | def _format_default(client, value):
if isinstance(value, File):
return os.path.relpath(
str((client.workflow_path / value.path).resolve())
)
return value | [
"def",
"_format_default",
"(",
"client",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"File",
")",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"str",
"(",
"(",
"client",
".",
"workflow_path",
"/",
"value",
".",
"path",
")... | Format default values. | [
"Format",
"default",
"values",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/rerun.py#L59-L65 |
15,221 | SwissDataScienceCenter/renku-python | renku/cli/rerun.py | show_inputs | def show_inputs(client, workflow):
"""Show workflow inputs and exit."""
for input_ in workflow.inputs:
click.echo(
'{id}: {default}'.format(
id=input_.id,
default=_format_default(client, input_.default),
)
)
sys.exit(0) | python | def show_inputs(client, workflow):
for input_ in workflow.inputs:
click.echo(
'{id}: {default}'.format(
id=input_.id,
default=_format_default(client, input_.default),
)
)
sys.exit(0) | [
"def",
"show_inputs",
"(",
"client",
",",
"workflow",
")",
":",
"for",
"input_",
"in",
"workflow",
".",
"inputs",
":",
"click",
".",
"echo",
"(",
"'{id}: {default}'",
".",
"format",
"(",
"id",
"=",
"input_",
".",
"id",
",",
"default",
"=",
"_format_defau... | Show workflow inputs and exit. | [
"Show",
"workflow",
"inputs",
"and",
"exit",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/rerun.py#L68-L77 |
15,222 | SwissDataScienceCenter/renku-python | renku/cli/rerun.py | edit_inputs | def edit_inputs(client, workflow):
"""Edit workflow inputs."""
types = {
'int': int,
'string': str,
'File': lambda x: File(path=Path(x).resolve()),
}
for input_ in workflow.inputs:
convert = types.get(input_.type, str)
input_.default = convert(
click.prompt(
'{0.id} ({0.type})'.format(input_),
default=_format_default(client, input_.default),
)
)
return workflow | python | def edit_inputs(client, workflow):
types = {
'int': int,
'string': str,
'File': lambda x: File(path=Path(x).resolve()),
}
for input_ in workflow.inputs:
convert = types.get(input_.type, str)
input_.default = convert(
click.prompt(
'{0.id} ({0.type})'.format(input_),
default=_format_default(client, input_.default),
)
)
return workflow | [
"def",
"edit_inputs",
"(",
"client",
",",
"workflow",
")",
":",
"types",
"=",
"{",
"'int'",
":",
"int",
",",
"'string'",
":",
"str",
",",
"'File'",
":",
"lambda",
"x",
":",
"File",
"(",
"path",
"=",
"Path",
"(",
"x",
")",
".",
"resolve",
"(",
")"... | Edit workflow inputs. | [
"Edit",
"workflow",
"inputs",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/rerun.py#L80-L95 |
15,223 | SwissDataScienceCenter/renku-python | renku/cli/rerun.py | rerun | def rerun(client, revision, roots, siblings, inputs, paths):
"""Recreate files generated by a sequence of ``run`` commands."""
graph = Graph(client)
outputs = graph.build(paths=paths, revision=revision)
# Check or extend siblings of outputs.
outputs = siblings(graph, outputs)
output_paths = {node.path for node in outputs}
# Normalize and check all starting paths.
roots = {graph.normalize_path(root) for root in roots}
assert not roots & output_paths, '--from colides with output paths'
# Generate workflow and check inputs.
# NOTE The workflow creation is done before opening a new file.
workflow = inputs(
client,
graph.ascwl(
input_paths=roots,
output_paths=output_paths,
outputs=outputs,
)
)
# Make sure all inputs are pulled from a storage.
client.pull_paths_from_storage(
*(path for _, path in workflow.iter_input_files(client.workflow_path))
)
# Store the generated workflow used for updating paths.
import yaml
output_file = client.workflow_path / '{0}.cwl'.format(uuid.uuid4().hex)
with output_file.open('w') as f:
f.write(
yaml.dump(
ascwl(
workflow,
filter=lambda _, x: x is not None,
basedir=client.workflow_path,
),
default_flow_style=False
)
)
# Execute the workflow and relocate all output files.
from ._cwl import execute
# FIXME get new output paths for edited tools
# output_paths = {path for _, path in workflow.iter_output_files()}
execute(
client,
output_file,
output_paths=output_paths,
) | python | def rerun(client, revision, roots, siblings, inputs, paths):
graph = Graph(client)
outputs = graph.build(paths=paths, revision=revision)
# Check or extend siblings of outputs.
outputs = siblings(graph, outputs)
output_paths = {node.path for node in outputs}
# Normalize and check all starting paths.
roots = {graph.normalize_path(root) for root in roots}
assert not roots & output_paths, '--from colides with output paths'
# Generate workflow and check inputs.
# NOTE The workflow creation is done before opening a new file.
workflow = inputs(
client,
graph.ascwl(
input_paths=roots,
output_paths=output_paths,
outputs=outputs,
)
)
# Make sure all inputs are pulled from a storage.
client.pull_paths_from_storage(
*(path for _, path in workflow.iter_input_files(client.workflow_path))
)
# Store the generated workflow used for updating paths.
import yaml
output_file = client.workflow_path / '{0}.cwl'.format(uuid.uuid4().hex)
with output_file.open('w') as f:
f.write(
yaml.dump(
ascwl(
workflow,
filter=lambda _, x: x is not None,
basedir=client.workflow_path,
),
default_flow_style=False
)
)
# Execute the workflow and relocate all output files.
from ._cwl import execute
# FIXME get new output paths for edited tools
# output_paths = {path for _, path in workflow.iter_output_files()}
execute(
client,
output_file,
output_paths=output_paths,
) | [
"def",
"rerun",
"(",
"client",
",",
"revision",
",",
"roots",
",",
"siblings",
",",
"inputs",
",",
"paths",
")",
":",
"graph",
"=",
"Graph",
"(",
"client",
")",
"outputs",
"=",
"graph",
".",
"build",
"(",
"paths",
"=",
"paths",
",",
"revision",
"=",
... | Recreate files generated by a sequence of ``run`` commands. | [
"Recreate",
"files",
"generated",
"by",
"a",
"sequence",
"of",
"run",
"commands",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/rerun.py#L134-L187 |
15,224 | SwissDataScienceCenter/renku-python | renku/cli/migrate.py | datasets | def datasets(ctx, client):
"""Migrate dataset metadata."""
from renku.models._jsonld import asjsonld
from renku.models.datasets import Dataset
from renku.models.refs import LinkReference
from ._checks.location_datasets import _dataset_metadata_pre_0_3_4
for old_path in _dataset_metadata_pre_0_3_4(client):
with old_path.open('r') as fp:
dataset = Dataset.from_jsonld(yaml.safe_load(fp))
name = str(old_path.parent.relative_to(client.path / 'data'))
new_path = (
client.renku_datasets_path / dataset.identifier.hex /
client.METADATA
)
new_path.parent.mkdir(parents=True, exist_ok=True)
dataset = dataset.rename_files(
lambda key: os.path.
relpath(str(old_path.parent / key), start=str(new_path.parent))
)
with new_path.open('w') as fp:
yaml.dump(asjsonld(dataset), fp, default_flow_style=False)
old_path.unlink()
LinkReference.create(client=client,
name='datasets/' + name).set_reference(new_path) | python | def datasets(ctx, client):
from renku.models._jsonld import asjsonld
from renku.models.datasets import Dataset
from renku.models.refs import LinkReference
from ._checks.location_datasets import _dataset_metadata_pre_0_3_4
for old_path in _dataset_metadata_pre_0_3_4(client):
with old_path.open('r') as fp:
dataset = Dataset.from_jsonld(yaml.safe_load(fp))
name = str(old_path.parent.relative_to(client.path / 'data'))
new_path = (
client.renku_datasets_path / dataset.identifier.hex /
client.METADATA
)
new_path.parent.mkdir(parents=True, exist_ok=True)
dataset = dataset.rename_files(
lambda key: os.path.
relpath(str(old_path.parent / key), start=str(new_path.parent))
)
with new_path.open('w') as fp:
yaml.dump(asjsonld(dataset), fp, default_flow_style=False)
old_path.unlink()
LinkReference.create(client=client,
name='datasets/' + name).set_reference(new_path) | [
"def",
"datasets",
"(",
"ctx",
",",
"client",
")",
":",
"from",
"renku",
".",
"models",
".",
"_jsonld",
"import",
"asjsonld",
"from",
"renku",
".",
"models",
".",
"datasets",
"import",
"Dataset",
"from",
"renku",
".",
"models",
".",
"refs",
"import",
"Li... | Migrate dataset metadata. | [
"Migrate",
"dataset",
"metadata",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/migrate.py#L45-L75 |
15,225 | SwissDataScienceCenter/renku-python | renku/cli/_docker.py | detect_registry_url | def detect_registry_url(client, auto_login=True):
"""Return a URL of the Docker registry."""
repo = client.repo
config = repo.config_reader()
# Find registry URL in .git/config
remote_url = None
try:
registry_url = config.get_value('renku', 'registry', None)
except NoSectionError:
registry_url = None
remote_branch = repo.head.reference.tracking_branch()
if remote_branch is not None:
remote_name = remote_branch.remote_name
config_section = 'renku "{remote_name}"'.format(
remote_name=remote_name
)
try:
registry_url = config.get_value(
config_section, 'registry', registry_url
)
except NoSectionError:
pass
remote_url = repo.remotes[remote_name].url
if registry_url:
# Look in [renku] and [renku "{remote_name}"] for registry_url key.
url = GitURL.parse(registry_url)
elif remote_url:
# Use URL based on remote configuration.
url = GitURL.parse(remote_url)
# Replace gitlab. with registry. unless running on gitlab.com.
hostname_parts = url.hostname.split('.')
if len(hostname_parts) > 2 and hostname_parts[0] == 'gitlab':
hostname_parts = hostname_parts[1:]
hostname = '.'.join(['registry'] + hostname_parts)
url = attr.evolve(url, hostname=hostname)
else:
raise errors.ConfigurationError(
'Configure renku.repository_url or Git remote.'
)
if auto_login and url.username and url.password:
try:
subprocess.run([
'docker',
'login',
url.hostname,
'-u',
url.username,
'--password-stdin',
],
check=True,
input=url.password.encode('utf-8'))
except subprocess.CalledProcessError:
raise errors.AuthenticationError(
'Check configuration of password or token in the registry URL'
)
return url | python | def detect_registry_url(client, auto_login=True):
repo = client.repo
config = repo.config_reader()
# Find registry URL in .git/config
remote_url = None
try:
registry_url = config.get_value('renku', 'registry', None)
except NoSectionError:
registry_url = None
remote_branch = repo.head.reference.tracking_branch()
if remote_branch is not None:
remote_name = remote_branch.remote_name
config_section = 'renku "{remote_name}"'.format(
remote_name=remote_name
)
try:
registry_url = config.get_value(
config_section, 'registry', registry_url
)
except NoSectionError:
pass
remote_url = repo.remotes[remote_name].url
if registry_url:
# Look in [renku] and [renku "{remote_name}"] for registry_url key.
url = GitURL.parse(registry_url)
elif remote_url:
# Use URL based on remote configuration.
url = GitURL.parse(remote_url)
# Replace gitlab. with registry. unless running on gitlab.com.
hostname_parts = url.hostname.split('.')
if len(hostname_parts) > 2 and hostname_parts[0] == 'gitlab':
hostname_parts = hostname_parts[1:]
hostname = '.'.join(['registry'] + hostname_parts)
url = attr.evolve(url, hostname=hostname)
else:
raise errors.ConfigurationError(
'Configure renku.repository_url or Git remote.'
)
if auto_login and url.username and url.password:
try:
subprocess.run([
'docker',
'login',
url.hostname,
'-u',
url.username,
'--password-stdin',
],
check=True,
input=url.password.encode('utf-8'))
except subprocess.CalledProcessError:
raise errors.AuthenticationError(
'Check configuration of password or token in the registry URL'
)
return url | [
"def",
"detect_registry_url",
"(",
"client",
",",
"auto_login",
"=",
"True",
")",
":",
"repo",
"=",
"client",
".",
"repo",
"config",
"=",
"repo",
".",
"config_reader",
"(",
")",
"# Find registry URL in .git/config",
"remote_url",
"=",
"None",
"try",
":",
"regi... | Return a URL of the Docker registry. | [
"Return",
"a",
"URL",
"of",
"the",
"Docker",
"registry",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_docker.py#L29-L91 |
15,226 | SwissDataScienceCenter/renku-python | renku/models/_json.py | JSONEncoder.default | def default(self, obj):
"""Encode more types."""
if isinstance(obj, UUID):
return obj.hex
elif isinstance(obj, datetime.datetime):
return obj.isoformat()
return super().default(obj) | python | def default(self, obj):
if isinstance(obj, UUID):
return obj.hex
elif isinstance(obj, datetime.datetime):
return obj.isoformat()
return super().default(obj) | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"UUID",
")",
":",
"return",
"obj",
".",
"hex",
"elif",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"obj",
".",
"isoformat",
... | Encode more types. | [
"Encode",
"more",
"types",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_json.py#L29-L36 |
15,227 | SwissDataScienceCenter/renku-python | renku/cli/run.py | run | def run(client, outputs, no_output, success_codes, isolation, command_line):
"""Tracking work on a specific problem."""
working_dir = client.repo.working_dir
mapped_std = _mapped_std_streams(client.candidate_paths)
factory = CommandLineToolFactory(
command_line=command_line,
directory=os.getcwd(),
working_dir=working_dir,
successCodes=success_codes,
**{
name: os.path.relpath(path, working_dir)
for name, path in mapped_std.items()
}
)
with client.with_workflow_storage() as wf:
with factory.watch(
client, no_output=no_output, outputs=outputs
) as tool:
# Make sure all inputs are pulled from a storage.
client.pull_paths_from_storage(
*(
path
for _, path in tool.iter_input_files(client.workflow_path)
)
)
returncode = call(
factory.command_line,
cwd=os.getcwd(),
**{key: getattr(sys, key)
for key in mapped_std.keys()},
)
if returncode not in (success_codes or {0}):
raise errors.InvalidSuccessCode(
returncode, success_codes=success_codes
)
sys.stdout.flush()
sys.stderr.flush()
wf.add_step(run=tool) | python | def run(client, outputs, no_output, success_codes, isolation, command_line):
working_dir = client.repo.working_dir
mapped_std = _mapped_std_streams(client.candidate_paths)
factory = CommandLineToolFactory(
command_line=command_line,
directory=os.getcwd(),
working_dir=working_dir,
successCodes=success_codes,
**{
name: os.path.relpath(path, working_dir)
for name, path in mapped_std.items()
}
)
with client.with_workflow_storage() as wf:
with factory.watch(
client, no_output=no_output, outputs=outputs
) as tool:
# Make sure all inputs are pulled from a storage.
client.pull_paths_from_storage(
*(
path
for _, path in tool.iter_input_files(client.workflow_path)
)
)
returncode = call(
factory.command_line,
cwd=os.getcwd(),
**{key: getattr(sys, key)
for key in mapped_std.keys()},
)
if returncode not in (success_codes or {0}):
raise errors.InvalidSuccessCode(
returncode, success_codes=success_codes
)
sys.stdout.flush()
sys.stderr.flush()
wf.add_step(run=tool) | [
"def",
"run",
"(",
"client",
",",
"outputs",
",",
"no_output",
",",
"success_codes",
",",
"isolation",
",",
"command_line",
")",
":",
"working_dir",
"=",
"client",
".",
"repo",
".",
"working_dir",
"mapped_std",
"=",
"_mapped_std_streams",
"(",
"client",
".",
... | Tracking work on a specific problem. | [
"Tracking",
"work",
"on",
"a",
"specific",
"problem",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/run.py#L164-L206 |
15,228 | SwissDataScienceCenter/renku-python | renku/cli/log.py | log | def log(client, revision, format, no_output, paths):
"""Show logs for a file."""
graph = Graph(client)
if not paths:
start, is_range, stop = revision.partition('..')
if not is_range:
stop = start
elif not stop:
stop = 'HEAD'
commit = client.repo.rev_parse(stop)
paths = (
str(client.path / item.a_path)
for item in commit.diff(commit.parents or NULL_TREE)
# if not item.deleted_file
)
# NOTE shall we warn when "not no_output and not paths"?
graph.build(paths=paths, revision=revision, can_be_cwl=no_output)
FORMATS[format](graph) | python | def log(client, revision, format, no_output, paths):
graph = Graph(client)
if not paths:
start, is_range, stop = revision.partition('..')
if not is_range:
stop = start
elif not stop:
stop = 'HEAD'
commit = client.repo.rev_parse(stop)
paths = (
str(client.path / item.a_path)
for item in commit.diff(commit.parents or NULL_TREE)
# if not item.deleted_file
)
# NOTE shall we warn when "not no_output and not paths"?
graph.build(paths=paths, revision=revision, can_be_cwl=no_output)
FORMATS[format](graph) | [
"def",
"log",
"(",
"client",
",",
"revision",
",",
"format",
",",
"no_output",
",",
"paths",
")",
":",
"graph",
"=",
"Graph",
"(",
"client",
")",
"if",
"not",
"paths",
":",
"start",
",",
"is_range",
",",
"stop",
"=",
"revision",
".",
"partition",
"("... | Show logs for a file. | [
"Show",
"logs",
"for",
"a",
"file",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/log.py#L91-L111 |
15,229 | SwissDataScienceCenter/renku-python | renku/cli/status.py | status | def status(ctx, client, revision, no_output, path):
"""Show a status of the repository."""
graph = Graph(client)
# TODO filter only paths = {graph.normalize_path(p) for p in path}
status = graph.build_status(revision=revision, can_be_cwl=no_output)
click.echo('On branch {0}'.format(client.repo.active_branch))
if status['outdated']:
click.echo(
'Files generated from newer inputs:\n'
' (use "renku log [<file>...]" to see the full lineage)\n'
' (use "renku update [<file>...]" to '
'generate the file from its latest inputs)\n'
)
for filepath, stts in sorted(status['outdated'].items()):
outdated = (
', '.join(
'{0}#{1}'.format(
click.style(
graph._format_path(n.path), fg='blue', bold=True
),
_format_sha1(graph, n),
) for n in stts
if n.path and n.path not in status['outdated']
)
)
click.echo(
'\t{0}: {1}'.format(
click.style(
graph._format_path(filepath), fg='red', bold=True
), outdated
)
)
click.echo()
else:
click.secho(
'All files were generated from the latest inputs.', fg='green'
)
if status['multiple-versions']:
click.echo(
'Input files used in different versions:\n'
' (use "renku log --revision <sha1> <file>" to see a lineage '
'for the given revision)\n'
)
for filepath, files in sorted(status['multiple-versions'].items()):
# Do not show duplicated commits! (see #387)
commits = {_format_sha1(graph, key) for key in files}
click.echo(
'\t{0}: {1}'.format(
click.style(
graph._format_path(filepath), fg='blue', bold=True
), ', '.join(commits)
)
)
click.echo()
if status['deleted']:
click.echo(
'Deleted files used to generate outputs:\n'
' (use "git show <sha1>:<file>" to see the file content '
'for the given revision)\n'
)
for filepath, node in status['deleted'].items():
click.echo(
'\t{0}: {1}'.format(
click.style(
graph._format_path(filepath), fg='blue', bold=True
), _format_sha1(graph, node)
)
)
click.echo()
ctx.exit(1 if status['outdated'] else 0) | python | def status(ctx, client, revision, no_output, path):
graph = Graph(client)
# TODO filter only paths = {graph.normalize_path(p) for p in path}
status = graph.build_status(revision=revision, can_be_cwl=no_output)
click.echo('On branch {0}'.format(client.repo.active_branch))
if status['outdated']:
click.echo(
'Files generated from newer inputs:\n'
' (use "renku log [<file>...]" to see the full lineage)\n'
' (use "renku update [<file>...]" to '
'generate the file from its latest inputs)\n'
)
for filepath, stts in sorted(status['outdated'].items()):
outdated = (
', '.join(
'{0}#{1}'.format(
click.style(
graph._format_path(n.path), fg='blue', bold=True
),
_format_sha1(graph, n),
) for n in stts
if n.path and n.path not in status['outdated']
)
)
click.echo(
'\t{0}: {1}'.format(
click.style(
graph._format_path(filepath), fg='red', bold=True
), outdated
)
)
click.echo()
else:
click.secho(
'All files were generated from the latest inputs.', fg='green'
)
if status['multiple-versions']:
click.echo(
'Input files used in different versions:\n'
' (use "renku log --revision <sha1> <file>" to see a lineage '
'for the given revision)\n'
)
for filepath, files in sorted(status['multiple-versions'].items()):
# Do not show duplicated commits! (see #387)
commits = {_format_sha1(graph, key) for key in files}
click.echo(
'\t{0}: {1}'.format(
click.style(
graph._format_path(filepath), fg='blue', bold=True
), ', '.join(commits)
)
)
click.echo()
if status['deleted']:
click.echo(
'Deleted files used to generate outputs:\n'
' (use "git show <sha1>:<file>" to see the file content '
'for the given revision)\n'
)
for filepath, node in status['deleted'].items():
click.echo(
'\t{0}: {1}'.format(
click.style(
graph._format_path(filepath), fg='blue', bold=True
), _format_sha1(graph, node)
)
)
click.echo()
ctx.exit(1 if status['outdated'] else 0) | [
"def",
"status",
"(",
"ctx",
",",
"client",
",",
"revision",
",",
"no_output",
",",
"path",
")",
":",
"graph",
"=",
"Graph",
"(",
"client",
")",
"# TODO filter only paths = {graph.normalize_path(p) for p in path}",
"status",
"=",
"graph",
".",
"build_status",
"(",... | Show a status of the repository. | [
"Show",
"a",
"status",
"of",
"the",
"repository",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/status.py#L59-L140 |
15,230 | SwissDataScienceCenter/renku-python | renku/cli/init.py | validate_name | def validate_name(ctx, param, value):
"""Validate a project name."""
if not value:
value = os.path.basename(ctx.params['directory'].rstrip(os.path.sep))
return value | python | def validate_name(ctx, param, value):
if not value:
value = os.path.basename(ctx.params['directory'].rstrip(os.path.sep))
return value | [
"def",
"validate_name",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"value",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"ctx",
".",
"params",
"[",
"'directory'",
"]",
".",
"rstrip",
"(",
"os",
".",
"path",
".",
... | Validate a project name. | [
"Validate",
"a",
"project",
"name",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/init.py#L80-L84 |
15,231 | SwissDataScienceCenter/renku-python | renku/cli/init.py | store_directory | def store_directory(ctx, param, value):
"""Store directory as a new Git home."""
Path(value).mkdir(parents=True, exist_ok=True)
set_git_home(value)
return value | python | def store_directory(ctx, param, value):
Path(value).mkdir(parents=True, exist_ok=True)
set_git_home(value)
return value | [
"def",
"store_directory",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"Path",
"(",
"value",
")",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"set_git_home",
"(",
"value",
")",
"return",
"value"
] | Store directory as a new Git home. | [
"Store",
"directory",
"as",
"a",
"new",
"Git",
"home",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/init.py#L87-L91 |
15,232 | SwissDataScienceCenter/renku-python | renku/cli/init.py | init | def init(ctx, client, directory, name, force, use_external_storage):
"""Initialize a project."""
if not client.use_external_storage:
use_external_storage = False
ctx.obj = client = attr.evolve(
client,
path=directory,
use_external_storage=use_external_storage,
)
msg = 'Initialized empty project in {path}'
branch_name = None
stack = contextlib.ExitStack()
if force and client.repo:
msg = 'Initialized project in {path} (branch {branch_name})'
merge_args = ['--no-ff', '-s', 'recursive', '-X', 'ours']
try:
commit = client.find_previous_commit(
str(client.renku_metadata_path),
)
branch_name = 'renku/init/' + str(commit)
except KeyError:
from git import NULL_TREE
commit = NULL_TREE
branch_name = 'renku/init/root'
merge_args.append('--allow-unrelated-histories')
ctx.obj = client = stack.enter_context(
client.worktree(
branch_name=branch_name,
commit=commit,
merge_args=merge_args,
)
)
try:
with client.lock:
path = client.init_repository(name=name, force=force)
except FileExistsError:
raise click.UsageError(
'Renku repository is not empty. '
'Please use --force flag to use the directory as Renku '
'repository.'
)
stack.enter_context(client.commit())
with stack:
# Install Git hooks.
from .githooks import install
ctx.invoke(install, force=force)
# Create all necessary template files.
from .runner import template
ctx.invoke(template, force=force)
click.echo(msg.format(path=path, branch_name=branch_name)) | python | def init(ctx, client, directory, name, force, use_external_storage):
if not client.use_external_storage:
use_external_storage = False
ctx.obj = client = attr.evolve(
client,
path=directory,
use_external_storage=use_external_storage,
)
msg = 'Initialized empty project in {path}'
branch_name = None
stack = contextlib.ExitStack()
if force and client.repo:
msg = 'Initialized project in {path} (branch {branch_name})'
merge_args = ['--no-ff', '-s', 'recursive', '-X', 'ours']
try:
commit = client.find_previous_commit(
str(client.renku_metadata_path),
)
branch_name = 'renku/init/' + str(commit)
except KeyError:
from git import NULL_TREE
commit = NULL_TREE
branch_name = 'renku/init/root'
merge_args.append('--allow-unrelated-histories')
ctx.obj = client = stack.enter_context(
client.worktree(
branch_name=branch_name,
commit=commit,
merge_args=merge_args,
)
)
try:
with client.lock:
path = client.init_repository(name=name, force=force)
except FileExistsError:
raise click.UsageError(
'Renku repository is not empty. '
'Please use --force flag to use the directory as Renku '
'repository.'
)
stack.enter_context(client.commit())
with stack:
# Install Git hooks.
from .githooks import install
ctx.invoke(install, force=force)
# Create all necessary template files.
from .runner import template
ctx.invoke(template, force=force)
click.echo(msg.format(path=path, branch_name=branch_name)) | [
"def",
"init",
"(",
"ctx",
",",
"client",
",",
"directory",
",",
"name",
",",
"force",
",",
"use_external_storage",
")",
":",
"if",
"not",
"client",
".",
"use_external_storage",
":",
"use_external_storage",
"=",
"False",
"ctx",
".",
"obj",
"=",
"client",
"... | Initialize a project. | [
"Initialize",
"a",
"project",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/init.py#L106-L166 |
15,233 | SwissDataScienceCenter/renku-python | renku/cli/_checks/files_in_datasets.py | check_missing_files | def check_missing_files(client):
"""Find missing files listed in datasets."""
missing = defaultdict(list)
for path, dataset in client.datasets.items():
for file in dataset.files:
filepath = (path.parent / file)
if not filepath.exists():
missing[str(
path.parent.relative_to(client.renku_datasets_path)
)].append(
os.path.normpath(str(filepath.relative_to(client.path)))
)
if not missing:
return True
click.secho(
WARNING + 'There are missing files in datasets.'
# '\n (use "renku dataset clean <name>" to clean them)'
)
for dataset, files in missing.items():
click.secho(
'\n\t' + click.style(dataset, fg='yellow') + ':\n\t ' +
'\n\t '.join(click.style(path, fg='red') for path in files)
)
return False | python | def check_missing_files(client):
missing = defaultdict(list)
for path, dataset in client.datasets.items():
for file in dataset.files:
filepath = (path.parent / file)
if not filepath.exists():
missing[str(
path.parent.relative_to(client.renku_datasets_path)
)].append(
os.path.normpath(str(filepath.relative_to(client.path)))
)
if not missing:
return True
click.secho(
WARNING + 'There are missing files in datasets.'
# '\n (use "renku dataset clean <name>" to clean them)'
)
for dataset, files in missing.items():
click.secho(
'\n\t' + click.style(dataset, fg='yellow') + ':\n\t ' +
'\n\t '.join(click.style(path, fg='red') for path in files)
)
return False | [
"def",
"check_missing_files",
"(",
"client",
")",
":",
"missing",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"path",
",",
"dataset",
"in",
"client",
".",
"datasets",
".",
"items",
"(",
")",
":",
"for",
"file",
"in",
"dataset",
".",
"files",
":",
"fil... | Find missing files listed in datasets. | [
"Find",
"missing",
"files",
"listed",
"in",
"datasets",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_checks/files_in_datasets.py#L28-L56 |
15,234 | SwissDataScienceCenter/renku-python | renku/errors.py | APIError.from_http_exception | def from_http_exception(cls, e):
"""Create ``APIError`` from ``requests.exception.HTTPError``."""
assert isinstance(e, requests.exceptions.HTTPError)
response = e.response
try:
message = response.json()['message']
except (KeyError, ValueError):
message = response.content.strip()
raise cls(message) | python | def from_http_exception(cls, e):
assert isinstance(e, requests.exceptions.HTTPError)
response = e.response
try:
message = response.json()['message']
except (KeyError, ValueError):
message = response.content.strip()
raise cls(message) | [
"def",
"from_http_exception",
"(",
"cls",
",",
"e",
")",
":",
"assert",
"isinstance",
"(",
"e",
",",
"requests",
".",
"exceptions",
".",
"HTTPError",
")",
"response",
"=",
"e",
".",
"response",
"try",
":",
"message",
"=",
"response",
".",
"json",
"(",
... | Create ``APIError`` from ``requests.exception.HTTPError``. | [
"Create",
"APIError",
"from",
"requests",
".",
"exception",
".",
"HTTPError",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/errors.py#L38-L47 |
15,235 | SwissDataScienceCenter/renku-python | renku/errors.py | UnexpectedStatusCode.return_or_raise | def return_or_raise(cls, response, expected_status_code):
"""Check for ``expected_status_code``."""
try:
if response.status_code in expected_status_code:
return response
except TypeError:
if response.status_code == expected_status_code:
return response
raise cls(response) | python | def return_or_raise(cls, response, expected_status_code):
try:
if response.status_code in expected_status_code:
return response
except TypeError:
if response.status_code == expected_status_code:
return response
raise cls(response) | [
"def",
"return_or_raise",
"(",
"cls",
",",
"response",
",",
"expected_status_code",
")",
":",
"try",
":",
"if",
"response",
".",
"status_code",
"in",
"expected_status_code",
":",
"return",
"response",
"except",
"TypeError",
":",
"if",
"response",
".",
"status_co... | Check for ``expected_status_code``. | [
"Check",
"for",
"expected_status_code",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/errors.py#L61-L70 |
15,236 | SwissDataScienceCenter/renku-python | renku/cli/_checks/references.py | check_missing_references | def check_missing_references(client):
"""Find missing references."""
from renku.models.refs import LinkReference
missing = [
ref for ref in LinkReference.iter_items(client)
if not ref.reference.exists()
]
if not missing:
return True
click.secho(
WARNING + 'There are missing references.'
'\n (use "git rm <name>" to clean them)\n\n\t' + '\n\t '.join(
click.style(str(ref.path), fg='yellow') + ' -> ' +
click.style(str(ref.reference), fg='red') for ref in missing
) + '\n'
)
return False | python | def check_missing_references(client):
from renku.models.refs import LinkReference
missing = [
ref for ref in LinkReference.iter_items(client)
if not ref.reference.exists()
]
if not missing:
return True
click.secho(
WARNING + 'There are missing references.'
'\n (use "git rm <name>" to clean them)\n\n\t' + '\n\t '.join(
click.style(str(ref.path), fg='yellow') + ' -> ' +
click.style(str(ref.reference), fg='red') for ref in missing
) + '\n'
)
return False | [
"def",
"check_missing_references",
"(",
"client",
")",
":",
"from",
"renku",
".",
"models",
".",
"refs",
"import",
"LinkReference",
"missing",
"=",
"[",
"ref",
"for",
"ref",
"in",
"LinkReference",
".",
"iter_items",
"(",
"client",
")",
"if",
"not",
"ref",
... | Find missing references. | [
"Find",
"missing",
"references",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_checks/references.py#L25-L44 |
15,237 | SwissDataScienceCenter/renku-python | renku/cli/_git.py | get_git_home | def get_git_home(path='.'):
"""Get Git path from the current context."""
ctx = click.get_current_context(silent=True)
if ctx and GIT_KEY in ctx.meta:
return ctx.meta[GIT_KEY]
from git import Repo
return Repo(path, search_parent_directories=True).working_dir | python | def get_git_home(path='.'):
ctx = click.get_current_context(silent=True)
if ctx and GIT_KEY in ctx.meta:
return ctx.meta[GIT_KEY]
from git import Repo
return Repo(path, search_parent_directories=True).working_dir | [
"def",
"get_git_home",
"(",
"path",
"=",
"'.'",
")",
":",
"ctx",
"=",
"click",
".",
"get_current_context",
"(",
"silent",
"=",
"True",
")",
"if",
"ctx",
"and",
"GIT_KEY",
"in",
"ctx",
".",
"meta",
":",
"return",
"ctx",
".",
"meta",
"[",
"GIT_KEY",
"]... | Get Git path from the current context. | [
"Get",
"Git",
"path",
"from",
"the",
"current",
"context",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_git.py#L32-L39 |
15,238 | SwissDataScienceCenter/renku-python | renku/cli/_git.py | get_git_isolation | def get_git_isolation():
"""Get Git isolation from the current context."""
ctx = click.get_current_context(silent=True)
if ctx and GIT_ISOLATION in ctx.meta:
return ctx.meta[GIT_ISOLATION] | python | def get_git_isolation():
ctx = click.get_current_context(silent=True)
if ctx and GIT_ISOLATION in ctx.meta:
return ctx.meta[GIT_ISOLATION] | [
"def",
"get_git_isolation",
"(",
")",
":",
"ctx",
"=",
"click",
".",
"get_current_context",
"(",
"silent",
"=",
"True",
")",
"if",
"ctx",
"and",
"GIT_ISOLATION",
"in",
"ctx",
".",
"meta",
":",
"return",
"ctx",
".",
"meta",
"[",
"GIT_ISOLATION",
"]"
] | Get Git isolation from the current context. | [
"Get",
"Git",
"isolation",
"from",
"the",
"current",
"context",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_git.py#L48-L52 |
15,239 | SwissDataScienceCenter/renku-python | renku/cli/_git.py | _safe_issue_checkout | def _safe_issue_checkout(repo, issue=None):
"""Safely checkout branch for the issue."""
branch_name = str(issue) if issue else 'master'
if branch_name not in repo.heads:
branch = repo.create_head(branch_name)
else:
branch = repo.heads[branch_name]
branch.checkout() | python | def _safe_issue_checkout(repo, issue=None):
branch_name = str(issue) if issue else 'master'
if branch_name not in repo.heads:
branch = repo.create_head(branch_name)
else:
branch = repo.heads[branch_name]
branch.checkout() | [
"def",
"_safe_issue_checkout",
"(",
"repo",
",",
"issue",
"=",
"None",
")",
":",
"branch_name",
"=",
"str",
"(",
"issue",
")",
"if",
"issue",
"else",
"'master'",
"if",
"branch_name",
"not",
"in",
"repo",
".",
"heads",
":",
"branch",
"=",
"repo",
".",
"... | Safely checkout branch for the issue. | [
"Safely",
"checkout",
"branch",
"for",
"the",
"issue",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_git.py#L55-L62 |
15,240 | SwissDataScienceCenter/renku-python | renku/models/_jsonld.py | attrib | def attrib(context=None, **kwargs):
"""Create a new attribute with context."""
kwargs.setdefault('metadata', {})
kwargs['metadata'][KEY] = context
return attr.ib(**kwargs) | python | def attrib(context=None, **kwargs):
kwargs.setdefault('metadata', {})
kwargs['metadata'][KEY] = context
return attr.ib(**kwargs) | [
"def",
"attrib",
"(",
"context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'metadata'",
",",
"{",
"}",
")",
"kwargs",
"[",
"'metadata'",
"]",
"[",
"KEY",
"]",
"=",
"context",
"return",
"attr",
".",
"ib",
"("... | Create a new attribute with context. | [
"Create",
"a",
"new",
"attribute",
"with",
"context",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_jsonld.py#L158-L162 |
15,241 | SwissDataScienceCenter/renku-python | renku/models/_jsonld.py | _container_attrib_builder | def _container_attrib_builder(name, container, mapper):
"""Builder for container attributes."""
context = {'@container': '@{0}'.format(name)}
def _attrib(type, **kwargs):
"""Define a container attribute."""
kwargs.setdefault('metadata', {})
kwargs['metadata'][KEY_CLS] = type
kwargs['default'] = Factory(container)
def _converter(value):
"""Convert value to the given type."""
if isinstance(value, container):
return mapper(type, value)
elif value is None:
return value
raise ValueError(value)
kwargs.setdefault('converter', _converter)
context_ib = context.copy()
context_ib.update(kwargs.pop('context', {}))
return attrib(context=context_ib, **kwargs)
return _attrib | python | def _container_attrib_builder(name, container, mapper):
context = {'@container': '@{0}'.format(name)}
def _attrib(type, **kwargs):
"""Define a container attribute."""
kwargs.setdefault('metadata', {})
kwargs['metadata'][KEY_CLS] = type
kwargs['default'] = Factory(container)
def _converter(value):
"""Convert value to the given type."""
if isinstance(value, container):
return mapper(type, value)
elif value is None:
return value
raise ValueError(value)
kwargs.setdefault('converter', _converter)
context_ib = context.copy()
context_ib.update(kwargs.pop('context', {}))
return attrib(context=context_ib, **kwargs)
return _attrib | [
"def",
"_container_attrib_builder",
"(",
"name",
",",
"container",
",",
"mapper",
")",
":",
"context",
"=",
"{",
"'@container'",
":",
"'@{0}'",
".",
"format",
"(",
"name",
")",
"}",
"def",
"_attrib",
"(",
"type",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\... | Builder for container attributes. | [
"Builder",
"for",
"container",
"attributes",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_jsonld.py#L177-L200 |
15,242 | SwissDataScienceCenter/renku-python | renku/models/_jsonld.py | asjsonld | def asjsonld(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
export_context=True,
basedir=None,
):
"""Dump a JSON-LD class to the JSON with generated ``@context`` field."""
jsonld_fields = inst.__class__._jsonld_fields
attrs = tuple(
field
for field in fields(inst.__class__) if field.name in jsonld_fields
)
rv = dict_factory()
def convert_value(v):
"""Convert special types."""
if isinstance(v, Path):
v = str(v)
return os.path.relpath(v, str(basedir)) if basedir else v
return v
for a in attrs:
v = getattr(inst, a.name)
# skip proxies
if isinstance(v, weakref.ReferenceType):
continue
# do not export context for containers
ec = export_context and KEY_CLS not in a.metadata
if filter is not None and not filter(a, v):
continue
if recurse is True:
if has(v.__class__):
rv[a.name] = asjsonld(
v,
recurse=True,
filter=filter,
dict_factory=dict_factory,
basedir=basedir,
)
elif isinstance(v, (tuple, list, set)):
cf = v.__class__ if retain_collection_types is True else list
rv[a.name] = cf([
asjsonld(
i,
recurse=True,
filter=filter,
dict_factory=dict_factory,
export_context=ec,
basedir=basedir,
) if has(i.__class__) else i for i in v
])
elif isinstance(v, dict):
df = dict_factory
rv[a.name] = df((
asjsonld(
kk,
dict_factory=df,
basedir=basedir,
) if has(kk.__class__) else convert_value(kk),
asjsonld(
vv,
dict_factory=df,
export_context=ec,
basedir=basedir,
) if has(vv.__class__) else vv
) for kk, vv in iteritems(v))
else:
rv[a.name] = convert_value(v)
else:
rv[a.name] = convert_value(v)
inst_cls = type(inst)
if export_context:
rv['@context'] = deepcopy(inst_cls._jsonld_context)
if inst_cls._jsonld_type:
rv['@type'] = inst_cls._jsonld_type
return rv | python | def asjsonld(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
export_context=True,
basedir=None,
):
jsonld_fields = inst.__class__._jsonld_fields
attrs = tuple(
field
for field in fields(inst.__class__) if field.name in jsonld_fields
)
rv = dict_factory()
def convert_value(v):
"""Convert special types."""
if isinstance(v, Path):
v = str(v)
return os.path.relpath(v, str(basedir)) if basedir else v
return v
for a in attrs:
v = getattr(inst, a.name)
# skip proxies
if isinstance(v, weakref.ReferenceType):
continue
# do not export context for containers
ec = export_context and KEY_CLS not in a.metadata
if filter is not None and not filter(a, v):
continue
if recurse is True:
if has(v.__class__):
rv[a.name] = asjsonld(
v,
recurse=True,
filter=filter,
dict_factory=dict_factory,
basedir=basedir,
)
elif isinstance(v, (tuple, list, set)):
cf = v.__class__ if retain_collection_types is True else list
rv[a.name] = cf([
asjsonld(
i,
recurse=True,
filter=filter,
dict_factory=dict_factory,
export_context=ec,
basedir=basedir,
) if has(i.__class__) else i for i in v
])
elif isinstance(v, dict):
df = dict_factory
rv[a.name] = df((
asjsonld(
kk,
dict_factory=df,
basedir=basedir,
) if has(kk.__class__) else convert_value(kk),
asjsonld(
vv,
dict_factory=df,
export_context=ec,
basedir=basedir,
) if has(vv.__class__) else vv
) for kk, vv in iteritems(v))
else:
rv[a.name] = convert_value(v)
else:
rv[a.name] = convert_value(v)
inst_cls = type(inst)
if export_context:
rv['@context'] = deepcopy(inst_cls._jsonld_context)
if inst_cls._jsonld_type:
rv['@type'] = inst_cls._jsonld_type
return rv | [
"def",
"asjsonld",
"(",
"inst",
",",
"recurse",
"=",
"True",
",",
"filter",
"=",
"None",
",",
"dict_factory",
"=",
"dict",
",",
"retain_collection_types",
"=",
"False",
",",
"export_context",
"=",
"True",
",",
"basedir",
"=",
"None",
",",
")",
":",
"json... | Dump a JSON-LD class to the JSON with generated ``@context`` field. | [
"Dump",
"a",
"JSON",
"-",
"LD",
"class",
"to",
"the",
"JSON",
"with",
"generated"
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_jsonld.py#L211-L295 |
15,243 | SwissDataScienceCenter/renku-python | renku/models/_jsonld.py | JSONLDMixin.from_jsonld | def from_jsonld(cls, data, __reference__=None, __source__=None):
"""Instantiate a JSON-LD class from data."""
if isinstance(data, cls):
return data
if not isinstance(data, dict):
raise ValueError(data)
if '@type' in data:
type_ = tuple(sorted(data['@type']))
if type_ in cls.__type_registry__ and getattr(
cls, '_jsonld_type', None
) != type_:
new_cls = cls.__type_registry__[type_]
if cls != new_cls:
return new_cls.from_jsonld(data)
if cls._jsonld_translate:
data = ld.compact(data, {'@context': cls._jsonld_translate})
data.pop('@context', None)
data.setdefault('@context', cls._jsonld_context)
if data['@context'] != cls._jsonld_context:
compacted = ld.compact(data, {'@context': cls._jsonld_context})
else:
compacted = data
# assert compacted['@type'] == cls._jsonld_type, '@type must be equal'
# TODO update self(not cls)._jsonld_context with data['@context']
fields = cls._jsonld_fields
if __reference__:
with with_reference(__reference__):
self = cls(
**{
k.lstrip('_'): v
for k, v in compacted.items() if k in fields
}
)
else:
self = cls(
**{
k.lstrip('_'): v
for k, v in compacted.items() if k in fields
}
)
if __source__:
setattr(self, '__source__', __source__)
return self | python | def from_jsonld(cls, data, __reference__=None, __source__=None):
if isinstance(data, cls):
return data
if not isinstance(data, dict):
raise ValueError(data)
if '@type' in data:
type_ = tuple(sorted(data['@type']))
if type_ in cls.__type_registry__ and getattr(
cls, '_jsonld_type', None
) != type_:
new_cls = cls.__type_registry__[type_]
if cls != new_cls:
return new_cls.from_jsonld(data)
if cls._jsonld_translate:
data = ld.compact(data, {'@context': cls._jsonld_translate})
data.pop('@context', None)
data.setdefault('@context', cls._jsonld_context)
if data['@context'] != cls._jsonld_context:
compacted = ld.compact(data, {'@context': cls._jsonld_context})
else:
compacted = data
# assert compacted['@type'] == cls._jsonld_type, '@type must be equal'
# TODO update self(not cls)._jsonld_context with data['@context']
fields = cls._jsonld_fields
if __reference__:
with with_reference(__reference__):
self = cls(
**{
k.lstrip('_'): v
for k, v in compacted.items() if k in fields
}
)
else:
self = cls(
**{
k.lstrip('_'): v
for k, v in compacted.items() if k in fields
}
)
if __source__:
setattr(self, '__source__', __source__)
return self | [
"def",
"from_jsonld",
"(",
"cls",
",",
"data",
",",
"__reference__",
"=",
"None",
",",
"__source__",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"cls",
")",
":",
"return",
"data",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
... | Instantiate a JSON-LD class from data. | [
"Instantiate",
"a",
"JSON",
"-",
"LD",
"class",
"from",
"data",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_jsonld.py#L304-L353 |
15,244 | SwissDataScienceCenter/renku-python | renku/models/_jsonld.py | JSONLDMixin.asjsonld | def asjsonld(self):
"""Create JSON-LD with the original source data."""
source = {}
if self.__source__:
source.update(self.__source__)
source.update(asjsonld(self))
return source | python | def asjsonld(self):
source = {}
if self.__source__:
source.update(self.__source__)
source.update(asjsonld(self))
return source | [
"def",
"asjsonld",
"(",
"self",
")",
":",
"source",
"=",
"{",
"}",
"if",
"self",
".",
"__source__",
":",
"source",
".",
"update",
"(",
"self",
".",
"__source__",
")",
"source",
".",
"update",
"(",
"asjsonld",
"(",
"self",
")",
")",
"return",
"source"... | Create JSON-LD with the original source data. | [
"Create",
"JSON",
"-",
"LD",
"with",
"the",
"original",
"source",
"data",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_jsonld.py#L370-L376 |
15,245 | SwissDataScienceCenter/renku-python | renku/models/_jsonld.py | JSONLDMixin.to_yaml | def to_yaml(self):
"""Store an instance to the referenced YAML file."""
import yaml
with self.__reference__.open('w') as fp:
yaml.dump(self.asjsonld(), fp, default_flow_style=False) | python | def to_yaml(self):
import yaml
with self.__reference__.open('w') as fp:
yaml.dump(self.asjsonld(), fp, default_flow_style=False) | [
"def",
"to_yaml",
"(",
"self",
")",
":",
"import",
"yaml",
"with",
"self",
".",
"__reference__",
".",
"open",
"(",
"'w'",
")",
"as",
"fp",
":",
"yaml",
".",
"dump",
"(",
"self",
".",
"asjsonld",
"(",
")",
",",
"fp",
",",
"default_flow_style",
"=",
... | Store an instance to the referenced YAML file. | [
"Store",
"an",
"instance",
"to",
"the",
"referenced",
"YAML",
"file",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_jsonld.py#L378-L383 |
15,246 | stephenmcd/django-email-extras | email_extras/utils.py | send_mail | def send_mail(subject, body_text, addr_from, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
attachments=None, body_html=None, html_message=None,
connection=None, headers=None):
"""
Sends a multipart email containing text and html versions which
are encrypted for each recipient that has a valid gpg key
installed.
"""
# Make sure only one HTML option is specified
if body_html is not None and html_message is not None: # pragma: no cover
raise ValueError("You cannot specify body_html and html_message at "
"the same time. Please only use html_message.")
# Push users to update their code
if body_html is not None: # pragma: no cover
warn("Using body_html is deprecated; use the html_message argument "
"instead. Please update your code.", DeprecationWarning)
html_message = body_html
# Allow for a single address to be passed in.
if isinstance(recipient_list, six.string_types):
recipient_list = [recipient_list]
connection = connection or get_connection(
username=auth_user, password=auth_password,
fail_silently=fail_silently)
# Obtain a list of the recipients that have gpg keys installed.
key_addresses = {}
if USE_GNUPG:
from email_extras.models import Address
key_addresses = dict(Address.objects.filter(address__in=recipient_list)
.values_list('address', 'use_asc'))
# Create the gpg object.
if key_addresses:
gpg = GPG(gnupghome=GNUPG_HOME)
if GNUPG_ENCODING is not None:
gpg.encoding = GNUPG_ENCODING
# Check if recipient has a gpg key installed
def has_pgp_key(addr):
return addr in key_addresses
# Encrypts body if recipient has a gpg key installed.
def encrypt_if_key(body, addr_list):
if has_pgp_key(addr_list[0]):
encrypted = gpg.encrypt(body, addr_list[0],
always_trust=ALWAYS_TRUST)
if encrypted == "" and body != "": # encryption failed
raise EncryptionFailedError("Encrypting mail to %s failed.",
addr_list[0])
return smart_text(encrypted)
return body
# Load attachments and create name/data tuples.
attachments_parts = []
if attachments is not None:
for attachment in attachments:
# Attachments can be pairs of name/data, or filesystem paths.
if not hasattr(attachment, "__iter__"):
with open(attachment, "rb") as f:
attachments_parts.append((basename(attachment), f.read()))
else:
attachments_parts.append(attachment)
# Send emails - encrypted emails needs to be sent individually, while
# non-encrypted emails can be sent in one send. So the final list of
# lists of addresses to send to looks like:
# [[unencrypted1, unencrypted2, unencrypted3], [encrypted1], [encrypted2]]
unencrypted = [addr for addr in recipient_list
if addr not in key_addresses]
unencrypted = [unencrypted] if unencrypted else unencrypted
encrypted = [[addr] for addr in key_addresses]
for addr_list in unencrypted + encrypted:
msg = EmailMultiAlternatives(subject,
encrypt_if_key(body_text, addr_list),
addr_from, addr_list,
connection=connection, headers=headers)
if html_message is not None:
if has_pgp_key(addr_list[0]):
mimetype = "application/gpg-encrypted"
else:
mimetype = "text/html"
msg.attach_alternative(encrypt_if_key(html_message, addr_list),
mimetype)
for parts in attachments_parts:
name = parts[0]
if key_addresses.get(addr_list[0]):
name += ".asc"
msg.attach(name, encrypt_if_key(parts[1], addr_list))
msg.send(fail_silently=fail_silently) | python | def send_mail(subject, body_text, addr_from, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
attachments=None, body_html=None, html_message=None,
connection=None, headers=None):
# Make sure only one HTML option is specified
if body_html is not None and html_message is not None: # pragma: no cover
raise ValueError("You cannot specify body_html and html_message at "
"the same time. Please only use html_message.")
# Push users to update their code
if body_html is not None: # pragma: no cover
warn("Using body_html is deprecated; use the html_message argument "
"instead. Please update your code.", DeprecationWarning)
html_message = body_html
# Allow for a single address to be passed in.
if isinstance(recipient_list, six.string_types):
recipient_list = [recipient_list]
connection = connection or get_connection(
username=auth_user, password=auth_password,
fail_silently=fail_silently)
# Obtain a list of the recipients that have gpg keys installed.
key_addresses = {}
if USE_GNUPG:
from email_extras.models import Address
key_addresses = dict(Address.objects.filter(address__in=recipient_list)
.values_list('address', 'use_asc'))
# Create the gpg object.
if key_addresses:
gpg = GPG(gnupghome=GNUPG_HOME)
if GNUPG_ENCODING is not None:
gpg.encoding = GNUPG_ENCODING
# Check if recipient has a gpg key installed
def has_pgp_key(addr):
return addr in key_addresses
# Encrypts body if recipient has a gpg key installed.
def encrypt_if_key(body, addr_list):
if has_pgp_key(addr_list[0]):
encrypted = gpg.encrypt(body, addr_list[0],
always_trust=ALWAYS_TRUST)
if encrypted == "" and body != "": # encryption failed
raise EncryptionFailedError("Encrypting mail to %s failed.",
addr_list[0])
return smart_text(encrypted)
return body
# Load attachments and create name/data tuples.
attachments_parts = []
if attachments is not None:
for attachment in attachments:
# Attachments can be pairs of name/data, or filesystem paths.
if not hasattr(attachment, "__iter__"):
with open(attachment, "rb") as f:
attachments_parts.append((basename(attachment), f.read()))
else:
attachments_parts.append(attachment)
# Send emails - encrypted emails needs to be sent individually, while
# non-encrypted emails can be sent in one send. So the final list of
# lists of addresses to send to looks like:
# [[unencrypted1, unencrypted2, unencrypted3], [encrypted1], [encrypted2]]
unencrypted = [addr for addr in recipient_list
if addr not in key_addresses]
unencrypted = [unencrypted] if unencrypted else unencrypted
encrypted = [[addr] for addr in key_addresses]
for addr_list in unencrypted + encrypted:
msg = EmailMultiAlternatives(subject,
encrypt_if_key(body_text, addr_list),
addr_from, addr_list,
connection=connection, headers=headers)
if html_message is not None:
if has_pgp_key(addr_list[0]):
mimetype = "application/gpg-encrypted"
else:
mimetype = "text/html"
msg.attach_alternative(encrypt_if_key(html_message, addr_list),
mimetype)
for parts in attachments_parts:
name = parts[0]
if key_addresses.get(addr_list[0]):
name += ".asc"
msg.attach(name, encrypt_if_key(parts[1], addr_list))
msg.send(fail_silently=fail_silently) | [
"def",
"send_mail",
"(",
"subject",
",",
"body_text",
",",
"addr_from",
",",
"recipient_list",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
",",
"attachments",
"=",
"None",
",",
"body_html",
"=",
"None... | Sends a multipart email containing text and html versions which
are encrypted for each recipient that has a valid gpg key
installed. | [
"Sends",
"a",
"multipart",
"email",
"containing",
"text",
"and",
"html",
"versions",
"which",
"are",
"encrypted",
"for",
"each",
"recipient",
"that",
"has",
"a",
"valid",
"gpg",
"key",
"installed",
"."
] | 8399792998cee84810be2b315dd9b51b200f9218 | https://github.com/stephenmcd/django-email-extras/blob/8399792998cee84810be2b315dd9b51b200f9218/email_extras/utils.py#L35-L127 |
15,247 | SwissDataScienceCenter/renku-python | renku/models/_sort.py | topological | def topological(nodes):
"""Return nodes in a topological order."""
order, enter, state = deque(), set(nodes), {}
def dfs(node):
"""Visit nodes in depth-first order."""
state[node] = GRAY
for parent in nodes.get(node, ()):
color = state.get(parent, None)
if color == GRAY:
raise ValueError('cycle')
if color == BLACK:
continue
enter.discard(parent)
dfs(parent)
order.appendleft(node)
state[node] = BLACK
while enter:
dfs(enter.pop())
return order | python | def topological(nodes):
order, enter, state = deque(), set(nodes), {}
def dfs(node):
"""Visit nodes in depth-first order."""
state[node] = GRAY
for parent in nodes.get(node, ()):
color = state.get(parent, None)
if color == GRAY:
raise ValueError('cycle')
if color == BLACK:
continue
enter.discard(parent)
dfs(parent)
order.appendleft(node)
state[node] = BLACK
while enter:
dfs(enter.pop())
return order | [
"def",
"topological",
"(",
"nodes",
")",
":",
"order",
",",
"enter",
",",
"state",
"=",
"deque",
"(",
")",
",",
"set",
"(",
"nodes",
")",
",",
"{",
"}",
"def",
"dfs",
"(",
"node",
")",
":",
"\"\"\"Visit nodes in depth-first order.\"\"\"",
"state",
"[",
... | Return nodes in a topological order. | [
"Return",
"nodes",
"in",
"a",
"topological",
"order",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_sort.py#L25-L46 |
15,248 | SwissDataScienceCenter/renku-python | renku/cli/_checks/location_datasets.py | check_dataset_metadata | def check_dataset_metadata(client):
"""Check location of dataset metadata."""
# Find pre 0.3.4 metadata files.
old_metadata = list(_dataset_metadata_pre_0_3_4(client))
if not old_metadata:
return True
click.secho(
WARNING + 'There are metadata files in the old location.'
'\n (use "renku migrate datasets" to move them)\n\n\t' + '\n\t'.join(
click.style(str(path.relative_to(client.path)), fg='yellow')
for path in old_metadata
) + '\n'
)
return False | python | def check_dataset_metadata(client):
# Find pre 0.3.4 metadata files.
old_metadata = list(_dataset_metadata_pre_0_3_4(client))
if not old_metadata:
return True
click.secho(
WARNING + 'There are metadata files in the old location.'
'\n (use "renku migrate datasets" to move them)\n\n\t' + '\n\t'.join(
click.style(str(path.relative_to(client.path)), fg='yellow')
for path in old_metadata
) + '\n'
)
return False | [
"def",
"check_dataset_metadata",
"(",
"client",
")",
":",
"# Find pre 0.3.4 metadata files.",
"old_metadata",
"=",
"list",
"(",
"_dataset_metadata_pre_0_3_4",
"(",
"client",
")",
")",
"if",
"not",
"old_metadata",
":",
"return",
"True",
"click",
".",
"secho",
"(",
... | Check location of dataset metadata. | [
"Check",
"location",
"of",
"dataset",
"metadata",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_checks/location_datasets.py#L30-L46 |
15,249 | SwissDataScienceCenter/renku-python | renku/cli/show.py | siblings | def siblings(client, revision, paths):
"""Show siblings for given paths."""
graph = Graph(client)
nodes = graph.build(paths=paths, revision=revision)
siblings_ = set(nodes)
for node in nodes:
siblings_ |= graph.siblings(node)
paths = {node.path for node in siblings_}
for path in paths:
click.echo(graph._format_path(path)) | python | def siblings(client, revision, paths):
graph = Graph(client)
nodes = graph.build(paths=paths, revision=revision)
siblings_ = set(nodes)
for node in nodes:
siblings_ |= graph.siblings(node)
paths = {node.path for node in siblings_}
for path in paths:
click.echo(graph._format_path(path)) | [
"def",
"siblings",
"(",
"client",
",",
"revision",
",",
"paths",
")",
":",
"graph",
"=",
"Graph",
"(",
"client",
")",
"nodes",
"=",
"graph",
".",
"build",
"(",
"paths",
"=",
"paths",
",",
"revision",
"=",
"revision",
")",
"siblings_",
"=",
"set",
"("... | Show siblings for given paths. | [
"Show",
"siblings",
"for",
"given",
"paths",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/show.py#L90-L100 |
15,250 | SwissDataScienceCenter/renku-python | renku/cli/show.py | inputs | def inputs(ctx, client, revision, paths):
r"""Show inputs files in the repository.
<PATHS> Files to show. If no files are given all input files are shown.
"""
from renku.models.provenance import ProcessRun
graph = Graph(client)
paths = set(paths)
nodes = graph.build(revision=revision)
commits = {node.commit for node in nodes}
candidates = {(node.commit, node.path)
for node in nodes if not paths or node.path in paths}
input_paths = set()
for commit in commits:
activity = graph.activities[commit]
if isinstance(activity, ProcessRun):
for usage in activity.qualified_usage:
for entity in usage.entity.entities:
path = str((usage.client.path / entity.path).relative_to(
client.path
))
usage_key = (entity.commit, entity.path)
if path not in input_paths and usage_key in candidates:
input_paths.add(path)
click.echo('\n'.join(graph._format_path(path) for path in input_paths))
ctx.exit(0 if not paths or len(input_paths) == len(paths) else 1) | python | def inputs(ctx, client, revision, paths):
r"""Show inputs files in the repository.
<PATHS> Files to show. If no files are given all input files are shown.
"""
from renku.models.provenance import ProcessRun
graph = Graph(client)
paths = set(paths)
nodes = graph.build(revision=revision)
commits = {node.commit for node in nodes}
candidates = {(node.commit, node.path)
for node in nodes if not paths or node.path in paths}
input_paths = set()
for commit in commits:
activity = graph.activities[commit]
if isinstance(activity, ProcessRun):
for usage in activity.qualified_usage:
for entity in usage.entity.entities:
path = str((usage.client.path / entity.path).relative_to(
client.path
))
usage_key = (entity.commit, entity.path)
if path not in input_paths and usage_key in candidates:
input_paths.add(path)
click.echo('\n'.join(graph._format_path(path) for path in input_paths))
ctx.exit(0 if not paths or len(input_paths) == len(paths) else 1) | [
"def",
"inputs",
"(",
"ctx",
",",
"client",
",",
"revision",
",",
"paths",
")",
":",
"from",
"renku",
".",
"models",
".",
"provenance",
"import",
"ProcessRun",
"graph",
"=",
"Graph",
"(",
"client",
")",
"paths",
"=",
"set",
"(",
"paths",
")",
"nodes",
... | r"""Show inputs files in the repository.
<PATHS> Files to show. If no files are given all input files are shown. | [
"r",
"Show",
"inputs",
"files",
"in",
"the",
"repository",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/show.py#L112-L144 |
15,251 | SwissDataScienceCenter/renku-python | renku/cli/show.py | outputs | def outputs(ctx, client, revision, paths):
r"""Show output files in the repository.
<PATHS> Files to show. If no files are given all output files are shown.
"""
graph = Graph(client)
filter = graph.build(paths=paths, revision=revision)
output_paths = graph.output_paths
click.echo('\n'.join(graph._format_path(path) for path in output_paths))
if paths:
if not output_paths:
ctx.exit(1)
from renku.models._datastructures import DirectoryTree
tree = DirectoryTree.from_list(item.path for item in filter)
for output in output_paths:
if tree.get(output) is None:
ctx.exit(1)
return | python | def outputs(ctx, client, revision, paths):
r"""Show output files in the repository.
<PATHS> Files to show. If no files are given all output files are shown.
"""
graph = Graph(client)
filter = graph.build(paths=paths, revision=revision)
output_paths = graph.output_paths
click.echo('\n'.join(graph._format_path(path) for path in output_paths))
if paths:
if not output_paths:
ctx.exit(1)
from renku.models._datastructures import DirectoryTree
tree = DirectoryTree.from_list(item.path for item in filter)
for output in output_paths:
if tree.get(output) is None:
ctx.exit(1)
return | [
"def",
"outputs",
"(",
"ctx",
",",
"client",
",",
"revision",
",",
"paths",
")",
":",
"graph",
"=",
"Graph",
"(",
"client",
")",
"filter",
"=",
"graph",
".",
"build",
"(",
"paths",
"=",
"paths",
",",
"revision",
"=",
"revision",
")",
"output_paths",
... | r"""Show output files in the repository.
<PATHS> Files to show. If no files are given all output files are shown. | [
"r",
"Show",
"output",
"files",
"in",
"the",
"repository",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/show.py#L156-L177 |
15,252 | SwissDataScienceCenter/renku-python | renku/cli/show.py | _context_names | def _context_names():
"""Return list of valid context names."""
import inspect
from renku.models import provenance
from renku.models._jsonld import JSONLDMixin
for name in dir(provenance):
cls = getattr(provenance, name)
if inspect.isclass(cls) and issubclass(cls, JSONLDMixin):
yield name | python | def _context_names():
import inspect
from renku.models import provenance
from renku.models._jsonld import JSONLDMixin
for name in dir(provenance):
cls = getattr(provenance, name)
if inspect.isclass(cls) and issubclass(cls, JSONLDMixin):
yield name | [
"def",
"_context_names",
"(",
")",
":",
"import",
"inspect",
"from",
"renku",
".",
"models",
"import",
"provenance",
"from",
"renku",
".",
"models",
".",
"_jsonld",
"import",
"JSONLDMixin",
"for",
"name",
"in",
"dir",
"(",
"provenance",
")",
":",
"cls",
"=... | Return list of valid context names. | [
"Return",
"list",
"of",
"valid",
"context",
"names",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/show.py#L180-L190 |
15,253 | SwissDataScienceCenter/renku-python | renku/cli/show.py | print_context_names | def print_context_names(ctx, param, value):
"""Print all possible types."""
if not value or ctx.resilient_parsing:
return
click.echo('\n'.join(_context_names()))
ctx.exit() | python | def print_context_names(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo('\n'.join(_context_names()))
ctx.exit() | [
"def",
"print_context_names",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"ctx",
".",
"resilient_parsing",
":",
"return",
"click",
".",
"echo",
"(",
"'\\n'",
".",
"join",
"(",
"_context_names",
"(",
")",
")",
")",
"ctx... | Print all possible types. | [
"Print",
"all",
"possible",
"types",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/show.py#L193-L198 |
15,254 | SwissDataScienceCenter/renku-python | renku/cli/show.py | _context_json | def _context_json(name):
"""Return JSON-LD string for given context name."""
from renku.models import provenance
cls = getattr(provenance, name)
return {
'@context': cls._jsonld_context,
'@type': cls._jsonld_type,
} | python | def _context_json(name):
from renku.models import provenance
cls = getattr(provenance, name)
return {
'@context': cls._jsonld_context,
'@type': cls._jsonld_type,
} | [
"def",
"_context_json",
"(",
"name",
")",
":",
"from",
"renku",
".",
"models",
"import",
"provenance",
"cls",
"=",
"getattr",
"(",
"provenance",
",",
"name",
")",
"return",
"{",
"'@context'",
":",
"cls",
".",
"_jsonld_context",
",",
"'@type'",
":",
"cls",
... | Return JSON-LD string for given context name. | [
"Return",
"JSON",
"-",
"LD",
"string",
"for",
"given",
"context",
"name",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/show.py#L201-L209 |
15,255 | SwissDataScienceCenter/renku-python | renku/cli/show.py | context | def context(names):
"""Show JSON-LD context for repository objects."""
import json
contexts = [_context_json(name) for name in set(names)]
if contexts:
click.echo(
json.dumps(
contexts[0] if len(contexts) == 1 else contexts,
indent=2,
)
) | python | def context(names):
import json
contexts = [_context_json(name) for name in set(names)]
if contexts:
click.echo(
json.dumps(
contexts[0] if len(contexts) == 1 else contexts,
indent=2,
)
) | [
"def",
"context",
"(",
"names",
")",
":",
"import",
"json",
"contexts",
"=",
"[",
"_context_json",
"(",
"name",
")",
"for",
"name",
"in",
"set",
"(",
"names",
")",
"]",
"if",
"contexts",
":",
"click",
".",
"echo",
"(",
"json",
".",
"dumps",
"(",
"c... | Show JSON-LD context for repository objects. | [
"Show",
"JSON",
"-",
"LD",
"context",
"for",
"repository",
"objects",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/show.py#L226-L237 |
15,256 | SwissDataScienceCenter/renku-python | renku/cli/workflow.py | workflow | def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name].append(ref.name)
for path in client.workflow_path.glob('*.cwl'):
click.echo(
'{path}: {names}'.format(
path=path.name,
names=', '.join(
click.style(_deref(name), fg='green')
for name in names[path.name]
),
)
) | python | def workflow(ctx, client):
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name].append(ref.name)
for path in client.workflow_path.glob('*.cwl'):
click.echo(
'{path}: {names}'.format(
path=path.name,
names=', '.join(
click.style(_deref(name), fg='green')
for name in names[path.name]
),
)
) | [
"def",
"workflow",
"(",
"ctx",
",",
"client",
")",
":",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"None",
":",
"from",
"renku",
".",
"models",
".",
"refs",
"import",
"LinkReference",
"names",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"ref",
"in",
... | List or manage workflows with subcommands. | [
"List",
"or",
"manage",
"workflows",
"with",
"subcommands",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/workflow.py#L59-L77 |
15,257 | SwissDataScienceCenter/renku-python | renku/cli/workflow.py | validate_path | def validate_path(ctx, param, value):
"""Detect a workflow path if it is not passed."""
client = ctx.obj
if value is None:
from renku.models.provenance import ProcessRun
activity = client.process_commit()
if not isinstance(activity, ProcessRun):
raise click.BadParameter('No tool was found.')
return activity.path
return value | python | def validate_path(ctx, param, value):
client = ctx.obj
if value is None:
from renku.models.provenance import ProcessRun
activity = client.process_commit()
if not isinstance(activity, ProcessRun):
raise click.BadParameter('No tool was found.')
return activity.path
return value | [
"def",
"validate_path",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"client",
"=",
"ctx",
".",
"obj",
"if",
"value",
"is",
"None",
":",
"from",
"renku",
".",
"models",
".",
"provenance",
"import",
"ProcessRun",
"activity",
"=",
"client",
".",
"pr... | Detect a workflow path if it is not passed. | [
"Detect",
"a",
"workflow",
"path",
"if",
"it",
"is",
"not",
"passed",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/workflow.py#L80-L93 |
15,258 | SwissDataScienceCenter/renku-python | renku/cli/workflow.py | create | def create(client, output_file, revision, paths):
"""Create a workflow description for a file."""
graph = Graph(client)
outputs = graph.build(paths=paths, revision=revision)
output_file.write(
yaml.dump(
ascwl(
graph.ascwl(outputs=outputs),
filter=lambda _, x: x is not None and x != [],
basedir=os.path.dirname(getattr(output_file, 'name', '.')) or
'.',
),
default_flow_style=False
)
) | python | def create(client, output_file, revision, paths):
graph = Graph(client)
outputs = graph.build(paths=paths, revision=revision)
output_file.write(
yaml.dump(
ascwl(
graph.ascwl(outputs=outputs),
filter=lambda _, x: x is not None and x != [],
basedir=os.path.dirname(getattr(output_file, 'name', '.')) or
'.',
),
default_flow_style=False
)
) | [
"def",
"create",
"(",
"client",
",",
"output_file",
",",
"revision",
",",
"paths",
")",
":",
"graph",
"=",
"Graph",
"(",
"client",
")",
"outputs",
"=",
"graph",
".",
"build",
"(",
"paths",
"=",
"paths",
",",
"revision",
"=",
"revision",
")",
"output_fi... | Create a workflow description for a file. | [
"Create",
"a",
"workflow",
"description",
"for",
"a",
"file",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/workflow.py#L147-L162 |
15,259 | SwissDataScienceCenter/renku-python | renku/cli/endpoint.py | endpoint | def endpoint(ctx, config, verbose):
"""Manage set of platform API endpoints."""
if ctx.invoked_subcommand is None:
# TODO default_endpoint = config.get('core', {}).get('default')
for endpoint, values in config.get('endpoints', {}).items():
# TODO is_default = default_endpoint == endpoint
if not verbose:
click.echo(endpoint)
else:
click.echo(
'{endpoint}\t{url}'.format(
endpoint=endpoint, url=values.get('url', '')
)
) | python | def endpoint(ctx, config, verbose):
if ctx.invoked_subcommand is None:
# TODO default_endpoint = config.get('core', {}).get('default')
for endpoint, values in config.get('endpoints', {}).items():
# TODO is_default = default_endpoint == endpoint
if not verbose:
click.echo(endpoint)
else:
click.echo(
'{endpoint}\t{url}'.format(
endpoint=endpoint, url=values.get('url', '')
)
) | [
"def",
"endpoint",
"(",
"ctx",
",",
"config",
",",
"verbose",
")",
":",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"None",
":",
"# TODO default_endpoint = config.get('core', {}).get('default')",
"for",
"endpoint",
",",
"values",
"in",
"config",
".",
"get",
"(",... | Manage set of platform API endpoints. | [
"Manage",
"set",
"of",
"platform",
"API",
"endpoints",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/endpoint.py#L30-L43 |
15,260 | SwissDataScienceCenter/renku-python | renku/_contexts.py | _wrap_path_or_stream | def _wrap_path_or_stream(method, mode): # noqa: D202
"""Open path with context or close stream at the end."""
def decorator(path_or_stream):
"""Open the path if needed."""
if isinstance(path_or_stream, (str, Path)):
return method(Path(path_or_stream).open(mode))
return method(path_or_stream)
return decorator | python | def _wrap_path_or_stream(method, mode): # noqa: D202
def decorator(path_or_stream):
"""Open the path if needed."""
if isinstance(path_or_stream, (str, Path)):
return method(Path(path_or_stream).open(mode))
return method(path_or_stream)
return decorator | [
"def",
"_wrap_path_or_stream",
"(",
"method",
",",
"mode",
")",
":",
"# noqa: D202",
"def",
"decorator",
"(",
"path_or_stream",
")",
":",
"\"\"\"Open the path if needed.\"\"\"",
"if",
"isinstance",
"(",
"path_or_stream",
",",
"(",
"str",
",",
"Path",
")",
")",
"... | Open path with context or close stream at the end. | [
"Open",
"path",
"with",
"context",
"or",
"close",
"stream",
"at",
"the",
"end",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/_contexts.py#L60-L69 |
15,261 | SwissDataScienceCenter/renku-python | renku/cli/doctor.py | doctor | def doctor(ctx, client):
"""Check your system and repository for potential problems."""
click.secho('\n'.join(textwrap.wrap(DOCTOR_INFO)) + '\n', bold=True)
from . import _checks
is_ok = True
for attr in _checks.__all__:
is_ok &= getattr(_checks, attr)(client)
if is_ok:
click.secho('Everything seems to be ok.', fg='green')
ctx.exit(0 if is_ok else 1) | python | def doctor(ctx, client):
click.secho('\n'.join(textwrap.wrap(DOCTOR_INFO)) + '\n', bold=True)
from . import _checks
is_ok = True
for attr in _checks.__all__:
is_ok &= getattr(_checks, attr)(client)
if is_ok:
click.secho('Everything seems to be ok.', fg='green')
ctx.exit(0 if is_ok else 1) | [
"def",
"doctor",
"(",
"ctx",
",",
"client",
")",
":",
"click",
".",
"secho",
"(",
"'\\n'",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",
"DOCTOR_INFO",
")",
")",
"+",
"'\\n'",
",",
"bold",
"=",
"True",
")",
"from",
".",
"import",
"_checks",
"is_o... | Check your system and repository for potential problems. | [
"Check",
"your",
"system",
"and",
"repository",
"for",
"potential",
"problems",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/doctor.py#L36-L49 |
15,262 | SwissDataScienceCenter/renku-python | renku/models/_datastructures.py | DirectoryTree.from_list | def from_list(cls, values):
"""Construct a tree from a list with paths."""
self = cls()
for value in values:
self.add(value)
return self | python | def from_list(cls, values):
self = cls()
for value in values:
self.add(value)
return self | [
"def",
"from_list",
"(",
"cls",
",",
"values",
")",
":",
"self",
"=",
"cls",
"(",
")",
"for",
"value",
"in",
"values",
":",
"self",
".",
"add",
"(",
"value",
")",
"return",
"self"
] | Construct a tree from a list with paths. | [
"Construct",
"a",
"tree",
"from",
"a",
"list",
"with",
"paths",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_datastructures.py#L198-L203 |
15,263 | SwissDataScienceCenter/renku-python | renku/models/_datastructures.py | DirectoryTree.get | def get(self, value, default=None):
"""Return a subtree if exists."""
path = value if isinstance(value, Path) else Path(str(value))
subtree = self
for part in path.parts:
try:
subtree = subtree[part]
except KeyError:
return default
return subtree | python | def get(self, value, default=None):
path = value if isinstance(value, Path) else Path(str(value))
subtree = self
for part in path.parts:
try:
subtree = subtree[part]
except KeyError:
return default
return subtree | [
"def",
"get",
"(",
"self",
",",
"value",
",",
"default",
"=",
"None",
")",
":",
"path",
"=",
"value",
"if",
"isinstance",
"(",
"value",
",",
"Path",
")",
"else",
"Path",
"(",
"str",
"(",
"value",
")",
")",
"subtree",
"=",
"self",
"for",
"part",
"... | Return a subtree if exists. | [
"Return",
"a",
"subtree",
"if",
"exists",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_datastructures.py#L205-L214 |
15,264 | SwissDataScienceCenter/renku-python | renku/models/_datastructures.py | DirectoryTree.add | def add(self, value):
"""Create a safe directory from a value."""
path = value if isinstance(value, Path) else Path(str(value))
if path and path != path.parent:
destination = self
for part in path.parts:
destination = destination.setdefault(part, DirectoryTree()) | python | def add(self, value):
path = value if isinstance(value, Path) else Path(str(value))
if path and path != path.parent:
destination = self
for part in path.parts:
destination = destination.setdefault(part, DirectoryTree()) | [
"def",
"add",
"(",
"self",
",",
"value",
")",
":",
"path",
"=",
"value",
"if",
"isinstance",
"(",
"value",
",",
"Path",
")",
"else",
"Path",
"(",
"str",
"(",
"value",
")",
")",
"if",
"path",
"and",
"path",
"!=",
"path",
".",
"parent",
":",
"desti... | Create a safe directory from a value. | [
"Create",
"a",
"safe",
"directory",
"from",
"a",
"value",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_datastructures.py#L216-L222 |
15,265 | SwissDataScienceCenter/renku-python | renku/cli/_options.py | default_endpoint_from_config | def default_endpoint_from_config(config, option=None):
"""Return a default endpoint."""
default_endpoint = config.get('core', {}).get('default')
project_endpoint = config.get('project',
{}).get('core',
{}).get('default', default_endpoint)
return Endpoint(
option or project_endpoint or default_endpoint,
default=default_endpoint,
project=project_endpoint,
option=option
) | python | def default_endpoint_from_config(config, option=None):
default_endpoint = config.get('core', {}).get('default')
project_endpoint = config.get('project',
{}).get('core',
{}).get('default', default_endpoint)
return Endpoint(
option or project_endpoint or default_endpoint,
default=default_endpoint,
project=project_endpoint,
option=option
) | [
"def",
"default_endpoint_from_config",
"(",
"config",
",",
"option",
"=",
"None",
")",
":",
"default_endpoint",
"=",
"config",
".",
"get",
"(",
"'core'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'default'",
")",
"project_endpoint",
"=",
"config",
".",
"get",
... | Return a default endpoint. | [
"Return",
"a",
"default",
"endpoint",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_options.py#L37-L48 |
15,266 | SwissDataScienceCenter/renku-python | renku/cli/_options.py | install_completion | def install_completion(ctx, attr, value): # pragma: no cover
"""Install completion for the current shell."""
import click_completion.core
if not value or ctx.resilient_parsing:
return value
shell, path = click_completion.core.install()
click.secho(
'{0} completion installed in {1}'.format(shell, path), fg='green'
)
ctx.exit() | python | def install_completion(ctx, attr, value): # pragma: no cover
import click_completion.core
if not value or ctx.resilient_parsing:
return value
shell, path = click_completion.core.install()
click.secho(
'{0} completion installed in {1}'.format(shell, path), fg='green'
)
ctx.exit() | [
"def",
"install_completion",
"(",
"ctx",
",",
"attr",
",",
"value",
")",
":",
"# pragma: no cover",
"import",
"click_completion",
".",
"core",
"if",
"not",
"value",
"or",
"ctx",
".",
"resilient_parsing",
":",
"return",
"value",
"shell",
",",
"path",
"=",
"cl... | Install completion for the current shell. | [
"Install",
"completion",
"for",
"the",
"current",
"shell",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_options.py#L67-L78 |
15,267 | SwissDataScienceCenter/renku-python | renku/cli/_options.py | default_endpoint | def default_endpoint(ctx, param, value):
"""Return default endpoint if specified."""
if ctx.resilient_parsing:
return
config = ctx.obj['config']
endpoint = default_endpoint_from_config(config, option=value)
if endpoint is None:
raise click.UsageError('No default endpoint found.')
return endpoint | python | def default_endpoint(ctx, param, value):
if ctx.resilient_parsing:
return
config = ctx.obj['config']
endpoint = default_endpoint_from_config(config, option=value)
if endpoint is None:
raise click.UsageError('No default endpoint found.')
return endpoint | [
"def",
"default_endpoint",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"ctx",
".",
"resilient_parsing",
":",
"return",
"config",
"=",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
"endpoint",
"=",
"default_endpoint_from_config",
"(",
"config",
",",
... | Return default endpoint if specified. | [
"Return",
"default",
"endpoint",
"if",
"specified",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_options.py#L81-L92 |
15,268 | SwissDataScienceCenter/renku-python | renku/cli/_options.py | validate_endpoint | def validate_endpoint(ctx, param, value):
"""Validate endpoint."""
try:
config = ctx.obj['config']
except Exception:
return
endpoint = default_endpoint(ctx, param, value)
if endpoint not in config.get('endpoints', {}):
raise click.UsageError('Unknown endpoint: {0}'.format(endpoint))
return endpoint | python | def validate_endpoint(ctx, param, value):
try:
config = ctx.obj['config']
except Exception:
return
endpoint = default_endpoint(ctx, param, value)
if endpoint not in config.get('endpoints', {}):
raise click.UsageError('Unknown endpoint: {0}'.format(endpoint))
return endpoint | [
"def",
"validate_endpoint",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"try",
":",
"config",
"=",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
"except",
"Exception",
":",
"return",
"endpoint",
"=",
"default_endpoint",
"(",
"ctx",
",",
"param",
",",
... | Validate endpoint. | [
"Validate",
"endpoint",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_options.py#L95-L107 |
15,269 | SwissDataScienceCenter/renku-python | renku/cli/_options.py | check_siblings | def check_siblings(graph, outputs):
"""Check that all outputs have their siblings listed."""
siblings = set()
for node in outputs:
siblings |= graph.siblings(node)
siblings = {node.path for node in siblings}
missing = siblings - {node.path for node in outputs}
if missing:
msg = (
'Include the files above in the command '
'or use the --with-siblings option.'
)
raise click.ClickException(
'There are missing output siblings:\n\n'
'\t{0}\n\n{1}'.format(
'\n\t'.join(click.style(path, fg='red') for path in missing),
msg,
),
)
return outputs | python | def check_siblings(graph, outputs):
siblings = set()
for node in outputs:
siblings |= graph.siblings(node)
siblings = {node.path for node in siblings}
missing = siblings - {node.path for node in outputs}
if missing:
msg = (
'Include the files above in the command '
'or use the --with-siblings option.'
)
raise click.ClickException(
'There are missing output siblings:\n\n'
'\t{0}\n\n{1}'.format(
'\n\t'.join(click.style(path, fg='red') for path in missing),
msg,
),
)
return outputs | [
"def",
"check_siblings",
"(",
"graph",
",",
"outputs",
")",
":",
"siblings",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"outputs",
":",
"siblings",
"|=",
"graph",
".",
"siblings",
"(",
"node",
")",
"siblings",
"=",
"{",
"node",
".",
"path",
"for",
"n... | Check that all outputs have their siblings listed. | [
"Check",
"that",
"all",
"outputs",
"have",
"their",
"siblings",
"listed",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_options.py#L131-L152 |
15,270 | SwissDataScienceCenter/renku-python | renku/cli/_options.py | with_siblings | def with_siblings(graph, outputs):
"""Include all missing siblings."""
siblings = set()
for node in outputs:
siblings |= graph.siblings(node)
return siblings | python | def with_siblings(graph, outputs):
siblings = set()
for node in outputs:
siblings |= graph.siblings(node)
return siblings | [
"def",
"with_siblings",
"(",
"graph",
",",
"outputs",
")",
":",
"siblings",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"outputs",
":",
"siblings",
"|=",
"graph",
".",
"siblings",
"(",
"node",
")",
"return",
"siblings"
] | Include all missing siblings. | [
"Include",
"all",
"missing",
"siblings",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_options.py#L155-L160 |
15,271 | SwissDataScienceCenter/renku-python | renku/cli/_echo.py | echo_via_pager | def echo_via_pager(*args, **kwargs):
"""Display pager only if it does not fit in one terminal screen.
NOTE: The feature is available only on ``less``-based pager.
"""
try:
restore = 'LESS' not in os.environ
os.environ.setdefault('LESS', '-iXFR')
click.echo_via_pager(*args, **kwargs)
finally:
if restore:
os.environ.pop('LESS', None) | python | def echo_via_pager(*args, **kwargs):
try:
restore = 'LESS' not in os.environ
os.environ.setdefault('LESS', '-iXFR')
click.echo_via_pager(*args, **kwargs)
finally:
if restore:
os.environ.pop('LESS', None) | [
"def",
"echo_via_pager",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"restore",
"=",
"'LESS'",
"not",
"in",
"os",
".",
"environ",
"os",
".",
"environ",
".",
"setdefault",
"(",
"'LESS'",
",",
"'-iXFR'",
")",
"click",
".",
"echo_vi... | Display pager only if it does not fit in one terminal screen.
NOTE: The feature is available only on ``less``-based pager. | [
"Display",
"pager",
"only",
"if",
"it",
"does",
"not",
"fit",
"in",
"one",
"terminal",
"screen",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_echo.py#L28-L39 |
15,272 | SwissDataScienceCenter/renku-python | renku/cli/_group.py | OptionalGroup.parse_args | def parse_args(self, ctx, args):
"""Check if the first argument is an existing command."""
if args and args[0] in self.commands:
args.insert(0, '')
super(OptionalGroup, self).parse_args(ctx, args) | python | def parse_args(self, ctx, args):
if args and args[0] in self.commands:
args.insert(0, '')
super(OptionalGroup, self).parse_args(ctx, args) | [
"def",
"parse_args",
"(",
"self",
",",
"ctx",
",",
"args",
")",
":",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
"in",
"self",
".",
"commands",
":",
"args",
".",
"insert",
"(",
"0",
",",
"''",
")",
"super",
"(",
"OptionalGroup",
",",
"self",
")",... | Check if the first argument is an existing command. | [
"Check",
"if",
"the",
"first",
"argument",
"is",
"an",
"existing",
"command",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_group.py#L26-L30 |
15,273 | SwissDataScienceCenter/renku-python | renku/cli/_cwl.py | execute | def execute(client, output_file, output_paths=None):
"""Run the generated workflow using cwltool library."""
output_paths = output_paths or set()
import cwltool.factory
from cwltool import workflow
from cwltool.context import LoadingContext, RuntimeContext
from cwltool.utils import visit_class
def construct_tool_object(toolpath_object, *args, **kwargs):
"""Fix missing locations."""
protocol = 'file://'
def addLocation(d):
if 'location' not in d and 'path' in d:
d['location'] = protocol + d['path']
visit_class(toolpath_object, ('File', 'Directory'), addLocation)
return workflow.default_make_tool(toolpath_object, *args, **kwargs)
argv = sys.argv
sys.argv = ['cwltool']
# Keep all environment variables.
runtime_context = RuntimeContext(
kwargs={
'rm_tmpdir': False,
'move_outputs': 'leave',
'preserve_entire_environment': True,
}
)
loading_context = LoadingContext(
kwargs={
'construct_tool_object': construct_tool_object,
}
)
factory = cwltool.factory.Factory(
loading_context=loading_context,
runtime_context=runtime_context,
)
process = factory.make(os.path.relpath(str(output_file)))
outputs = process()
sys.argv = argv
# Move outputs to correct location in the repository.
output_dirs = process.factory.executor.output_dirs
def remove_prefix(location, prefix='file://'):
if location.startswith(prefix):
return location[len(prefix):]
return location
locations = {
remove_prefix(output['location'])
for output in outputs.values()
}
with progressbar(
locations,
label='Moving outputs',
) as bar:
for location in bar:
for output_dir in output_dirs:
if location.startswith(output_dir):
output_path = location[len(output_dir):].lstrip(
os.path.sep
)
destination = client.path / output_path
if destination.is_dir():
shutil.rmtree(str(destination))
destination = destination.parent
shutil.move(location, str(destination))
continue
unchanged_paths = client.remove_unmodified(output_paths)
if unchanged_paths:
click.echo(
'Unchanged files:\n\n\t{0}'.format(
'\n\t'.join(
click.style(path, fg='yellow') for path in unchanged_paths
)
)
) | python | def execute(client, output_file, output_paths=None):
output_paths = output_paths or set()
import cwltool.factory
from cwltool import workflow
from cwltool.context import LoadingContext, RuntimeContext
from cwltool.utils import visit_class
def construct_tool_object(toolpath_object, *args, **kwargs):
"""Fix missing locations."""
protocol = 'file://'
def addLocation(d):
if 'location' not in d and 'path' in d:
d['location'] = protocol + d['path']
visit_class(toolpath_object, ('File', 'Directory'), addLocation)
return workflow.default_make_tool(toolpath_object, *args, **kwargs)
argv = sys.argv
sys.argv = ['cwltool']
# Keep all environment variables.
runtime_context = RuntimeContext(
kwargs={
'rm_tmpdir': False,
'move_outputs': 'leave',
'preserve_entire_environment': True,
}
)
loading_context = LoadingContext(
kwargs={
'construct_tool_object': construct_tool_object,
}
)
factory = cwltool.factory.Factory(
loading_context=loading_context,
runtime_context=runtime_context,
)
process = factory.make(os.path.relpath(str(output_file)))
outputs = process()
sys.argv = argv
# Move outputs to correct location in the repository.
output_dirs = process.factory.executor.output_dirs
def remove_prefix(location, prefix='file://'):
if location.startswith(prefix):
return location[len(prefix):]
return location
locations = {
remove_prefix(output['location'])
for output in outputs.values()
}
with progressbar(
locations,
label='Moving outputs',
) as bar:
for location in bar:
for output_dir in output_dirs:
if location.startswith(output_dir):
output_path = location[len(output_dir):].lstrip(
os.path.sep
)
destination = client.path / output_path
if destination.is_dir():
shutil.rmtree(str(destination))
destination = destination.parent
shutil.move(location, str(destination))
continue
unchanged_paths = client.remove_unmodified(output_paths)
if unchanged_paths:
click.echo(
'Unchanged files:\n\n\t{0}'.format(
'\n\t'.join(
click.style(path, fg='yellow') for path in unchanged_paths
)
)
) | [
"def",
"execute",
"(",
"client",
",",
"output_file",
",",
"output_paths",
"=",
"None",
")",
":",
"output_paths",
"=",
"output_paths",
"or",
"set",
"(",
")",
"import",
"cwltool",
".",
"factory",
"from",
"cwltool",
"import",
"workflow",
"from",
"cwltool",
".",... | Run the generated workflow using cwltool library. | [
"Run",
"the",
"generated",
"workflow",
"using",
"cwltool",
"library",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_cwl.py#L29-L113 |
15,274 | SwissDataScienceCenter/renku-python | renku/cli/image.py | pull | def pull(client, revision, auto_login):
"""Pull an existing image from the project registry."""
registry_url = detect_registry_url(client, auto_login=auto_login)
repo = client.repo
sha = repo.rev_parse(revision).hexsha
short_sha = repo.git.rev_parse(sha, short=7)
image = '{registry}:{short_sha}'.format(
registry=registry_url.image, short_sha=short_sha
)
result = subprocess.run(['docker', 'image', 'pull', image])
if result.returncode != 0:
raise click.ClickException(
'The image "{image}" was not pulled.\n\n'
'Push the repository to the server or build the image manually:\n'
'\n\tdocker build -t {image} .'.format(image=image)
) | python | def pull(client, revision, auto_login):
registry_url = detect_registry_url(client, auto_login=auto_login)
repo = client.repo
sha = repo.rev_parse(revision).hexsha
short_sha = repo.git.rev_parse(sha, short=7)
image = '{registry}:{short_sha}'.format(
registry=registry_url.image, short_sha=short_sha
)
result = subprocess.run(['docker', 'image', 'pull', image])
if result.returncode != 0:
raise click.ClickException(
'The image "{image}" was not pulled.\n\n'
'Push the repository to the server or build the image manually:\n'
'\n\tdocker build -t {image} .'.format(image=image)
) | [
"def",
"pull",
"(",
"client",
",",
"revision",
",",
"auto_login",
")",
":",
"registry_url",
"=",
"detect_registry_url",
"(",
"client",
",",
"auto_login",
"=",
"auto_login",
")",
"repo",
"=",
"client",
".",
"repo",
"sha",
"=",
"repo",
".",
"rev_parse",
"(",... | Pull an existing image from the project registry. | [
"Pull",
"an",
"existing",
"image",
"from",
"the",
"project",
"registry",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/image.py#L90-L108 |
15,275 | SwissDataScienceCenter/renku-python | renku/cli/_format/dataset_files.py | tabular | def tabular(client, records):
"""Format dataset files with a tabular output.
:param client: LocalClient instance.
:param records: Filtered collection.
"""
from renku.models._tabulate import tabulate
echo_via_pager(
tabulate(
records,
headers=OrderedDict((
('added', None),
('authors_csv', 'authors'),
('dataset', None),
('full_path', 'path'),
)),
)
) | python | def tabular(client, records):
from renku.models._tabulate import tabulate
echo_via_pager(
tabulate(
records,
headers=OrderedDict((
('added', None),
('authors_csv', 'authors'),
('dataset', None),
('full_path', 'path'),
)),
)
) | [
"def",
"tabular",
"(",
"client",
",",
"records",
")",
":",
"from",
"renku",
".",
"models",
".",
"_tabulate",
"import",
"tabulate",
"echo_via_pager",
"(",
"tabulate",
"(",
"records",
",",
"headers",
"=",
"OrderedDict",
"(",
"(",
"(",
"'added'",
",",
"None",... | Format dataset files with a tabular output.
:param client: LocalClient instance.
:param records: Filtered collection. | [
"Format",
"dataset",
"files",
"with",
"a",
"tabular",
"output",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/dataset_files.py#L25-L43 |
15,276 | SwissDataScienceCenter/renku-python | renku/cli/_format/dataset_files.py | jsonld | def jsonld(client, records):
"""Format dataset files as JSON-LD.
:param client: LocalClient instance.
:param records: Filtered collection.
"""
from renku.models._json import dumps
from renku.models._jsonld import asjsonld
data = [asjsonld(record) for record in records]
echo_via_pager(dumps(data, indent=2)) | python | def jsonld(client, records):
from renku.models._json import dumps
from renku.models._jsonld import asjsonld
data = [asjsonld(record) for record in records]
echo_via_pager(dumps(data, indent=2)) | [
"def",
"jsonld",
"(",
"client",
",",
"records",
")",
":",
"from",
"renku",
".",
"models",
".",
"_json",
"import",
"dumps",
"from",
"renku",
".",
"models",
".",
"_jsonld",
"import",
"asjsonld",
"data",
"=",
"[",
"asjsonld",
"(",
"record",
")",
"for",
"r... | Format dataset files as JSON-LD.
:param client: LocalClient instance.
:param records: Filtered collection. | [
"Format",
"dataset",
"files",
"as",
"JSON",
"-",
"LD",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/dataset_files.py#L46-L56 |
15,277 | SwissDataScienceCenter/renku-python | renku/cli/_exc.py | IssueFromTraceback.main | def main(self, *args, **kwargs):
"""Catch all exceptions."""
try:
result = super().main(*args, **kwargs)
return result
except Exception:
if HAS_SENTRY:
self._handle_sentry()
if not (sys.stdin.isatty() and sys.stdout.isatty()):
raise
self._handle_github() | python | def main(self, *args, **kwargs):
try:
result = super().main(*args, **kwargs)
return result
except Exception:
if HAS_SENTRY:
self._handle_sentry()
if not (sys.stdin.isatty() and sys.stdout.isatty()):
raise
self._handle_github() | [
"def",
"main",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
"super",
"(",
")",
".",
"main",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
"except",
"Exception",
":",
"if",
"H... | Catch all exceptions. | [
"Catch",
"all",
"exceptions",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_exc.py#L97-L109 |
15,278 | SwissDataScienceCenter/renku-python | renku/cli/_exc.py | IssueFromTraceback._handle_sentry | def _handle_sentry(self):
"""Handle exceptions using Sentry."""
from sentry_sdk import capture_exception, configure_scope
from sentry_sdk.utils import capture_internal_exceptions
with configure_scope() as scope:
with capture_internal_exceptions():
from git import Repo
from renku.cli._git import get_git_home
from renku.models.datasets import Author
user = Author.from_git(Repo(get_git_home()))
scope.user = {'name': user.name, 'email': user.email}
event_id = capture_exception()
click.echo(
_BUG + 'Recorded in Sentry with ID: {0}\n'.format(event_id),
err=True,
)
raise | python | def _handle_sentry(self):
from sentry_sdk import capture_exception, configure_scope
from sentry_sdk.utils import capture_internal_exceptions
with configure_scope() as scope:
with capture_internal_exceptions():
from git import Repo
from renku.cli._git import get_git_home
from renku.models.datasets import Author
user = Author.from_git(Repo(get_git_home()))
scope.user = {'name': user.name, 'email': user.email}
event_id = capture_exception()
click.echo(
_BUG + 'Recorded in Sentry with ID: {0}\n'.format(event_id),
err=True,
)
raise | [
"def",
"_handle_sentry",
"(",
"self",
")",
":",
"from",
"sentry_sdk",
"import",
"capture_exception",
",",
"configure_scope",
"from",
"sentry_sdk",
".",
"utils",
"import",
"capture_internal_exceptions",
"with",
"configure_scope",
"(",
")",
"as",
"scope",
":",
"with",... | Handle exceptions using Sentry. | [
"Handle",
"exceptions",
"using",
"Sentry",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_exc.py#L111-L131 |
15,279 | SwissDataScienceCenter/renku-python | renku/cli/_exc.py | IssueFromTraceback._handle_github | def _handle_github(self):
"""Handle exception and submit it as GitHub issue."""
value = click.prompt(
_BUG + click.style(
'1. Open an issue by typing "open";\n',
fg='green',
) + click.style(
'2. Print human-readable information by typing '
'"print";\n',
fg='yellow',
) + click.style(
'3. See the full traceback without submitting details '
'(default: "ignore").\n\n',
fg='red',
) + 'Please select an action by typing its name',
type=click.Choice([
'open',
'print',
'ignore',
], ),
default='ignore',
)
getattr(self, '_process_' + value)() | python | def _handle_github(self):
value = click.prompt(
_BUG + click.style(
'1. Open an issue by typing "open";\n',
fg='green',
) + click.style(
'2. Print human-readable information by typing '
'"print";\n',
fg='yellow',
) + click.style(
'3. See the full traceback without submitting details '
'(default: "ignore").\n\n',
fg='red',
) + 'Please select an action by typing its name',
type=click.Choice([
'open',
'print',
'ignore',
], ),
default='ignore',
)
getattr(self, '_process_' + value)() | [
"def",
"_handle_github",
"(",
"self",
")",
":",
"value",
"=",
"click",
".",
"prompt",
"(",
"_BUG",
"+",
"click",
".",
"style",
"(",
"'1. Open an issue by typing \"open\";\\n'",
",",
"fg",
"=",
"'green'",
",",
")",
"+",
"click",
".",
"style",
"(",
"'2. Prin... | Handle exception and submit it as GitHub issue. | [
"Handle",
"exception",
"and",
"submit",
"it",
"as",
"GitHub",
"issue",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_exc.py#L133-L155 |
15,280 | SwissDataScienceCenter/renku-python | renku/cli/_exc.py | IssueFromTraceback._format_issue_body | def _format_issue_body(self, limit=-5):
"""Return formatted body."""
from renku import __version__
re_paths = r'(' + r'|'.join([path or os.getcwd()
for path in sys.path]) + r')'
tb = re.sub(re_paths, '[...]', traceback.format_exc(limit=limit))
return (
'## Describe the bug\nA clear and concise description.\n\n'
'## Details\n'
'*Please verify and redact the details.*\n\n'
'**Renku version:** ' + __version__ + '\n'
'**OS:** ' + platform.system() + ' (' + platform.version() + ')\n'
'**Python:** ' + platform.python_version() + '\n\n'
'### Traceback\n\n```\n' + tb + '```\n\n'
'## Additional context\nAdd any other context about the problem.'
) | python | def _format_issue_body(self, limit=-5):
from renku import __version__
re_paths = r'(' + r'|'.join([path or os.getcwd()
for path in sys.path]) + r')'
tb = re.sub(re_paths, '[...]', traceback.format_exc(limit=limit))
return (
'## Describe the bug\nA clear and concise description.\n\n'
'## Details\n'
'*Please verify and redact the details.*\n\n'
'**Renku version:** ' + __version__ + '\n'
'**OS:** ' + platform.system() + ' (' + platform.version() + ')\n'
'**Python:** ' + platform.python_version() + '\n\n'
'### Traceback\n\n```\n' + tb + '```\n\n'
'## Additional context\nAdd any other context about the problem.'
) | [
"def",
"_format_issue_body",
"(",
"self",
",",
"limit",
"=",
"-",
"5",
")",
":",
"from",
"renku",
"import",
"__version__",
"re_paths",
"=",
"r'('",
"+",
"r'|'",
".",
"join",
"(",
"[",
"path",
"or",
"os",
".",
"getcwd",
"(",
")",
"for",
"path",
"in",
... | Return formatted body. | [
"Return",
"formatted",
"body",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_exc.py#L164-L181 |
15,281 | SwissDataScienceCenter/renku-python | renku/cli/_exc.py | IssueFromTraceback._format_issue_url | def _format_issue_url(self):
"""Format full issue URL."""
query = urlencode({
'title': self._format_issue_title(),
'body': self._format_issue_body(),
})
return self.REPO_URL + self.ISSUE_SUFFIX + '?' + query | python | def _format_issue_url(self):
query = urlencode({
'title': self._format_issue_title(),
'body': self._format_issue_body(),
})
return self.REPO_URL + self.ISSUE_SUFFIX + '?' + query | [
"def",
"_format_issue_url",
"(",
"self",
")",
":",
"query",
"=",
"urlencode",
"(",
"{",
"'title'",
":",
"self",
".",
"_format_issue_title",
"(",
")",
",",
"'body'",
":",
"self",
".",
"_format_issue_body",
"(",
")",
",",
"}",
")",
"return",
"self",
".",
... | Format full issue URL. | [
"Format",
"full",
"issue",
"URL",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_exc.py#L183-L189 |
15,282 | SwissDataScienceCenter/renku-python | renku/cli/_exc.py | IssueFromTraceback._process_open | def _process_open(self):
"""Open link in a browser."""
click.launch(self._format_issue_url())
if not click.confirm('Did it work?', default=True):
click.echo()
self._process_print()
click.secho(
'\nOpen the line manually and copy the text above\n',
fg='yellow'
)
click.secho(
' ' + self.REPO_URL + self.ISSUE_SUFFIX + '\n', bold=True
) | python | def _process_open(self):
click.launch(self._format_issue_url())
if not click.confirm('Did it work?', default=True):
click.echo()
self._process_print()
click.secho(
'\nOpen the line manually and copy the text above\n',
fg='yellow'
)
click.secho(
' ' + self.REPO_URL + self.ISSUE_SUFFIX + '\n', bold=True
) | [
"def",
"_process_open",
"(",
"self",
")",
":",
"click",
".",
"launch",
"(",
"self",
".",
"_format_issue_url",
"(",
")",
")",
"if",
"not",
"click",
".",
"confirm",
"(",
"'Did it work?'",
",",
"default",
"=",
"True",
")",
":",
"click",
".",
"echo",
"(",
... | Open link in a browser. | [
"Open",
"link",
"in",
"a",
"browser",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_exc.py#L191-L203 |
15,283 | SwissDataScienceCenter/renku-python | renku/cli/_client.py | pass_local_client | def pass_local_client(
method=None,
clean=None,
up_to_date=None,
commit=None,
ignore_std_streams=True,
lock=None,
):
"""Pass client from the current context to the decorated command."""
if method is None:
return functools.partial(
pass_local_client,
clean=clean,
up_to_date=up_to_date,
commit=commit,
ignore_std_streams=ignore_std_streams,
lock=lock,
)
def new_func(*args, **kwargs):
ctx = click.get_current_context()
client = ctx.ensure_object(LocalClient)
stack = contextlib.ExitStack()
# Handle --isolation option:
if get_git_isolation():
client = stack.enter_context(client.worktree())
transaction = client.transaction(
clean=clean,
up_to_date=up_to_date,
commit=commit,
ignore_std_streams=ignore_std_streams
)
stack.enter_context(transaction)
if lock or (lock is None and commit):
stack.enter_context(client.lock)
with stack:
result = ctx.invoke(method, client, *args, **kwargs)
return result
return functools.update_wrapper(new_func, method) | python | def pass_local_client(
method=None,
clean=None,
up_to_date=None,
commit=None,
ignore_std_streams=True,
lock=None,
):
if method is None:
return functools.partial(
pass_local_client,
clean=clean,
up_to_date=up_to_date,
commit=commit,
ignore_std_streams=ignore_std_streams,
lock=lock,
)
def new_func(*args, **kwargs):
ctx = click.get_current_context()
client = ctx.ensure_object(LocalClient)
stack = contextlib.ExitStack()
# Handle --isolation option:
if get_git_isolation():
client = stack.enter_context(client.worktree())
transaction = client.transaction(
clean=clean,
up_to_date=up_to_date,
commit=commit,
ignore_std_streams=ignore_std_streams
)
stack.enter_context(transaction)
if lock or (lock is None and commit):
stack.enter_context(client.lock)
with stack:
result = ctx.invoke(method, client, *args, **kwargs)
return result
return functools.update_wrapper(new_func, method) | [
"def",
"pass_local_client",
"(",
"method",
"=",
"None",
",",
"clean",
"=",
"None",
",",
"up_to_date",
"=",
"None",
",",
"commit",
"=",
"None",
",",
"ignore_std_streams",
"=",
"True",
",",
"lock",
"=",
"None",
",",
")",
":",
"if",
"method",
"is",
"None"... | Pass client from the current context to the decorated command. | [
"Pass",
"client",
"from",
"the",
"current",
"context",
"to",
"the",
"decorated",
"command",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_client.py#L40-L83 |
15,284 | SwissDataScienceCenter/renku-python | renku/api/_git.py | _mapped_std_streams | def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')):
"""Get a mapping of standard streams to given paths."""
# FIXME add device number too
standard_inos = {}
for stream in streams:
try:
stream_stat = os.fstat(getattr(sys, stream).fileno())
key = stream_stat.st_dev, stream_stat.st_ino
standard_inos[key] = stream
except Exception: # FIXME UnsupportedOperation
pass
# FIXME if not getattr(sys, stream).istty()
def stream_inos(paths):
"""Yield tuples with stats and path."""
for path in paths:
try:
stat = os.stat(path)
key = (stat.st_dev, stat.st_ino)
if key in standard_inos:
yield standard_inos[key], path
except FileNotFoundError: # pragma: no cover
pass
return dict(stream_inos(lookup_paths)) if standard_inos else {} | python | def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')):
# FIXME add device number too
standard_inos = {}
for stream in streams:
try:
stream_stat = os.fstat(getattr(sys, stream).fileno())
key = stream_stat.st_dev, stream_stat.st_ino
standard_inos[key] = stream
except Exception: # FIXME UnsupportedOperation
pass
# FIXME if not getattr(sys, stream).istty()
def stream_inos(paths):
"""Yield tuples with stats and path."""
for path in paths:
try:
stat = os.stat(path)
key = (stat.st_dev, stat.st_ino)
if key in standard_inos:
yield standard_inos[key], path
except FileNotFoundError: # pragma: no cover
pass
return dict(stream_inos(lookup_paths)) if standard_inos else {} | [
"def",
"_mapped_std_streams",
"(",
"lookup_paths",
",",
"streams",
"=",
"(",
"'stdin'",
",",
"'stdout'",
",",
"'stderr'",
")",
")",
":",
"# FIXME add device number too",
"standard_inos",
"=",
"{",
"}",
"for",
"stream",
"in",
"streams",
":",
"try",
":",
"stream... | Get a mapping of standard streams to given paths. | [
"Get",
"a",
"mapping",
"of",
"standard",
"streams",
"to",
"given",
"paths",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/api/_git.py#L37-L61 |
15,285 | SwissDataScienceCenter/renku-python | renku/api/_git.py | _clean_streams | def _clean_streams(repo, mapped_streams):
"""Clean mapped standard streams."""
for stream_name in ('stdout', 'stderr'):
stream = mapped_streams.get(stream_name)
if not stream:
continue
path = os.path.relpath(stream, start=repo.working_dir)
if (path, 0) not in repo.index.entries:
os.remove(stream)
else:
blob = repo.index.entries[(path, 0)].to_blob(repo)
with open(path, 'wb') as fp:
fp.write(blob.data_stream.read()) | python | def _clean_streams(repo, mapped_streams):
for stream_name in ('stdout', 'stderr'):
stream = mapped_streams.get(stream_name)
if not stream:
continue
path = os.path.relpath(stream, start=repo.working_dir)
if (path, 0) not in repo.index.entries:
os.remove(stream)
else:
blob = repo.index.entries[(path, 0)].to_blob(repo)
with open(path, 'wb') as fp:
fp.write(blob.data_stream.read()) | [
"def",
"_clean_streams",
"(",
"repo",
",",
"mapped_streams",
")",
":",
"for",
"stream_name",
"in",
"(",
"'stdout'",
",",
"'stderr'",
")",
":",
"stream",
"=",
"mapped_streams",
".",
"get",
"(",
"stream_name",
")",
"if",
"not",
"stream",
":",
"continue",
"pa... | Clean mapped standard streams. | [
"Clean",
"mapped",
"standard",
"streams",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/api/_git.py#L64-L77 |
15,286 | SwissDataScienceCenter/renku-python | renku/api/_git.py | _expand_directories | def _expand_directories(paths):
"""Expand directory with all files it contains."""
for path in paths:
path_ = Path(path)
if path_.is_dir():
for expanded in path_.rglob('*'):
yield str(expanded)
else:
yield path | python | def _expand_directories(paths):
for path in paths:
path_ = Path(path)
if path_.is_dir():
for expanded in path_.rglob('*'):
yield str(expanded)
else:
yield path | [
"def",
"_expand_directories",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"path_",
"=",
"Path",
"(",
"path",
")",
"if",
"path_",
".",
"is_dir",
"(",
")",
":",
"for",
"expanded",
"in",
"path_",
".",
"rglob",
"(",
"'*'",
")",
":",
"yie... | Expand directory with all files it contains. | [
"Expand",
"directory",
"with",
"all",
"files",
"it",
"contains",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/api/_git.py#L80-L88 |
15,287 | SwissDataScienceCenter/renku-python | renku/cli/dataset.py | dataset | def dataset(ctx, client, revision, datadir, format):
"""Handle datasets."""
ctx.meta['renku.datasets.datadir'] = datadir
if ctx.invoked_subcommand is not None:
return
if revision is None:
datasets = client.datasets.values()
else:
datasets = client.datasets_from_commit(client.repo.commit(revision))
DATASETS_FORMATS[format](client, datasets) | python | def dataset(ctx, client, revision, datadir, format):
ctx.meta['renku.datasets.datadir'] = datadir
if ctx.invoked_subcommand is not None:
return
if revision is None:
datasets = client.datasets.values()
else:
datasets = client.datasets_from_commit(client.repo.commit(revision))
DATASETS_FORMATS[format](client, datasets) | [
"def",
"dataset",
"(",
"ctx",
",",
"client",
",",
"revision",
",",
"datadir",
",",
"format",
")",
":",
"ctx",
".",
"meta",
"[",
"'renku.datasets.datadir'",
"]",
"=",
"datadir",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"not",
"None",
":",
"return",
"... | Handle datasets. | [
"Handle",
"datasets",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L175-L187 |
15,288 | SwissDataScienceCenter/renku-python | renku/cli/dataset.py | create | def create(client, name):
"""Create an empty dataset in the current repo."""
from renku.models.datasets import Author
with client.with_dataset(name=name) as dataset:
click.echo('Creating a dataset ... ', nl=False)
author = Author.from_git(client.repo)
if author not in dataset.authors:
dataset.authors.append(author)
click.secho('OK', fg='green') | python | def create(client, name):
from renku.models.datasets import Author
with client.with_dataset(name=name) as dataset:
click.echo('Creating a dataset ... ', nl=False)
author = Author.from_git(client.repo)
if author not in dataset.authors:
dataset.authors.append(author)
click.secho('OK', fg='green') | [
"def",
"create",
"(",
"client",
",",
"name",
")",
":",
"from",
"renku",
".",
"models",
".",
"datasets",
"import",
"Author",
"with",
"client",
".",
"with_dataset",
"(",
"name",
"=",
"name",
")",
"as",
"dataset",
":",
"click",
".",
"echo",
"(",
"'Creatin... | Create an empty dataset in the current repo. | [
"Create",
"an",
"empty",
"dataset",
"in",
"the",
"current",
"repo",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L193-L203 |
15,289 | SwissDataScienceCenter/renku-python | renku/cli/dataset.py | add | def add(client, name, urls, link, relative_to, target, force):
"""Add data to a dataset."""
try:
with client.with_dataset(name=name) as dataset:
target = target if target else None
with progressbar(urls, label='Adding data to dataset') as bar:
for url in bar:
client.add_data_to_dataset(
dataset,
url,
link=link,
target=target,
relative_to=relative_to,
force=force,
)
except FileNotFoundError:
raise BadParameter('Could not process {0}'.format(url)) | python | def add(client, name, urls, link, relative_to, target, force):
try:
with client.with_dataset(name=name) as dataset:
target = target if target else None
with progressbar(urls, label='Adding data to dataset') as bar:
for url in bar:
client.add_data_to_dataset(
dataset,
url,
link=link,
target=target,
relative_to=relative_to,
force=force,
)
except FileNotFoundError:
raise BadParameter('Could not process {0}'.format(url)) | [
"def",
"add",
"(",
"client",
",",
"name",
",",
"urls",
",",
"link",
",",
"relative_to",
",",
"target",
",",
"force",
")",
":",
"try",
":",
"with",
"client",
".",
"with_dataset",
"(",
"name",
"=",
"name",
")",
"as",
"dataset",
":",
"target",
"=",
"t... | Add data to a dataset. | [
"Add",
"data",
"to",
"a",
"dataset",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L222-L238 |
15,290 | SwissDataScienceCenter/renku-python | renku/cli/dataset.py | ls_files | def ls_files(client, names, authors, include, exclude, format):
"""List files in dataset."""
records = _filter(
client, names=names, authors=authors, include=include, exclude=exclude
)
DATASET_FILES_FORMATS[format](client, records) | python | def ls_files(client, names, authors, include, exclude, format):
records = _filter(
client, names=names, authors=authors, include=include, exclude=exclude
)
DATASET_FILES_FORMATS[format](client, records) | [
"def",
"ls_files",
"(",
"client",
",",
"names",
",",
"authors",
",",
"include",
",",
"exclude",
",",
"format",
")",
":",
"records",
"=",
"_filter",
"(",
"client",
",",
"names",
"=",
"names",
",",
"authors",
"=",
"authors",
",",
"include",
"=",
"include... | List files in dataset. | [
"List",
"files",
"in",
"dataset",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L269-L275 |
15,291 | SwissDataScienceCenter/renku-python | renku/cli/dataset.py | unlink | def unlink(client, name, include, exclude, yes):
"""Remove matching files from a dataset."""
dataset = client.load_dataset(name=name)
records = _filter(
client, names=[dataset.name], include=include, exclude=exclude
)
if not yes and records:
prompt_text = (
'You are about to remove '
'following from "{0}" dataset.\n'.format(dataset.name) +
'\n'.join([str(record.full_path)
for record in records]) + '\nDo you wish to continue?'
)
click.confirm(WARNING + prompt_text, abort=True)
if records:
for item in records:
dataset.unlink_file(item.path)
dataset.to_yaml()
click.secho('OK', fg='green') | python | def unlink(client, name, include, exclude, yes):
dataset = client.load_dataset(name=name)
records = _filter(
client, names=[dataset.name], include=include, exclude=exclude
)
if not yes and records:
prompt_text = (
'You are about to remove '
'following from "{0}" dataset.\n'.format(dataset.name) +
'\n'.join([str(record.full_path)
for record in records]) + '\nDo you wish to continue?'
)
click.confirm(WARNING + prompt_text, abort=True)
if records:
for item in records:
dataset.unlink_file(item.path)
dataset.to_yaml()
click.secho('OK', fg='green') | [
"def",
"unlink",
"(",
"client",
",",
"name",
",",
"include",
",",
"exclude",
",",
"yes",
")",
":",
"dataset",
"=",
"client",
".",
"load_dataset",
"(",
"name",
"=",
"name",
")",
"records",
"=",
"_filter",
"(",
"client",
",",
"names",
"=",
"[",
"datase... | Remove matching files from a dataset. | [
"Remove",
"matching",
"files",
"from",
"a",
"dataset",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L296-L317 |
15,292 | SwissDataScienceCenter/renku-python | renku/cli/dataset.py | _include_exclude | def _include_exclude(file_path, include=None, exclude=None):
"""Check if file matches one of include filters and not in exclude filter.
:param file_path: Path to the file.
:param include: Tuple containing patterns to which include from result.
:param exclude: Tuple containing patterns to which exclude from result.
"""
if exclude is not None and exclude:
for pattern in exclude:
if file_path.match(pattern):
return False
if include is not None and include:
for pattern in include:
if file_path.match(pattern):
return True
return False
return True | python | def _include_exclude(file_path, include=None, exclude=None):
if exclude is not None and exclude:
for pattern in exclude:
if file_path.match(pattern):
return False
if include is not None and include:
for pattern in include:
if file_path.match(pattern):
return True
return False
return True | [
"def",
"_include_exclude",
"(",
"file_path",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"exclude",
"is",
"not",
"None",
"and",
"exclude",
":",
"for",
"pattern",
"in",
"exclude",
":",
"if",
"file_path",
".",
"match",
"(",
... | Check if file matches one of include filters and not in exclude filter.
:param file_path: Path to the file.
:param include: Tuple containing patterns to which include from result.
:param exclude: Tuple containing patterns to which exclude from result. | [
"Check",
"if",
"file",
"matches",
"one",
"of",
"include",
"filters",
"and",
"not",
"in",
"exclude",
"filter",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L365-L383 |
15,293 | SwissDataScienceCenter/renku-python | renku/cli/dataset.py | _filter | def _filter(client, names=None, authors=None, include=None, exclude=None):
"""Filter dataset files by specified filters.
:param names: Filter by specified dataset names.
:param authors: Filter by authors.
:param include: Include files matching file pattern.
:param exclude: Exclude files matching file pattern.
"""
if isinstance(authors, str):
authors = set(authors.split(','))
if isinstance(authors, list) or isinstance(authors, tuple):
authors = set(authors)
records = []
for path_, dataset in client.datasets.items():
if not names or dataset.name in names:
for file_ in dataset.files.values():
file_.dataset = dataset.name
path_ = file_.full_path.relative_to(client.path)
match = _include_exclude(path_, include, exclude)
if authors:
match = match and authors.issubset({
author.name
for author in file_.authors
})
if match:
records.append(file_)
return sorted(records, key=lambda file_: file_.added) | python | def _filter(client, names=None, authors=None, include=None, exclude=None):
if isinstance(authors, str):
authors = set(authors.split(','))
if isinstance(authors, list) or isinstance(authors, tuple):
authors = set(authors)
records = []
for path_, dataset in client.datasets.items():
if not names or dataset.name in names:
for file_ in dataset.files.values():
file_.dataset = dataset.name
path_ = file_.full_path.relative_to(client.path)
match = _include_exclude(path_, include, exclude)
if authors:
match = match and authors.issubset({
author.name
for author in file_.authors
})
if match:
records.append(file_)
return sorted(records, key=lambda file_: file_.added) | [
"def",
"_filter",
"(",
"client",
",",
"names",
"=",
"None",
",",
"authors",
"=",
"None",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"authors",
",",
"str",
")",
":",
"authors",
"=",
"set",
"(",
"auth... | Filter dataset files by specified filters.
:param names: Filter by specified dataset names.
:param authors: Filter by authors.
:param include: Include files matching file pattern.
:param exclude: Exclude files matching file pattern. | [
"Filter",
"dataset",
"files",
"by",
"specified",
"filters",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L386-L418 |
15,294 | SwissDataScienceCenter/renku-python | renku/cli/config.py | _split_section_and_key | def _split_section_and_key(key):
"""Return a tuple with config section and key."""
parts = key.split('.')
if len(parts) > 1:
return 'renku "{0}"'.format(parts[0]), '.'.join(parts[1:])
return 'renku', key | python | def _split_section_and_key(key):
parts = key.split('.')
if len(parts) > 1:
return 'renku "{0}"'.format(parts[0]), '.'.join(parts[1:])
return 'renku', key | [
"def",
"_split_section_and_key",
"(",
"key",
")",
":",
"parts",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
":",
"return",
"'renku \"{0}\"'",
".",
"format",
"(",
"parts",
"[",
"0",
"]",
")",
",",
"'.'",
".",... | Return a tuple with config section and key. | [
"Return",
"a",
"tuple",
"with",
"config",
"section",
"and",
"key",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/config.py#L47-L52 |
15,295 | SwissDataScienceCenter/renku-python | renku/cli/config.py | config | def config(client, key, value):
"""Get and set Renku repository and global options."""
if value is None:
cfg = client.repo.config_reader()
click.echo(cfg.get_value(*_split_section_and_key(key)))
else:
with client.repo.config_writer() as cfg:
section, config_key = _split_section_and_key(key)
cfg.set_value(section, config_key, value)
click.echo(value) | python | def config(client, key, value):
if value is None:
cfg = client.repo.config_reader()
click.echo(cfg.get_value(*_split_section_and_key(key)))
else:
with client.repo.config_writer() as cfg:
section, config_key = _split_section_and_key(key)
cfg.set_value(section, config_key, value)
click.echo(value) | [
"def",
"config",
"(",
"client",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"cfg",
"=",
"client",
".",
"repo",
".",
"config_reader",
"(",
")",
"click",
".",
"echo",
"(",
"cfg",
".",
"get_value",
"(",
"*",
"_split_section_and... | Get and set Renku repository and global options. | [
"Get",
"and",
"set",
"Renku",
"repository",
"and",
"global",
"options",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/config.py#L59-L68 |
15,296 | SwissDataScienceCenter/renku-python | renku/api/datasets.py | check_for_git_repo | def check_for_git_repo(url):
"""Check if a url points to a git repository."""
u = parse.urlparse(url)
is_git = False
if os.path.splitext(u.path)[1] == '.git':
is_git = True
elif u.scheme in ('', 'file'):
from git import InvalidGitRepositoryError, Repo
try:
Repo(u.path, search_parent_directories=True)
is_git = True
except InvalidGitRepositoryError:
is_git = False
return is_git | python | def check_for_git_repo(url):
u = parse.urlparse(url)
is_git = False
if os.path.splitext(u.path)[1] == '.git':
is_git = True
elif u.scheme in ('', 'file'):
from git import InvalidGitRepositoryError, Repo
try:
Repo(u.path, search_parent_directories=True)
is_git = True
except InvalidGitRepositoryError:
is_git = False
return is_git | [
"def",
"check_for_git_repo",
"(",
"url",
")",
":",
"u",
"=",
"parse",
".",
"urlparse",
"(",
"url",
")",
"is_git",
"=",
"False",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"u",
".",
"path",
")",
"[",
"1",
"]",
"==",
"'.git'",
":",
"is_git",
"=... | Check if a url points to a git repository. | [
"Check",
"if",
"a",
"url",
"points",
"to",
"a",
"git",
"repository",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/api/datasets.py#L443-L458 |
15,297 | SwissDataScienceCenter/renku-python | renku/cli/env.py | env | def env(config, endpoint):
"""Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)"
"""
access_token = config['endpoints'][endpoint]['token']['access_token']
click.echo('export {0}={1}'.format('RENKU_ENDPOINT', endpoint))
click.echo('export {0}={1}'.format('RENKU_ACCESS_TOKEN', access_token))
click.echo('# Run this command to configure your Renku client:')
click.echo('# eval "$(renku env)"') | python | def env(config, endpoint):
access_token = config['endpoints'][endpoint]['token']['access_token']
click.echo('export {0}={1}'.format('RENKU_ENDPOINT', endpoint))
click.echo('export {0}={1}'.format('RENKU_ACCESS_TOKEN', access_token))
click.echo('# Run this command to configure your Renku client:')
click.echo('# eval "$(renku env)"') | [
"def",
"env",
"(",
"config",
",",
"endpoint",
")",
":",
"access_token",
"=",
"config",
"[",
"'endpoints'",
"]",
"[",
"endpoint",
"]",
"[",
"'token'",
"]",
"[",
"'access_token'",
"]",
"click",
".",
"echo",
"(",
"'export {0}={1}'",
".",
"format",
"(",
"'RE... | Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)" | [
"Print",
"RENKU",
"environment",
"variables",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/env.py#L29-L41 |
15,298 | SwissDataScienceCenter/renku-python | renku/cli/_version.py | _check_version | def _check_version():
"""Check renku version."""
from ._config import APP_NAME
if VersionCache.load(APP_NAME).is_fresh:
return
from pkg_resources import parse_version
from renku.version import __version__
version = parse_version(__version__)
allow_prereleases = version.is_prerelease
latest_version = find_latest_version(
'renku', allow_prereleases=allow_prereleases
)
if version < latest_version:
click.secho(
'You are using renku version {version}, however version '
'{latest_version} is available.\n'
'You should consider upgrading ...'.format(
version=__version__,
latest_version=latest_version,
),
fg='yellow',
bold=True,
)
VersionCache(pypi_version=str(latest_version)).dump(APP_NAME) | python | def _check_version():
from ._config import APP_NAME
if VersionCache.load(APP_NAME).is_fresh:
return
from pkg_resources import parse_version
from renku.version import __version__
version = parse_version(__version__)
allow_prereleases = version.is_prerelease
latest_version = find_latest_version(
'renku', allow_prereleases=allow_prereleases
)
if version < latest_version:
click.secho(
'You are using renku version {version}, however version '
'{latest_version} is available.\n'
'You should consider upgrading ...'.format(
version=__version__,
latest_version=latest_version,
),
fg='yellow',
bold=True,
)
VersionCache(pypi_version=str(latest_version)).dump(APP_NAME) | [
"def",
"_check_version",
"(",
")",
":",
"from",
".",
"_config",
"import",
"APP_NAME",
"if",
"VersionCache",
".",
"load",
"(",
"APP_NAME",
")",
".",
"is_fresh",
":",
"return",
"from",
"pkg_resources",
"import",
"parse_version",
"from",
"renku",
".",
"version",
... | Check renku version. | [
"Check",
"renku",
"version",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_version.py#L128-L157 |
15,299 | SwissDataScienceCenter/renku-python | renku/cli/_version.py | check_version | def check_version(ctx, param, value):
"""Check for latest version of renku on PyPI."""
if ctx.resilient_parsing:
return
if not value and ctx.invoked_subcommand != 'run':
ctx.call_on_close(_check_version) | python | def check_version(ctx, param, value):
if ctx.resilient_parsing:
return
if not value and ctx.invoked_subcommand != 'run':
ctx.call_on_close(_check_version) | [
"def",
"check_version",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"ctx",
".",
"resilient_parsing",
":",
"return",
"if",
"not",
"value",
"and",
"ctx",
".",
"invoked_subcommand",
"!=",
"'run'",
":",
"ctx",
".",
"call_on_close",
"(",
"_check_ver... | Check for latest version of renku on PyPI. | [
"Check",
"for",
"latest",
"version",
"of",
"renku",
"on",
"PyPI",
"."
] | 691644d695b055a01e0ca22b2620e55bbd928c0d | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_version.py#L160-L166 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.