2020-10-05 14:53:07 +03:00
|
|
|
from typing import Dict, Any, Union, List, Optional, Tuple, Iterable, TYPE_CHECKING
|
2020-08-23 19:32:09 +03:00
|
|
|
import sys
|
2020-08-25 01:30:52 +03:00
|
|
|
import shutil
|
2020-07-09 02:42:51 +03:00
|
|
|
from pathlib import Path
|
|
|
|
from wasabi import msg
|
|
|
|
import srsly
|
2020-07-10 00:51:18 +03:00
|
|
|
import hashlib
|
2020-07-10 18:57:40 +03:00
|
|
|
import typer
|
2020-08-27 19:56:55 +03:00
|
|
|
from click import NoSuchOption
|
2020-09-21 13:50:13 +03:00
|
|
|
from click.parser import split_arg_string
|
2020-07-10 18:57:40 +03:00
|
|
|
from typer.main import get_command
|
2020-07-11 00:34:17 +03:00
|
|
|
from contextlib import contextmanager
|
2020-09-28 16:09:59 +03:00
|
|
|
from thinc.api import Config, ConfigValidationError, require_gpu
|
2020-07-11 00:34:17 +03:00
|
|
|
from configparser import InterpolationError
|
2020-09-21 12:25:10 +03:00
|
|
|
import os
|
2020-07-09 02:42:51 +03:00
|
|
|
|
2020-07-10 18:57:40 +03:00
|
|
|
from ..schemas import ProjectConfigSchema, validate
|
2020-09-21 12:25:10 +03:00
|
|
|
from ..util import import_file, run_command, make_tempdir, registry, logger
|
2021-02-10 05:45:27 +03:00
|
|
|
from ..util import is_compatible_version, SimpleFrozenDict, ENV_VARS
|
2020-10-05 21:00:42 +03:00
|
|
|
from .. import about
|
2020-07-09 02:42:51 +03:00
|
|
|
|
2020-08-23 19:32:09 +03:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from pathy import Pathy # noqa: F401
|
|
|
|
|
2020-07-09 02:42:51 +03:00
|
|
|
|
2021-01-30 13:03:25 +03:00
|
|
|
SDIST_SUFFIX = ".tar.gz"
|
|
|
|
WHEEL_SUFFIX = "-py3-none-any.whl"
|
|
|
|
|
2020-07-09 02:42:51 +03:00
|
|
|
PROJECT_FILE = "project.yml"
|
|
|
|
PROJECT_LOCK = "project.lock"
|
2020-07-10 18:57:40 +03:00
|
|
|
COMMAND = "python -m spacy"
|
|
|
|
NAME = "spacy"
|
|
|
|
HELP = """spaCy Command-line Interface
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/cli
|
2020-07-10 18:57:40 +03:00
|
|
|
"""
|
2020-07-12 14:53:41 +03:00
|
|
|
PROJECT_HELP = f"""Command-line interface for spaCy projects and templates.
|
|
|
|
You'd typically start by cloning a project template to a local directory and
|
|
|
|
fetching its assets like datasets etc. See the project's {PROJECT_FILE} for the
|
|
|
|
available commands.
|
|
|
|
"""
|
|
|
|
DEBUG_HELP = """Suite of helpful commands for debugging and profiling. Includes
|
|
|
|
commands to check and validate your config files, training and evaluation data,
|
|
|
|
and custom model implementations.
|
2020-07-10 18:57:40 +03:00
|
|
|
"""
|
2020-09-03 14:13:03 +03:00
|
|
|
INIT_HELP = """Commands for initializing configs and pipeline packages."""
|
2020-07-10 18:57:40 +03:00
|
|
|
|
|
|
|
# Wrappers for Typer's annotations. Initially created to set defaults and to
|
|
|
|
# keep the names short, but not needed at the moment.
|
|
|
|
Arg = typer.Argument
|
|
|
|
Opt = typer.Option
|
|
|
|
|
|
|
|
app = typer.Typer(name=NAME, help=HELP)
|
|
|
|
project_cli = typer.Typer(name="project", help=PROJECT_HELP, no_args_is_help=True)
|
2020-07-12 14:53:41 +03:00
|
|
|
debug_cli = typer.Typer(name="debug", help=DEBUG_HELP, no_args_is_help=True)
|
2020-08-02 16:18:30 +03:00
|
|
|
init_cli = typer.Typer(name="init", help=INIT_HELP, no_args_is_help=True)
|
2020-07-12 14:53:41 +03:00
|
|
|
|
2020-07-10 18:57:40 +03:00
|
|
|
app.add_typer(project_cli)
|
2020-07-12 14:53:41 +03:00
|
|
|
app.add_typer(debug_cli)
|
2020-08-02 16:18:30 +03:00
|
|
|
app.add_typer(init_cli)
|
2020-07-10 18:57:40 +03:00
|
|
|
|
|
|
|
|
|
|
|
def setup_cli() -> None:
|
2020-09-08 16:23:34 +03:00
|
|
|
# Make sure the entry-point for CLI runs, so that they get imported.
|
|
|
|
registry.cli.get_all()
|
2020-07-10 18:57:40 +03:00
|
|
|
# Ensure that the help messages always display the correct prompt
|
|
|
|
command = get_command(app)
|
|
|
|
command(prog_name=COMMAND)
|
|
|
|
|
|
|
|
|
2020-09-21 13:50:13 +03:00
|
|
|
def parse_config_overrides(
|
2020-09-30 16:15:11 +03:00
|
|
|
args: List[str], env_var: Optional[str] = ENV_VARS.CONFIG_OVERRIDES
|
2020-09-21 12:25:10 +03:00
|
|
|
) -> Dict[str, Any]:
|
2020-07-10 18:57:40 +03:00
|
|
|
"""Generate a dictionary of config overrides based on the extra arguments
|
|
|
|
provided on the CLI, e.g. --training.batch_size to override
|
|
|
|
"training.batch_size". Arguments without a "." are considered invalid,
|
|
|
|
since the config only allows top-level sections to exist.
|
|
|
|
|
2020-09-21 13:50:13 +03:00
|
|
|
env_vars (Optional[str]): Optional environment variable to read from.
|
2020-07-10 18:57:40 +03:00
|
|
|
RETURNS (Dict[str, Any]): The parsed dict, keyed by nested config setting.
|
|
|
|
"""
|
2020-09-21 13:50:13 +03:00
|
|
|
env_string = os.environ.get(env_var, "") if env_var else ""
|
|
|
|
env_overrides = _parse_overrides(split_arg_string(env_string))
|
|
|
|
cli_overrides = _parse_overrides(args, is_cli=True)
|
|
|
|
if cli_overrides:
|
|
|
|
keys = [k for k in cli_overrides if k not in env_overrides]
|
|
|
|
logger.debug(f"Config overrides from CLI: {keys}")
|
|
|
|
if env_overrides:
|
|
|
|
logger.debug(f"Config overrides from env variables: {list(env_overrides)}")
|
|
|
|
return {**cli_overrides, **env_overrides}
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_overrides(args: List[str], is_cli: bool = False) -> Dict[str, Any]:
|
|
|
|
result = {}
|
2020-07-10 18:57:40 +03:00
|
|
|
while args:
|
|
|
|
opt = args.pop(0)
|
2020-09-21 13:50:13 +03:00
|
|
|
err = f"Invalid config override '{opt}'"
|
2020-07-10 18:57:40 +03:00
|
|
|
if opt.startswith("--"): # new argument
|
2020-08-27 19:56:55 +03:00
|
|
|
orig_opt = opt
|
2020-08-18 17:06:37 +03:00
|
|
|
opt = opt.replace("--", "")
|
2020-07-10 18:57:40 +03:00
|
|
|
if "." not in opt:
|
2020-09-21 13:50:13 +03:00
|
|
|
if is_cli:
|
|
|
|
raise NoSuchOption(orig_opt)
|
|
|
|
else:
|
|
|
|
msg.fail(f"{err}: can't override top-level sections", exits=1)
|
2020-07-28 14:43:15 +03:00
|
|
|
if "=" in opt: # we have --opt=value
|
|
|
|
opt, value = opt.split("=", 1)
|
2020-08-18 17:06:37 +03:00
|
|
|
opt = opt.replace("-", "_")
|
2020-07-10 18:57:40 +03:00
|
|
|
else:
|
2020-07-28 14:43:15 +03:00
|
|
|
if not args or args[0].startswith("--"): # flag with no value
|
|
|
|
value = "true"
|
|
|
|
else:
|
|
|
|
value = args.pop(0)
|
2021-02-10 05:45:27 +03:00
|
|
|
result[opt] = _parse_override(value)
|
2020-07-10 18:57:40 +03:00
|
|
|
else:
|
2020-09-21 13:50:13 +03:00
|
|
|
msg.fail(f"{err}: name should start with --", exits=1)
|
|
|
|
return result
|
2020-07-09 02:42:51 +03:00
|
|
|
|
|
|
|
|
2021-02-10 05:45:27 +03:00
|
|
|
def _parse_override(value: Any) -> Any:
|
|
|
|
# Just like we do in the config, we're calling json.loads on the
|
|
|
|
# values. But since they come from the CLI, it'd be unintuitive to
|
|
|
|
# explicitly mark strings with escaped quotes. So we're working
|
|
|
|
# around that here by falling back to a string if parsing fails.
|
|
|
|
# TODO: improve logic to handle simple types like list of strings?
|
|
|
|
try:
|
|
|
|
return srsly.json_loads(value)
|
|
|
|
except ValueError:
|
|
|
|
return str(value)
|
|
|
|
|
|
|
|
|
|
|
|
def load_project_config(
|
|
|
|
path: Path, interpolate: bool = True, overrides: Dict[str, Any] = SimpleFrozenDict()
|
|
|
|
) -> Dict[str, Any]:
|
2020-07-10 00:51:18 +03:00
|
|
|
"""Load the project.yml file from a directory and validate it. Also make
|
|
|
|
sure that all directories defined in the config exist.
|
2020-07-09 02:42:51 +03:00
|
|
|
|
|
|
|
path (Path): The path to the project directory.
|
2020-08-23 19:32:09 +03:00
|
|
|
interpolate (bool): Whether to substitute project variables.
|
2021-02-10 05:45:27 +03:00
|
|
|
overrides (Dict[str, Any]): Optional config overrides.
|
2020-07-09 02:42:51 +03:00
|
|
|
RETURNS (Dict[str, Any]): The loaded project.yml.
|
|
|
|
"""
|
|
|
|
config_path = path / PROJECT_FILE
|
|
|
|
if not config_path.exists():
|
|
|
|
msg.fail(f"Can't find {PROJECT_FILE}", config_path, exits=1)
|
|
|
|
invalid_err = f"Invalid {PROJECT_FILE}. Double-check that the YAML is correct."
|
|
|
|
try:
|
|
|
|
config = srsly.read_yaml(config_path)
|
|
|
|
except ValueError as e:
|
|
|
|
msg.fail(invalid_err, e, exits=1)
|
|
|
|
errors = validate(ProjectConfigSchema, config)
|
|
|
|
if errors:
|
2020-08-23 13:14:02 +03:00
|
|
|
msg.fail(invalid_err)
|
|
|
|
print("\n".join(errors))
|
|
|
|
sys.exit(1)
|
2020-10-05 21:00:42 +03:00
|
|
|
validate_project_version(config)
|
2020-07-09 02:42:51 +03:00
|
|
|
validate_project_commands(config)
|
2020-07-10 00:51:18 +03:00
|
|
|
# Make sure directories defined in config exist
|
|
|
|
for subdir in config.get("directories", []):
|
|
|
|
dir_path = path / subdir
|
|
|
|
if not dir_path.exists():
|
|
|
|
dir_path.mkdir(parents=True)
|
2020-08-23 19:32:09 +03:00
|
|
|
if interpolate:
|
2021-02-10 05:45:27 +03:00
|
|
|
err = f"{PROJECT_FILE} validation error"
|
2020-08-23 19:32:09 +03:00
|
|
|
with show_validation_error(title=err, hint_fill=False):
|
2021-02-10 05:45:27 +03:00
|
|
|
config = substitute_project_variables(config, overrides)
|
2020-07-09 02:42:51 +03:00
|
|
|
return config
|
|
|
|
|
|
|
|
|
2021-02-10 05:45:27 +03:00
|
|
|
def substitute_project_variables(
|
|
|
|
config: Dict[str, Any],
|
|
|
|
overrides: Dict[str, Any] = SimpleFrozenDict(),
|
|
|
|
key: str = "vars",
|
|
|
|
env_key: str = "env",
|
|
|
|
) -> Dict[str, Any]:
|
|
|
|
"""Interpolate variables in the project file using the config system.
|
|
|
|
|
|
|
|
config (Dict[str, Any]): The project config.
|
|
|
|
overrides (Dict[str, Any]): Optional config overrides.
|
|
|
|
key (str): Key containing variables in project config.
|
|
|
|
env_key (str): Key containing environment variable mapping in project config.
|
|
|
|
RETURNS (Dict[str, Any]): The interpolated project config.
|
|
|
|
"""
|
2020-08-23 19:32:09 +03:00
|
|
|
config.setdefault(key, {})
|
2021-02-10 05:45:27 +03:00
|
|
|
config.setdefault(env_key, {})
|
|
|
|
# Substitute references to env vars with their values
|
|
|
|
for config_var, env_var in config[env_key].items():
|
|
|
|
config[env_key][config_var] = _parse_override(os.environ.get(env_var, ""))
|
2020-08-23 19:32:09 +03:00
|
|
|
# Need to put variables in the top scope again so we can have a top-level
|
|
|
|
# section "project" (otherwise, a list of commands in the top scope wouldn't)
|
|
|
|
# be allowed by Thinc's config system
|
2021-02-10 05:45:27 +03:00
|
|
|
cfg = Config({"project": config, key: config[key], env_key: config[env_key]})
|
|
|
|
cfg = Config().from_str(cfg.to_str(), overrides=overrides)
|
2020-08-23 19:32:09 +03:00
|
|
|
interpolated = cfg.interpolate()
|
|
|
|
return dict(interpolated["project"])
|
|
|
|
|
|
|
|
|
2020-10-05 21:00:42 +03:00
|
|
|
def validate_project_version(config: Dict[str, Any]) -> None:
|
|
|
|
"""If the project defines a compatible spaCy version range, chec that it's
|
|
|
|
compatible with the current version of spaCy.
|
|
|
|
|
|
|
|
config (Dict[str, Any]): The loaded config.
|
|
|
|
"""
|
|
|
|
spacy_version = config.get("spacy_version", None)
|
|
|
|
if spacy_version and not is_compatible_version(about.__version__, spacy_version):
|
|
|
|
err = (
|
|
|
|
f"The {PROJECT_FILE} specifies a spaCy version range ({spacy_version}) "
|
|
|
|
f"that's not compatible with the version of spaCy you're running "
|
|
|
|
f"({about.__version__}). You can edit version requirement in the "
|
|
|
|
f"{PROJECT_FILE} to load it, but the project may not run as expected."
|
|
|
|
)
|
|
|
|
msg.fail(err, exits=1)
|
|
|
|
|
|
|
|
|
2020-07-09 02:42:51 +03:00
|
|
|
def validate_project_commands(config: Dict[str, Any]) -> None:
|
|
|
|
"""Check that project commands and workflows are valid, don't contain
|
|
|
|
duplicates, don't clash and only refer to commands that exist.
|
|
|
|
|
|
|
|
config (Dict[str, Any]): The loaded config.
|
|
|
|
"""
|
|
|
|
command_names = [cmd["name"] for cmd in config.get("commands", [])]
|
|
|
|
workflows = config.get("workflows", {})
|
|
|
|
duplicates = set([cmd for cmd in command_names if command_names.count(cmd) > 1])
|
|
|
|
if duplicates:
|
|
|
|
err = f"Duplicate commands defined in {PROJECT_FILE}: {', '.join(duplicates)}"
|
|
|
|
msg.fail(err, exits=1)
|
|
|
|
for workflow_name, workflow_steps in workflows.items():
|
|
|
|
if workflow_name in command_names:
|
|
|
|
err = f"Can't use workflow name '{workflow_name}': name already exists as a command"
|
|
|
|
msg.fail(err, exits=1)
|
|
|
|
for step in workflow_steps:
|
|
|
|
if step not in command_names:
|
|
|
|
msg.fail(
|
|
|
|
f"Unknown command specified in workflow '{workflow_name}': {step}",
|
|
|
|
f"Workflows can only refer to commands defined in the 'commands' "
|
|
|
|
f"section of the {PROJECT_FILE}.",
|
|
|
|
exits=1,
|
|
|
|
)
|
2020-07-10 00:51:18 +03:00
|
|
|
|
|
|
|
|
2020-10-05 14:53:07 +03:00
|
|
|
def get_hash(data, exclude: Iterable[str] = tuple()) -> str:
|
2020-07-10 00:51:18 +03:00
|
|
|
"""Get the hash for a JSON-serializable object.
|
|
|
|
|
|
|
|
data: The data to hash.
|
2020-10-05 14:53:07 +03:00
|
|
|
exclude (Iterable[str]): Top-level keys to exclude if data is a dict.
|
2020-07-10 00:51:18 +03:00
|
|
|
RETURNS (str): The hash.
|
|
|
|
"""
|
2020-10-05 14:53:07 +03:00
|
|
|
if isinstance(data, dict):
|
|
|
|
data = {k: v for k, v in data.items() if k not in exclude}
|
2020-07-10 00:51:18 +03:00
|
|
|
data_str = srsly.json_dumps(data, sort_keys=True).encode("utf8")
|
|
|
|
return hashlib.md5(data_str).hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
def get_checksum(path: Union[Path, str]) -> str:
|
|
|
|
"""Get the checksum for a file or directory given its file path. If a
|
|
|
|
directory path is provided, this uses all files in that directory.
|
|
|
|
|
|
|
|
path (Union[Path, str]): The file or directory path.
|
|
|
|
RETURNS (str): The checksum.
|
|
|
|
"""
|
|
|
|
path = Path(path)
|
|
|
|
if path.is_file():
|
|
|
|
return hashlib.md5(Path(path).read_bytes()).hexdigest()
|
|
|
|
if path.is_dir():
|
|
|
|
# TODO: this is currently pretty slow
|
|
|
|
dir_checksum = hashlib.md5()
|
|
|
|
for sub_file in sorted(fp for fp in path.rglob("*") if fp.is_file()):
|
|
|
|
dir_checksum.update(sub_file.read_bytes())
|
|
|
|
return dir_checksum.hexdigest()
|
2020-08-25 12:54:53 +03:00
|
|
|
msg.fail(f"Can't get checksum for {path}: not a file or directory", exits=1)
|
2020-07-11 00:34:17 +03:00
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
2020-08-02 16:18:30 +03:00
|
|
|
def show_validation_error(
|
|
|
|
file_path: Optional[Union[str, Path]] = None,
|
|
|
|
*,
|
2020-09-26 14:13:57 +03:00
|
|
|
title: Optional[str] = None,
|
|
|
|
desc: str = "",
|
|
|
|
show_config: Optional[bool] = None,
|
2020-08-14 17:49:26 +03:00
|
|
|
hint_fill: bool = True,
|
2020-08-02 16:18:30 +03:00
|
|
|
):
|
2020-07-11 00:34:17 +03:00
|
|
|
"""Helper to show custom config validation errors on the CLI.
|
|
|
|
|
2020-08-02 16:18:30 +03:00
|
|
|
file_path (str / Path): Optional file path of config file, used in hints.
|
2020-09-26 14:13:57 +03:00
|
|
|
title (str): Override title of custom formatted error.
|
|
|
|
desc (str): Override description of custom formatted error.
|
|
|
|
show_config (bool): Whether to output the config the error refers to.
|
2020-08-14 17:49:26 +03:00
|
|
|
hint_fill (bool): Show hint about filling config.
|
2020-07-11 00:34:17 +03:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
yield
|
2020-09-26 14:13:57 +03:00
|
|
|
except ConfigValidationError as e:
|
|
|
|
title = title if title is not None else e.title
|
2020-09-27 23:31:57 +03:00
|
|
|
if e.desc:
|
|
|
|
desc = f"{e.desc}" if not desc else f"{e.desc}\n\n{desc}"
|
2020-09-26 14:13:57 +03:00
|
|
|
# Re-generate a new error object with overrides
|
|
|
|
err = e.from_error(e, title="", desc=desc, show_config=show_config)
|
|
|
|
msg.fail(title)
|
|
|
|
print(err.text.strip())
|
|
|
|
if hint_fill and "value_error.missing" in err.error_types:
|
2020-12-08 12:44:59 +03:00
|
|
|
config_path = (
|
2020-12-08 12:41:18 +03:00
|
|
|
file_path
|
|
|
|
if file_path is not None and str(file_path) != "-"
|
|
|
|
else "config.cfg"
|
|
|
|
)
|
2020-08-02 16:18:30 +03:00
|
|
|
msg.text(
|
|
|
|
"If your config contains missing values, you can run the 'init "
|
2020-08-14 17:49:26 +03:00
|
|
|
"fill-config' command to fill in all the defaults, if possible:",
|
2020-08-02 16:18:30 +03:00
|
|
|
spaced=True,
|
|
|
|
)
|
2020-10-06 10:47:23 +03:00
|
|
|
print(f"{COMMAND} init fill-config {config_path} {config_path} \n")
|
2020-07-11 00:34:17 +03:00
|
|
|
sys.exit(1)
|
2020-09-27 23:41:00 +03:00
|
|
|
except InterpolationError as e:
|
|
|
|
msg.fail("Config validation error", e, exits=1)
|
2020-07-11 14:03:53 +03:00
|
|
|
|
|
|
|
|
|
|
|
def import_code(code_path: Optional[Union[Path, str]]) -> None:
|
|
|
|
"""Helper to import Python file provided in training commands / commands
|
|
|
|
using the config. This makes custom registered functions available.
|
|
|
|
"""
|
|
|
|
if code_path is not None:
|
|
|
|
if not Path(code_path).exists():
|
|
|
|
msg.fail("Path to Python code not found", code_path, exits=1)
|
|
|
|
try:
|
|
|
|
import_file("python_code", code_path)
|
|
|
|
except Exception as e:
|
|
|
|
msg.fail(f"Couldn't load Python code: {code_path}", e, exits=1)
|
2020-08-05 00:39:19 +03:00
|
|
|
|
|
|
|
|
2020-08-23 19:32:09 +03:00
|
|
|
def upload_file(src: Path, dest: Union[str, "Pathy"]) -> None:
|
|
|
|
"""Upload a file.
|
|
|
|
|
|
|
|
src (Path): The source path.
|
|
|
|
url (str): The destination URL to upload to.
|
|
|
|
"""
|
2020-08-25 01:30:52 +03:00
|
|
|
import smart_open
|
2020-08-27 19:56:55 +03:00
|
|
|
|
2020-08-26 16:48:23 +03:00
|
|
|
dest = str(dest)
|
|
|
|
with smart_open.open(dest, mode="wb") as output_file:
|
|
|
|
with src.open(mode="rb") as input_file:
|
|
|
|
output_file.write(input_file.read())
|
2020-08-23 19:32:09 +03:00
|
|
|
|
|
|
|
|
|
|
|
def download_file(src: Union[str, "Pathy"], dest: Path, *, force: bool = False) -> None:
|
|
|
|
"""Download a file using smart_open.
|
|
|
|
|
|
|
|
url (str): The URL of the file.
|
|
|
|
dest (Path): The destination path.
|
|
|
|
force (bool): Whether to force download even if file exists.
|
|
|
|
If False, the download will be skipped.
|
|
|
|
"""
|
2020-08-25 01:30:52 +03:00
|
|
|
import smart_open
|
2020-08-27 19:56:55 +03:00
|
|
|
|
2020-08-23 19:32:09 +03:00
|
|
|
if dest.exists() and not force:
|
|
|
|
return None
|
2020-08-26 16:48:23 +03:00
|
|
|
src = str(src)
|
2020-09-21 17:01:46 +03:00
|
|
|
with smart_open.open(src, mode="rb", ignore_ext=True) as input_file:
|
2020-08-26 16:48:23 +03:00
|
|
|
with dest.open(mode="wb") as output_file:
|
|
|
|
output_file.write(input_file.read())
|
2020-08-23 19:32:09 +03:00
|
|
|
|
|
|
|
|
|
|
|
def ensure_pathy(path):
|
|
|
|
"""Temporary helper to prevent importing Pathy globally (which can cause
|
|
|
|
slow and annoying Google Cloud warning)."""
|
|
|
|
from pathy import Pathy # noqa: F811
|
|
|
|
|
|
|
|
return Pathy(path)
|
2020-08-25 01:30:52 +03:00
|
|
|
|
|
|
|
|
2020-09-14 15:12:58 +03:00
|
|
|
def git_checkout(
|
|
|
|
repo: str, subpath: str, dest: Path, *, branch: str = "master", sparse: bool = False
|
|
|
|
):
|
2020-09-13 11:52:28 +03:00
|
|
|
git_version = get_git_version()
|
2020-08-25 01:30:52 +03:00
|
|
|
if dest.exists():
|
2020-08-25 12:54:53 +03:00
|
|
|
msg.fail("Destination of checkout must not exist", exits=1)
|
2020-08-25 01:30:52 +03:00
|
|
|
if not dest.parent.exists():
|
2020-10-04 12:16:31 +03:00
|
|
|
msg.fail("Parent of destination of checkout must exist", exits=1)
|
2020-09-20 17:22:04 +03:00
|
|
|
if sparse and git_version >= (2, 22):
|
|
|
|
return git_sparse_checkout(repo, subpath, dest, branch)
|
|
|
|
elif sparse:
|
|
|
|
# Only show warnings if the user explicitly wants sparse checkout but
|
|
|
|
# the Git version doesn't support it
|
|
|
|
err_old = (
|
|
|
|
f"You're running an old version of Git (v{git_version[0]}.{git_version[1]}) "
|
|
|
|
f"that doesn't fully support sparse checkout yet."
|
|
|
|
)
|
|
|
|
err_unk = "You're running an unknown version of Git, so sparse checkout has been disabled."
|
|
|
|
msg.warn(
|
|
|
|
f"{err_unk if git_version == (0, 0) else err_old} "
|
|
|
|
f"This means that more files than necessary may be downloaded "
|
|
|
|
f"temporarily. To only download the files needed, make sure "
|
|
|
|
f"you're using Git v2.22 or above."
|
|
|
|
)
|
|
|
|
with make_tempdir() as tmp_dir:
|
|
|
|
cmd = f"git -C {tmp_dir} clone {repo} . -b {branch}"
|
2020-09-21 11:59:07 +03:00
|
|
|
run_command(cmd, capture=True)
|
2020-09-20 17:22:04 +03:00
|
|
|
# We need Path(name) to make sure we also support subdirectories
|
2021-02-01 14:29:04 +03:00
|
|
|
try:
|
|
|
|
shutil.copytree(str(tmp_dir / Path(subpath)), str(dest))
|
|
|
|
except FileNotFoundError:
|
|
|
|
err = f"Can't clone {subpath}. Make sure the directory exists in the repo (branch '{branch}')"
|
|
|
|
msg.fail(err, repo, exits=1)
|
2020-09-20 17:22:04 +03:00
|
|
|
|
|
|
|
|
|
|
|
def git_sparse_checkout(repo, subpath, dest, branch):
|
2020-08-26 05:00:14 +03:00
|
|
|
# We're using Git, partial clone and sparse checkout to
|
|
|
|
# only clone the files we need
|
|
|
|
# This ends up being RIDICULOUS. omg.
|
|
|
|
# So, every tutorial and SO post talks about 'sparse checkout'...But they
|
|
|
|
# go and *clone* the whole repo. Worthless. And cloning part of a repo
|
|
|
|
# turns out to be completely broken. The only way to specify a "path" is..
|
|
|
|
# a path *on the server*? The contents of which, specifies the paths. Wat.
|
|
|
|
# Obviously this is hopelessly broken and insecure, because you can query
|
|
|
|
# arbitrary paths on the server! So nobody enables this.
|
|
|
|
# What we have to do is disable *all* files. We could then just checkout
|
|
|
|
# the path, and it'd "work", but be hopelessly slow...Because it goes and
|
|
|
|
# transfers every missing object one-by-one. So the final piece is that we
|
|
|
|
# need to use some weird git internals to fetch the missings in bulk, and
|
|
|
|
# *that* we can do by path.
|
2020-08-25 01:30:52 +03:00
|
|
|
# We're using Git and sparse checkout to only clone the files we need
|
|
|
|
with make_tempdir() as tmp_dir:
|
2020-08-26 05:00:14 +03:00
|
|
|
# This is the "clone, but don't download anything" part.
|
2020-09-20 17:31:48 +03:00
|
|
|
cmd = (
|
|
|
|
f"git clone {repo} {tmp_dir} --no-checkout --depth 1 "
|
|
|
|
f"-b {branch} --filter=blob:none"
|
|
|
|
)
|
2020-09-20 17:22:04 +03:00
|
|
|
run_command(cmd)
|
2020-08-26 05:00:14 +03:00
|
|
|
# Now we need to find the missing filenames for the subpath we want.
|
|
|
|
# Looking for this 'rev-list' command in the git --help? Hah.
|
2020-09-20 17:30:05 +03:00
|
|
|
cmd = f"git -C {tmp_dir} rev-list --objects --all --missing=print -- {subpath}"
|
2020-09-20 17:22:04 +03:00
|
|
|
ret = run_command(cmd, capture=True)
|
2020-09-22 12:50:19 +03:00
|
|
|
git_repo = _http_to_git(repo)
|
2020-08-26 05:00:14 +03:00
|
|
|
# Now pass those missings into another bit of git internals
|
2020-09-01 20:49:01 +03:00
|
|
|
missings = " ".join([x[1:] for x in ret.stdout.split() if x.startswith("?")])
|
2020-09-20 17:22:04 +03:00
|
|
|
if not missings:
|
2020-09-12 15:43:22 +03:00
|
|
|
err = (
|
|
|
|
f"Could not find any relevant files for '{subpath}'. "
|
|
|
|
f"Did you specify a correct and complete path within repo '{repo}' "
|
|
|
|
f"and branch {branch}?"
|
|
|
|
)
|
|
|
|
msg.fail(err, exits=1)
|
2020-09-20 17:22:04 +03:00
|
|
|
cmd = f"git -C {tmp_dir} fetch-pack {git_repo} {missings}"
|
|
|
|
run_command(cmd, capture=True)
|
2020-08-26 05:00:14 +03:00
|
|
|
# And finally, we can checkout our subpath
|
2020-09-01 20:49:01 +03:00
|
|
|
cmd = f"git -C {tmp_dir} checkout {branch} {subpath}"
|
2020-09-20 17:22:04 +03:00
|
|
|
run_command(cmd, capture=True)
|
2020-08-25 01:30:52 +03:00
|
|
|
# We need Path(name) to make sure we also support subdirectories
|
|
|
|
shutil.move(str(tmp_dir / Path(subpath)), str(dest))
|
2020-09-01 20:49:01 +03:00
|
|
|
|
2020-09-12 15:43:22 +03:00
|
|
|
|
2020-09-13 11:52:28 +03:00
|
|
|
def get_git_version(
|
|
|
|
error: str = "Could not run 'git'. Make sure it's installed and the executable is available.",
|
|
|
|
) -> Tuple[int, int]:
|
|
|
|
"""Get the version of git and raise an error if calling 'git --version' fails.
|
|
|
|
|
|
|
|
error (str): The error message to show.
|
|
|
|
RETURNS (Tuple[int, int]): The version as a (major, minor) tuple. Returns
|
|
|
|
(0, 0) if the version couldn't be determined.
|
|
|
|
"""
|
2020-09-20 17:22:04 +03:00
|
|
|
ret = run_command("git --version", capture=True)
|
2020-09-13 11:52:28 +03:00
|
|
|
stdout = ret.stdout.strip()
|
|
|
|
if not stdout or not stdout.startswith("git version"):
|
|
|
|
return (0, 0)
|
|
|
|
version = stdout[11:].strip().split(".")
|
2020-09-10 16:49:13 +03:00
|
|
|
return (int(version[0]), int(version[1]))
|
|
|
|
|
|
|
|
|
2020-09-22 12:50:19 +03:00
|
|
|
def _http_to_git(repo: str) -> str:
|
2020-09-01 20:49:01 +03:00
|
|
|
if repo.startswith("http://"):
|
|
|
|
repo = repo.replace(r"http://", r"https://")
|
|
|
|
if repo.startswith(r"https://"):
|
|
|
|
repo = repo.replace("https://", "git@").replace("/", ":", 1)
|
2020-09-10 18:39:52 +03:00
|
|
|
if repo.endswith("/"):
|
|
|
|
repo = repo[:-1]
|
2020-09-01 20:49:01 +03:00
|
|
|
repo = f"{repo}.git"
|
|
|
|
return repo
|
2020-09-12 15:43:22 +03:00
|
|
|
|
|
|
|
|
2020-09-13 11:52:02 +03:00
|
|
|
def string_to_list(value: str, intify: bool = False) -> Union[List[str], List[int]]:
|
|
|
|
"""Parse a comma-separated string to a list and account for various
|
|
|
|
formatting options. Mostly used to handle CLI arguments that take a list of
|
|
|
|
comma-separated values.
|
|
|
|
|
|
|
|
value (str): The value to parse.
|
|
|
|
intify (bool): Whether to convert values to ints.
|
|
|
|
RETURNS (Union[List[str], List[int]]): A list of strings or ints.
|
|
|
|
"""
|
2020-09-12 15:43:22 +03:00
|
|
|
if not value:
|
|
|
|
return []
|
|
|
|
if value.startswith("[") and value.endswith("]"):
|
|
|
|
value = value[1:-1]
|
|
|
|
result = []
|
|
|
|
for p in value.split(","):
|
|
|
|
p = p.strip()
|
|
|
|
if p.startswith("'") and p.endswith("'"):
|
|
|
|
p = p[1:-1]
|
|
|
|
if p.startswith('"') and p.endswith('"'):
|
|
|
|
p = p[1:-1]
|
|
|
|
p = p.strip()
|
|
|
|
if intify:
|
|
|
|
p = int(p)
|
|
|
|
result.append(p)
|
|
|
|
return result
|
2020-09-28 16:09:59 +03:00
|
|
|
|
|
|
|
|
2020-09-28 22:17:10 +03:00
|
|
|
def setup_gpu(use_gpu: int) -> None:
|
|
|
|
"""Configure the GPU and log info."""
|
2020-09-28 16:09:59 +03:00
|
|
|
if use_gpu >= 0:
|
|
|
|
msg.info(f"Using GPU: {use_gpu}")
|
|
|
|
require_gpu(use_gpu)
|
|
|
|
else:
|
|
|
|
msg.info("Using CPU")
|