Merge branch 'master' into opt-validate

This commit is contained in:
Ruslan Kuprieiev
2019-11-20 11:00:28 +02:00
committed by GitHub
21 changed files with 184 additions and 74 deletions
+13 -2
View File
@@ -59,10 +59,12 @@ class OutputNotFoundError(DvcException):
output (unicode): path to the file/directory.
"""
def __init__(self, output):
def __init__(self, output, repo=None):
self.output = output
self.repo = repo
super(OutputNotFoundError, self).__init__(
"unable to find DVC-file with output '{path}'".format(
path=relpath(output)
path=relpath(self.output)
)
)
@@ -338,3 +340,12 @@ class RemoteNotSpecifiedInExternalRepoError(DvcException):
),
cause=cause,
)
class NoOutputInExternalRepoError(DvcException):
def __init__(self, path, external_repo_path, external_repo_url):
super(NoOutputInExternalRepoError, self).__init__(
"Output '{}' not found in target repository '{}'".format(
relpath(path, external_repo_path), external_repo_url
)
)
+7 -1
View File
@@ -9,7 +9,9 @@ from funcy import retry
from dvc.config import NoRemoteError
from dvc.exceptions import RemoteNotSpecifiedInExternalRepoError
from dvc.utils import remove
from dvc.exceptions import NoOutputInExternalRepoError
from dvc.exceptions import OutputNotFoundError
from dvc.utils.fs import remove
REPO_CACHE = {}
@@ -25,6 +27,10 @@ def external_repo(url=None, rev=None, rev_lock=None, cache_dir=None):
yield repo
except NoRemoteError as exc:
raise RemoteNotSpecifiedInExternalRepoError(url, cause=exc)
except OutputNotFoundError as exc:
if exc.repo is repo:
raise NoOutputInExternalRepoError(exc.output, repo.root_dir, url)
raise
repo.close()
+1 -1
View File
@@ -26,13 +26,13 @@ from dvc.utils import copyfile
from dvc.utils import file_md5
from dvc.utils import makedirs
from dvc.utils import relpath
from dvc.utils import remove
from dvc.utils import tmp_fname
from dvc.utils import walk_files
from dvc.utils.compat import fspath_py35
from dvc.utils.compat import open
from dvc.utils.compat import str
from dvc.utils.fs import move
from dvc.utils.fs import remove
logger = logging.getLogger(__name__)
+1 -1
View File
@@ -435,7 +435,7 @@ class Repo(object):
matched = list(filter(func, outs))
if not matched:
raise OutputNotFoundError(path)
raise OutputNotFoundError(path, self)
return matched
+1 -1
View File
@@ -1,4 +1,4 @@
from dvc.utils import remove
from dvc.utils.fs import remove
def destroy(self):
+1 -1
View File
@@ -11,8 +11,8 @@ from dvc.external_repo import external_repo
from dvc.path_info import PathInfo
from dvc.stage import Stage
from dvc.state import StateNoop
from dvc.utils import remove
from dvc.utils import resolve_output
from dvc.utils.fs import remove
logger = logging.getLogger(__name__)
+1 -1
View File
@@ -11,7 +11,7 @@ from dvc.scm import NoSCM
from dvc.scm import SCM
from dvc.utils import boxify
from dvc.utils import relpath
from dvc.utils import remove
from dvc.utils.fs import remove
logger = logging.getLogger(__name__)
+27 -13
View File
@@ -22,7 +22,8 @@ from dvc.utils import relpath
from dvc.utils.collections import apply_diff
from dvc.utils.fs import contains_symlink_up_to
from dvc.utils.stage import dump_stage_file
from dvc.utils.stage import load_stage_fd
from dvc.utils.stage import parse_stage
from dvc.utils.stage import parse_stage_for_update
logger = logging.getLogger(__name__)
@@ -166,8 +167,8 @@ class Stage(object):
md5=None,
locked=False,
tag=None,
state=None,
always_changed=False,
stage_text=None,
):
if deps is None:
deps = []
@@ -184,7 +185,7 @@ class Stage(object):
self.locked = locked
self.tag = tag
self.always_changed = always_changed
self._state = state or {}
self._stage_text = stage_text
def __repr__(self):
return "Stage: '{path}'".format(
@@ -355,7 +356,7 @@ class Stage(object):
@staticmethod
def validate(d, fname=None):
from dvc.utils import convert_to_unicode
from dvc.utils.compat import convert_to_unicode
try:
Stage.COMPILED_SCHEMA(convert_to_unicode(d))
@@ -609,10 +610,8 @@ class Stage(object):
Stage._check_isfile(repo, fname)
with repo.tree.open(fname) as fd:
d = load_stage_fd(fd, fname)
# Making a deepcopy since the original structure
# looses keys in deps and outs load
state = copy.deepcopy(d)
stage_text = fd.read()
d = parse_stage(stage_text, fname)
Stage.validate(d, fname=relpath(fname))
path = os.path.abspath(fname)
@@ -630,7 +629,8 @@ class Stage(object):
locked=d.get(Stage.PARAM_LOCKED, False),
tag=tag,
always_changed=d.get(Stage.PARAM_ALWAYS_CHANGED, False),
state=state,
# We store stage text to apply updates to the same structure
stage_text=stage_text,
)
stage.deps = dependency.loadd_from(stage, d.get(Stage.PARAM_DEPS, []))
@@ -653,7 +653,6 @@ class Stage(object):
Stage.PARAM_LOCKED: self.locked,
Stage.PARAM_DEPS: [d.dumpd() for d in self.deps],
Stage.PARAM_OUTS: [o.dumpd() for o in self.outs],
Stage.PARAM_META: self._state.get("meta"),
Stage.PARAM_ALWAYS_CHANGED: self.always_changed,
}.items()
if value
@@ -667,9 +666,24 @@ class Stage(object):
logger.debug(
"Saving information to '{file}'.".format(file=relpath(fname))
)
d = self.dumpd()
apply_diff(d, self._state)
dump_stage_file(fname, self._state)
state = self.dumpd()
# When we load a stage we parse yaml with a fast parser, which strips
# off all the comments and formatting. To retain those on update we do
# a trick here:
# - reparse the same yaml text with a slow but smart ruamel yaml parser
# - apply changes to a returned structure
# - serialize it
if self._stage_text is not None:
saved_state = parse_stage_for_update(self._stage_text, fname)
# Stage doesn't work with meta in any way, so .dumpd() doesn't
# have it. We simply copy it over.
if "meta" in saved_state:
state["meta"] = saved_state["meta"]
apply_diff(state, saved_state)
state = saved_state
dump_stage_file(fname, state)
self.repo.scm.track_file(relpath(fname))
+1 -1
View File
@@ -10,7 +10,6 @@ from dvc.config import Config
from dvc.exceptions import DvcException
from dvc.utils import current_timestamp
from dvc.utils import relpath
from dvc.utils import remove
from dvc.utils import to_chunks
from dvc.utils.compat import fspath_py35
from dvc.utils.compat import is_py2
@@ -18,6 +17,7 @@ from dvc.utils.compat import urlencode
from dvc.utils.compat import urlunparse
from dvc.utils.fs import get_inode
from dvc.utils.fs import get_mtime_and_size
from dvc.utils.fs import remove
SQLITE_MAX_VARIABLES_NUMBER = 999
+5 -42
View File
@@ -1,15 +1,12 @@
"""Helpers for other modules."""
from __future__ import unicode_literals
import errno
import hashlib
import json
import logging
import math
import os
import re
import shutil
import stat
import sys
import time
@@ -152,40 +149,16 @@ def makedirs(path, exist_ok=False, mode=None):
_makedirs(path, exist_ok=exist_ok)
return
umask = os.umask(0)
# utilize umask to set proper permissions since Python 3.7 the `mode`
# `makedirs` argument no longer affects the file permission bits of
# newly-created intermediate-level directories.
umask = os.umask(0o777 - mode)
try:
_makedirs(path, exist_ok=exist_ok, mode=mode)
_makedirs(path, exist_ok=exist_ok)
finally:
os.umask(umask)
def _chmod(func, p, excinfo):
perm = os.lstat(p).st_mode
perm |= stat.S_IWRITE
try:
os.chmod(p, perm)
except OSError as exc:
# broken symlink or file is not owned by us
if exc.errno not in [errno.ENOENT, errno.EPERM]:
raise
func(p)
def remove(path):
logger.debug("Removing '{}'".format(relpath(path)))
try:
if os.path.isdir(path):
shutil.rmtree(path, onerror=_chmod)
else:
_chmod(os.unlink, path, None)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
def _split(list_to_split, chunk_size):
return [
list_to_split[i : i + chunk_size]
@@ -292,16 +265,6 @@ def fix_env(env=None):
return env
def convert_to_unicode(data):
if isinstance(data, builtin_str):
return str(data)
if isinstance(data, dict):
return dict(map(convert_to_unicode, data.items()))
if isinstance(data, (list, tuple)):
return type(data)(map(convert_to_unicode, data))
return data
def tmp_fname(fname):
""" Temporary name for a partial download """
return fspath(fname) + "." + str(uuid()) + ".tmp"
+12 -2
View File
@@ -85,8 +85,6 @@ def _makedirs(name, mode=0o777, exist_ok=False):
if e.errno != errno.EEXIST:
raise
cdir = os.curdir
if isinstance(tail, bytes):
cdir = bytes(os.curdir, "ASCII")
if tail == cdir:
return
try:
@@ -143,6 +141,15 @@ if is_py2:
def __exit__(self, *args):
self.close()
def convert_to_unicode(data):
if isinstance(data, builtin_str):
return str(data)
if isinstance(data, dict):
return dict(map(convert_to_unicode, data.items()))
if isinstance(data, (list, tuple)):
return type(data)(map(convert_to_unicode, data))
return data
elif is_py3:
import pathlib # noqa: F401
@@ -170,6 +177,9 @@ elif is_py3:
range = range # noqa: F821
FileNotFoundError = FileNotFoundError
def convert_to_unicode(data):
return data
# Backport os.fspath() from Python 3.6
try:
+31
View File
@@ -4,6 +4,7 @@ import errno
import logging
import os
import shutil
import stat
import nanotime
from shortuuid import uuid
@@ -13,6 +14,7 @@ from dvc.system import System
from dvc.utils import dict_md5
from dvc.utils import fspath
from dvc.utils import fspath_py35
from dvc.utils import relpath
from dvc.utils import walk_files
from dvc.utils.compat import str
@@ -103,3 +105,32 @@ def move(src, dst, mode=None):
os.chmod(tmp, mode)
shutil.move(tmp, dst)
def _chmod(func, p, excinfo):
perm = os.lstat(p).st_mode
perm |= stat.S_IWRITE
try:
os.chmod(p, perm)
except OSError as exc:
# broken symlink or file is not owned by us
if exc.errno not in [errno.ENOENT, errno.EPERM]:
raise
func(p)
def remove(path):
path = fspath_py35(path)
logger.debug("Removing '{}'".format(relpath(path)))
try:
if os.path.isdir(path):
shutil.rmtree(path, onerror=_chmod)
else:
_chmod(os.unlink, path, None)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
+24 -3
View File
@@ -1,19 +1,40 @@
import yaml
from ruamel.yaml import YAML
from ruamel.yaml.error import YAMLError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader
from dvc.exceptions import StageFileCorruptedError
from dvc.utils.compat import open
def load_stage_file(path):
with open(path, "r", encoding="utf-8") as fd:
return load_stage_fd(fd, path)
return parse_stage(fd.read(), path)
def load_stage_fd(fd, path):
def parse_stage(text, path):
try:
return yaml.load(text, Loader=SafeLoader) or {}
except yaml.error.YAMLError as exc:
raise StageFileCorruptedError(path, cause=exc)
def parse_stage_for_update(text, path):
"""Parses text into Python structure.
Unlike `parse_stage()` this returns ordereddicts, values have special
attributes to store comments and line breaks. This allows us to preserve
all of those upon dump.
This one is, however, several times slower than simple `parse_stage()`.
"""
try:
yaml = YAML()
return yaml.load(fd) or {}
return yaml.load(text) or {}
except YAMLError as exc:
raise StageFileCorruptedError(path, cause=exc)
+1 -1
View File
@@ -7,7 +7,7 @@ import os
import subprocess
_BASE_VERSION = "0.68.1"
_BASE_VERSION = "0.70.0"
def _generate_version(base_version):
+2 -1
View File
@@ -72,6 +72,7 @@ install_requires = [
"treelib>=1.5.5",
"inflect>=2.1.0",
"humanize>=0.5.1",
"PyYAML>=5.1.2",
"ruamel.yaml>=0.16.1",
"funcy>=1.12",
"pathspec>=0.6.0",
@@ -116,7 +117,7 @@ tests_requirements = [
"pytest-timeout>=1.3.3",
"pytest-cov>=2.6.1",
"pytest-xdist>=1.26.1",
"pytest-mock>=1.10.4",
"pytest-mock==1.11.2",
"flaky>=3.5.3",
"mock>=3.0.0",
"xmltodict>=0.11.0",
+1 -1
View File
@@ -13,9 +13,9 @@ from git import Repo
from git.exc import GitCommandNotFound
from dvc.repo import Repo as DvcRepo
from dvc.utils import remove
from dvc.utils.compat import open
from dvc.utils.compat import str
from dvc.utils.fs import remove
logger = logging.getLogger("dvc")
+6 -1
View File
@@ -8,7 +8,7 @@ import pytest
from mock import patch
from dvc.config import Config
from dvc.exceptions import DownloadError
from dvc.exceptions import DownloadError, NoOutputInExternalRepoError
from dvc.stage import Stage
from dvc.system import System
from dvc.utils import makedirs
@@ -154,3 +154,8 @@ def test_pull_non_workspace(git, dvc_repo, erepo):
os.remove(stage.outs[0].cache_path)
dvc_repo.fetch(all_tags=True)
assert os.path.exists(stage.outs[0].cache_path)
def test_import_non_existing(dvc_repo, erepo):
with pytest.raises(NoOutputInExternalRepoError):
dvc_repo.imp(erepo.root_dir, "invalid_output")
+19
View File
@@ -1,6 +1,10 @@
# encoding: utf-8
import filecmp
import os
import shutil
import stat
import pytest
from dvc import utils
from tests.basic_env import TestDvc
@@ -69,3 +73,18 @@ class TestUtils(TestDvc):
)
assert expected == utils.boxify("message")
@pytest.mark.skipif(os.name == "nt", reason="Not supported for Windows.")
def test_makedirs_permissions(tmpdir):
dir_mode = 0o755
os.chdir(str(tmpdir))
intermediate_dir = "тестовая-директория"
test_dir = os.path.join(intermediate_dir, "data")
assert not os.path.exists(intermediate_dir)
utils.makedirs(test_dir, mode=dir_mode)
assert stat.S_IMODE(os.stat(test_dir).st_mode) == dir_mode
assert stat.S_IMODE(os.stat(intermediate_dir).st_mode) == dir_mode
+1 -1
View File
@@ -2,7 +2,7 @@ from dvc.cli import parse_args
from dvc.command.update import CmdUpdate
def test_update(mocker):
def test_update(dvc_repo, mocker):
targets = ["target1", "target2", "target3"]
cli_args = parse_args(["update"] + targets)
assert cli_args.func == CmdUpdate
+12
View File
@@ -16,6 +16,7 @@ from dvc.utils.fs import contains_symlink_up_to
from dvc.utils.fs import get_inode
from dvc.utils.fs import get_mtime_and_size
from dvc.utils.fs import move
from dvc.utils.fs import remove
from tests.basic_env import TestDir
from tests.utils import spy
@@ -152,3 +153,14 @@ def test_move(repo_dir):
move(src_info, dest_info)
assert not os.path.isfile(src_info.fspath)
assert len(os.listdir(dest_info.fspath)) == 1
def test_remove(repo_dir):
path = repo_dir.FOO
path_info = PathInfo(repo_dir.BAR)
remove(path)
assert not os.path.isfile(path)
remove(path_info)
assert not os.path.isfile(path_info.fspath)
+17
View File
@@ -1,4 +1,5 @@
import filecmp
import re
import os
import pytest
@@ -9,6 +10,7 @@ from dvc.utils import file_md5
from dvc.utils import fix_env
from dvc.utils import makedirs
from dvc.utils import to_chunks
from dvc.utils import tmp_fname
from tests.basic_env import TestDir
@@ -122,3 +124,18 @@ def test_makedirs(repo_dir):
makedirs(path_info)
assert os.path.isdir(path_info.fspath)
def test_tmp_fname():
file_path = os.path.join("path", "to", "file")
file_path_info = PathInfo(file_path)
def pattern(path):
return r"^" + re.escape(path) + r"\.[a-z0-9]{22}\.tmp$"
assert re.search(pattern(file_path), tmp_fname(file_path), re.IGNORECASE)
assert re.search(
pattern(file_path_info.fspath),
tmp_fname(file_path_info),
re.IGNORECASE,
)