From 58c9e5557ced5ae7e6c9c0a1643d84ea8e07ddcb Mon Sep 17 00:00:00 2001 From: Alexander Schepanovski Date: Mon, 11 Nov 2019 13:41:50 +0100 Subject: [PATCH 01/20] perf: optimize yaml parsing for stages --- dvc/stage.py | 33 ++++++++++++++++++++------------- dvc/utils/stage.py | 19 ++++++++++++++++--- setup.py | 1 + 3 files changed, 37 insertions(+), 16 deletions(-) diff --git a/dvc/stage.py b/dvc/stage.py index d408019dc..32e8204bf 100644 --- a/dvc/stage.py +++ b/dvc/stage.py @@ -1,6 +1,5 @@ from __future__ import unicode_literals -import copy import logging import os import re @@ -27,7 +26,8 @@ from dvc.utils.compat import pathlib from dvc.utils.compat import str 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__) @@ -170,8 +170,8 @@ class Stage(object): md5=None, locked=False, tag=None, - state=None, always_changed=False, + stage_text=None, ): if deps is None: deps = [] @@ -188,7 +188,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( @@ -613,10 +613,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) @@ -634,7 +632,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, [])) @@ -657,7 +656,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 @@ -671,9 +669,18 @@ 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() + + # If we have stage file we apply diffs instead of overwriting it + # to preserve comments, string formatting and meta key. + if self._stage_text is not None: + saved_state = parse_stage_for_update(self._stage_text, fname) + 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)) diff --git a/dvc/utils/stage.py b/dvc/utils/stage.py index 7d5eb8116..2d3f31618 100644 --- a/dvc/utils/stage.py +++ b/dvc/utils/stage.py @@ -1,19 +1,32 @@ +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): try: yaml = YAML() - return yaml.load(fd) or {} + return yaml.load(text) or {} except YAMLError as exc: raise StageFileCorruptedError(path, cause=exc) diff --git a/setup.py b/setup.py index 00bd03bf6..d8f08940a 100644 --- a/setup.py +++ b/setup.py @@ -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", From 329d072c2241f9414b87f84d95b6b1e1a92d7313 Mon Sep 17 00:00:00 2001 From: Alexander Schepanovski Date: Wed, 13 Nov 2019 16:35:05 +0100 Subject: [PATCH 02/20] perf: explain why two yaml parsers are used --- dvc/stage.py | 10 ++++++++-- dvc/utils/stage.py | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/dvc/stage.py b/dvc/stage.py index 32e8204bf..48820cd86 100644 --- a/dvc/stage.py +++ b/dvc/stage.py @@ -671,10 +671,16 @@ class Stage(object): ) state = self.dumpd() - # If we have stage file we apply diffs instead of overwriting it - # to preserve comments, string formatting and meta key. + # 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) diff --git a/dvc/utils/stage.py b/dvc/utils/stage.py index 2d3f31618..c3a4b0e66 100644 --- a/dvc/utils/stage.py +++ b/dvc/utils/stage.py @@ -24,6 +24,14 @@ def parse_stage(text, path): 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(text) or {} From 2b934470b47bc3c66f0fc688e4fe7b1c16813e9d Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 13 Nov 2019 14:12:01 -0800 Subject: [PATCH 03/20] makedirs: fix mode flag is being ignored starting from Python 3.7 --- dvc/utils/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dvc/utils/__init__.py b/dvc/utils/__init__.py index 864c9e5f5..350a6c3bc 100644 --- a/dvc/utils/__init__.py +++ b/dvc/utils/__init__.py @@ -152,9 +152,9 @@ def makedirs(path, exist_ok=False, mode=None): _makedirs(path, exist_ok=exist_ok) return - umask = os.umask(0) + umask = os.umask(0o777 - mode) try: - _makedirs(path, exist_ok=exist_ok, mode=mode) + _makedirs(path, exist_ok=exist_ok) finally: os.umask(umask) From eec7618f49c9180338af02362b0b44ea7044dd4c Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 13 Nov 2019 16:58:51 -0800 Subject: [PATCH 04/20] tests: makedirs permissions on intermediate dirs --- tests/func/test_utils.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/func/test_utils.py b/tests/func/test_utils.py index 73f489e25..3ea25eed5 100644 --- a/tests/func/test_utils.py +++ b/tests/func/test_utils.py @@ -1,6 +1,9 @@ import filecmp import os import shutil +import stat + +import pytest from dvc import utils from tests.basic_env import TestDvc @@ -69,3 +72,16 @@ class TestUtils(TestDvc): ) assert expected == utils.boxify("message") + + +@pytest.mark.skipif(os.name == "nt", reason="Not supported for Windows.") +def test_makedirs_permissions(): + dir_mode = 0o755 + intermediate_dir = "testdir" + test_dir = os.path.join(intermediate_dir, "data") + 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 + + shutil.rmtree(test_dir) From 636d850c848a8ce90c037901621a1c391283d8ae Mon Sep 17 00:00:00 2001 From: Aman Sharma Date: Fri, 15 Nov 2019 01:54:40 +0530 Subject: [PATCH 05/20] Ensure `remove` accepts str and Path-like objects --- dvc/external_repo.py | 2 +- dvc/remote/local.py | 2 +- dvc/repo/destroy.py | 2 +- dvc/repo/get.py | 2 +- dvc/repo/init.py | 2 +- dvc/state.py | 2 +- dvc/utils/__init__.py | 14 -------------- dvc/utils/fs.py | 17 +++++++++++++++++ tests/basic_env.py | 2 +- tests/unit/utils/test_fs.py | 12 ++++++++++++ 10 files changed, 36 insertions(+), 21 deletions(-) diff --git a/dvc/external_repo.py b/dvc/external_repo.py index 874240bc7..46657fc4d 100644 --- a/dvc/external_repo.py +++ b/dvc/external_repo.py @@ -9,7 +9,7 @@ from funcy import retry from dvc.config import NoRemoteError from dvc.exceptions import RemoteNotSpecifiedInExternalRepoError -from dvc.utils import remove +from dvc.utils.fs import remove REPO_CACHE = {} diff --git a/dvc/remote/local.py b/dvc/remote/local.py index 2145fc170..bd20e91b5 100644 --- a/dvc/remote/local.py +++ b/dvc/remote/local.py @@ -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__) diff --git a/dvc/repo/destroy.py b/dvc/repo/destroy.py index e5938e195..0f9272854 100644 --- a/dvc/repo/destroy.py +++ b/dvc/repo/destroy.py @@ -1,4 +1,4 @@ -from dvc.utils import remove +from dvc.utils.fs import remove def destroy(self): diff --git a/dvc/repo/get.py b/dvc/repo/get.py index 011700684..21d01ed7e 100644 --- a/dvc/repo/get.py +++ b/dvc/repo/get.py @@ -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__) diff --git a/dvc/repo/init.py b/dvc/repo/init.py index fce49b7d7..e06307e0a 100644 --- a/dvc/repo/init.py +++ b/dvc/repo/init.py @@ -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__) diff --git a/dvc/state.py b/dvc/state.py index a7d6f733d..6ef52a114 100644 --- a/dvc/state.py +++ b/dvc/state.py @@ -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 diff --git a/dvc/utils/__init__.py b/dvc/utils/__init__.py index 864c9e5f5..a31884211 100644 --- a/dvc/utils/__init__.py +++ b/dvc/utils/__init__.py @@ -8,7 +8,6 @@ import logging import math import os import re -import shutil import stat import sys import time @@ -173,19 +172,6 @@ def _chmod(func, p, excinfo): 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] diff --git a/dvc/utils/fs.py b/dvc/utils/fs.py index 76be6f9a0..eff297693 100644 --- a/dvc/utils/fs.py +++ b/dvc/utils/fs.py @@ -10,9 +10,11 @@ from shortuuid import uuid from dvc.exceptions import DvcException from dvc.system import System +from dvc.utils import _chmod 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,18 @@ def move(src, dst, mode=None): os.chmod(tmp, mode) shutil.move(tmp, dst) + + +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 diff --git a/tests/basic_env.py b/tests/basic_env.py index ae80d60e5..1fba67a55 100644 --- a/tests/basic_env.py +++ b/tests/basic_env.py @@ -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") diff --git a/tests/unit/utils/test_fs.py b/tests/unit/utils/test_fs.py index 32fa749a5..a8faabb0c 100644 --- a/tests/unit/utils/test_fs.py +++ b/tests/unit/utils/test_fs.py @@ -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) From 303d52e4acdc33dea6e3e89ffd2213cbbc8a4505 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 14 Nov 2019 14:32:52 -0800 Subject: [PATCH 06/20] tests: fix mkdirs permissions test to cleanup after failure --- tests/func/test_utils.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/func/test_utils.py b/tests/func/test_utils.py index 3ea25eed5..c764a80e4 100644 --- a/tests/func/test_utils.py +++ b/tests/func/test_utils.py @@ -1,3 +1,4 @@ +# encoding: utf-8 import filecmp import os import shutil @@ -77,11 +78,14 @@ class TestUtils(TestDvc): @pytest.mark.skipif(os.name == "nt", reason="Not supported for Windows.") def test_makedirs_permissions(): dir_mode = 0o755 - intermediate_dir = "testdir" + intermediate_dir = "тестовая-директория" test_dir = os.path.join(intermediate_dir, "data") - 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 + assert not os.path.exists(intermediate_dir) - shutil.rmtree(test_dir) + try: + 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 + finally: + shutil.rmtree(intermediate_dir) From ecfbc3a6de136bf5881891c2f0a03265ba423c2d Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 14 Nov 2019 14:33:36 -0800 Subject: [PATCH 07/20] compat: fix py2 mkdirs implementation, bytes do not exist on py2 --- dvc/utils/compat.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/dvc/utils/compat.py b/dvc/utils/compat.py index 7d66dd090..4863e4a56 100644 --- a/dvc/utils/compat.py +++ b/dvc/utils/compat.py @@ -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: From 3943b0eb57bd46ab50901548f3100bf7906c17a2 Mon Sep 17 00:00:00 2001 From: Alexander Schepanovski Date: Wed, 13 Nov 2019 18:21:26 +0100 Subject: [PATCH 08/20] perf: a small stage validation optimization --- dvc/stage.py | 2 +- dvc/utils/__init__.py | 10 ---------- dvc/utils/compat.py | 12 ++++++++++++ 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/dvc/stage.py b/dvc/stage.py index d408019dc..45c7ddf7a 100644 --- a/dvc/stage.py +++ b/dvc/stage.py @@ -359,7 +359,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: Schema(Stage.SCHEMA).validate(convert_to_unicode(d)) diff --git a/dvc/utils/__init__.py b/dvc/utils/__init__.py index 864c9e5f5..dc6e394a5 100644 --- a/dvc/utils/__init__.py +++ b/dvc/utils/__init__.py @@ -292,16 +292,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" diff --git a/dvc/utils/compat.py b/dvc/utils/compat.py index 7d66dd090..c34d800d8 100644 --- a/dvc/utils/compat.py +++ b/dvc/utils/compat.py @@ -143,6 +143,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 +179,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: From d9cd9ece8b7dd296617a3488be006e46248bd9b6 Mon Sep 17 00:00:00 2001 From: Aman Sharma Date: Sat, 16 Nov 2019 00:44:20 +0530 Subject: [PATCH 09/20] Move `_chmod` to fs.py --- dvc/utils/__init__.py | 16 ---------------- dvc/utils/fs.py | 16 +++++++++++++++- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/dvc/utils/__init__.py b/dvc/utils/__init__.py index a31884211..61b25eee1 100644 --- a/dvc/utils/__init__.py +++ b/dvc/utils/__init__.py @@ -1,14 +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 stat import sys import time @@ -158,20 +156,6 @@ def makedirs(path, exist_ok=False, mode=None): 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 _split(list_to_split, chunk_size): return [ list_to_split[i : i + chunk_size] diff --git a/dvc/utils/fs.py b/dvc/utils/fs.py index eff297693..c73a23563 100644 --- a/dvc/utils/fs.py +++ b/dvc/utils/fs.py @@ -4,13 +4,13 @@ import errno import logging import os import shutil +import stat import nanotime from shortuuid import uuid from dvc.exceptions import DvcException from dvc.system import System -from dvc.utils import _chmod from dvc.utils import dict_md5 from dvc.utils import fspath from dvc.utils import fspath_py35 @@ -107,6 +107,20 @@ def move(src, dst, mode=None): 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) From 3edad21b41c267700a64bbf3485f96958ade01e7 Mon Sep 17 00:00:00 2001 From: Aman Sharma Date: Mon, 18 Nov 2019 01:44:54 +0530 Subject: [PATCH 10/20] Write test for `tmp_fname` to check if it accepts Path-like and str objects --- tests/unit/utils/test_utils.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/unit/utils/test_utils.py b/tests/unit/utils/test_utils.py index 6d4aba0bc..6b4f75a53 100644 --- a/tests/unit/utils/test_utils.py +++ b/tests/unit/utils/test_utils.py @@ -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, + ) From 0ac18fb05109187d89ff634002a5247a62de7a47 Mon Sep 17 00:00:00 2001 From: Ruslan Kuprieiev Date: Mon, 18 Nov 2019 15:13:19 +0200 Subject: [PATCH 11/20] dvc: bump to 0.69.0 --- dvc/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dvc/version.py b/dvc/version.py index 038469215..6af6b2b5a 100644 --- a/dvc/version.py +++ b/dvc/version.py @@ -7,7 +7,7 @@ import os import subprocess -_BASE_VERSION = "0.68.1" +_BASE_VERSION = "0.69.0" def _generate_version(base_version): From aa6a77285d7173c13c01ca12636a47dff919d1da Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Tue, 19 Nov 2019 00:17:27 -0800 Subject: [PATCH 12/20] makedirs: add comment on why do have to use umask --- dvc/utils/__init__.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dvc/utils/__init__.py b/dvc/utils/__init__.py index 350a6c3bc..a7e9ab5f4 100644 --- a/dvc/utils/__init__.py +++ b/dvc/utils/__init__.py @@ -152,6 +152,9 @@ def makedirs(path, exist_ok=False, mode=None): _makedirs(path, exist_ok=exist_ok) return + # 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) From 1c752a9548b922f3207fdb4991130acb190a81f0 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Tue, 19 Nov 2019 00:32:09 -0800 Subject: [PATCH 13/20] tests: makedirs permissions test simplify with tmpdir fixture --- tests/func/test_utils.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/tests/func/test_utils.py b/tests/func/test_utils.py index c764a80e4..594fdc332 100644 --- a/tests/func/test_utils.py +++ b/tests/func/test_utils.py @@ -76,16 +76,15 @@ class TestUtils(TestDvc): @pytest.mark.skipif(os.name == "nt", reason="Not supported for Windows.") -def test_makedirs_permissions(): +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) - try: - 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 - finally: - shutil.rmtree(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 From f575bc7a1dfb92f81d762aa7545597fba9ffca26 Mon Sep 17 00:00:00 2001 From: pawel Date: Mon, 11 Nov 2019 16:13:13 +0100 Subject: [PATCH 14/20] import: intercept and rephrase OutputNotFound message --- dvc/exceptions.py | 9 +++++++++ dvc/repo/imp.py | 9 ++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/dvc/exceptions.py b/dvc/exceptions.py index 291606614..3c85f3dae 100644 --- a/dvc/exceptions.py +++ b/dvc/exceptions.py @@ -338,3 +338,12 @@ class RemoteNotSpecifiedInExternalRepoError(DvcException): ), cause=cause, ) + + +class NoOutputInExternalRepoError(DvcException): + def __init__(self, repo_url, path): + super(NoOutputInExternalRepoError, self).__init__( + "Output '{}' not found in target repository: '{}'".format( + path, repo_url + ) + ) diff --git a/dvc/repo/imp.py b/dvc/repo/imp.py index 68ead389b..869039266 100644 --- a/dvc/repo/imp.py +++ b/dvc/repo/imp.py @@ -1,6 +1,13 @@ +from dvc.exceptions import NoOutputInExternalRepoError +from dvc.exceptions import OutputNotFoundError + + def imp(self, url, path, out=None, rev=None): erepo = {"url": url} if rev is not None: erepo["rev"] = rev - return self.imp_url(path, out=out, erepo=erepo, locked=True) + try: + return self.imp_url(path, out=out, erepo=erepo, locked=True) + except OutputNotFoundError: + raise NoOutputInExternalRepoError(url, path) From e5aaf987768caa8bedff226b6ba6fb6181cc3fad Mon Sep 17 00:00:00 2001 From: pawel Date: Wed, 13 Nov 2019 18:05:58 +0100 Subject: [PATCH 15/20] import/get: make extarnal repo handle OutputNotFound --- dvc/dependency/repo.py | 6 +++--- dvc/exceptions.py | 6 ++++-- dvc/external_repo.py | 6 ++++++ dvc/repo/__init__.py | 14 ++++++++++---- dvc/repo/fetch.py | 2 +- dvc/repo/get.py | 2 +- dvc/repo/imp.py | 9 +-------- 7 files changed, 26 insertions(+), 19 deletions(-) diff --git a/dvc/dependency/repo.py b/dvc/dependency/repo.py index 20439c024..68cd044a1 100644 --- a/dvc/dependency/repo.py +++ b/dvc/dependency/repo.py @@ -49,10 +49,10 @@ class DependencyREPO(DependencyLOCAL): def status(self): with self._make_repo() as repo: - current = repo.find_out_by_relpath(self.def_path).info + current = repo.find_out_by_path(self.def_path).info with self._make_repo(rev_lock=None) as repo: - updated = repo.find_out_by_relpath(self.def_path).info + updated = repo.find_out_by_path(self.def_path).info if current != updated: return {str(self): "update available"} @@ -71,7 +71,7 @@ class DependencyREPO(DependencyLOCAL): ) as repo: self.def_repo[self.PARAM_REV_LOCK] = repo.scm.get_rev() - out = repo.find_out_by_relpath(self.def_path) + out = repo.find_out_by_path(self.def_path) with repo.state: repo.cloud.pull(out.get_used_cache()) diff --git a/dvc/exceptions.py b/dvc/exceptions.py index 3c85f3dae..369b33ac7 100644 --- a/dvc/exceptions.py +++ b/dvc/exceptions.py @@ -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.repo = repo + self.failed_output = output super(OutputNotFoundError, self).__init__( "unable to find DVC-file with output '{path}'".format( - path=relpath(output) + path=relpath(self.failed_output) ) ) diff --git a/dvc/external_repo.py b/dvc/external_repo.py index 46657fc4d..d528af6a5 100644 --- a/dvc/external_repo.py +++ b/dvc/external_repo.py @@ -9,6 +9,8 @@ from funcy import retry from dvc.config import NoRemoteError from dvc.exceptions import RemoteNotSpecifiedInExternalRepoError +from dvc.exceptions import NoOutputInExternalRepoError +from dvc.exceptions import OutputNotFoundError from dvc.utils.fs import remove @@ -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(url, exc.failed_output) + raise repo.close() diff --git a/dvc/repo/__init__.py b/dvc/repo/__init__.py index e0003b808..86d6a343c 100644 --- a/dvc/repo/__init__.py +++ b/dvc/repo/__init__.py @@ -418,10 +418,13 @@ class Repo(object): return get_stages(self.graph) def find_outs_by_path(self, path, outs=None, recursive=False): + abs_path = ( + path if os.path.isabs(path) else os.path.join(self.root_dir, path) + ) + if not outs: outs = [out for stage in self.stages for out in stage.outs] - abs_path = os.path.abspath(path) is_dir = self.tree.isdir(abs_path) def func(out): @@ -435,12 +438,15 @@ class Repo(object): matched = list(filter(func, outs)) if not matched: - raise OutputNotFoundError(path) + if abs_path.startswith(self.root_dir): + failed_output = relpath(abs_path) + else: + failed_output = path + raise OutputNotFoundError(failed_output, self) return matched - def find_out_by_relpath(self, relpath): - path = os.path.join(self.root_dir, relpath) + def find_out_by_path(self, path): out, = self.find_outs_by_path(path) return out diff --git a/dvc/repo/fetch.py b/dvc/repo/fetch.py index 531fd4d53..0440dddae 100644 --- a/dvc/repo/fetch.py +++ b/dvc/repo/fetch.py @@ -81,7 +81,7 @@ def _fetch_external(self, repo_url, repo_rev, files): cache = NamedCache() for name in files: try: - out = repo.find_out_by_relpath(name) + out = repo.find_out_by_path(name) except OutputNotFoundError: failed += 1 logger.exception( diff --git a/dvc/repo/get.py b/dvc/repo/get.py index 21d01ed7e..64ca5eaf0 100644 --- a/dvc/repo/get.py +++ b/dvc/repo/get.py @@ -49,7 +49,7 @@ def get(url, path, out=None, rev=None): # the same cache file might be used a few times in a directory. repo.cache.local.cache_types = ["reflink", "hardlink", "copy"] - o = repo.find_out_by_relpath(path) + o = repo.find_out_by_path(path) with repo.state: repo.cloud.pull(o.get_used_cache()) o.path_info = PathInfo(os.path.abspath(out)) diff --git a/dvc/repo/imp.py b/dvc/repo/imp.py index 869039266..68ead389b 100644 --- a/dvc/repo/imp.py +++ b/dvc/repo/imp.py @@ -1,13 +1,6 @@ -from dvc.exceptions import NoOutputInExternalRepoError -from dvc.exceptions import OutputNotFoundError - - def imp(self, url, path, out=None, rev=None): erepo = {"url": url} if rev is not None: erepo["rev"] = rev - try: - return self.imp_url(path, out=out, erepo=erepo, locked=True) - except OutputNotFoundError: - raise NoOutputInExternalRepoError(url, path) + return self.imp_url(path, out=out, erepo=erepo, locked=True) From 5a92c46033fc62c3e90dc1244242894278892951 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Redzy=C5=84ski?= Date: Fri, 15 Nov 2019 17:21:54 +0100 Subject: [PATCH 16/20] import: just inform that output not found --- dvc/dependency/repo.py | 6 +++--- dvc/exceptions.py | 9 +++------ dvc/external_repo.py | 2 +- dvc/repo/__init__.py | 14 ++++---------- dvc/repo/fetch.py | 2 +- dvc/repo/get.py | 2 +- tests/func/test_import.py | 7 ++++++- 7 files changed, 19 insertions(+), 23 deletions(-) diff --git a/dvc/dependency/repo.py b/dvc/dependency/repo.py index 68cd044a1..20439c024 100644 --- a/dvc/dependency/repo.py +++ b/dvc/dependency/repo.py @@ -49,10 +49,10 @@ class DependencyREPO(DependencyLOCAL): def status(self): with self._make_repo() as repo: - current = repo.find_out_by_path(self.def_path).info + current = repo.find_out_by_relpath(self.def_path).info with self._make_repo(rev_lock=None) as repo: - updated = repo.find_out_by_path(self.def_path).info + updated = repo.find_out_by_relpath(self.def_path).info if current != updated: return {str(self): "update available"} @@ -71,7 +71,7 @@ class DependencyREPO(DependencyLOCAL): ) as repo: self.def_repo[self.PARAM_REV_LOCK] = repo.scm.get_rev() - out = repo.find_out_by_path(self.def_path) + out = repo.find_out_by_relpath(self.def_path) with repo.state: repo.cloud.pull(out.get_used_cache()) diff --git a/dvc/exceptions.py b/dvc/exceptions.py index 369b33ac7..ce30ffa88 100644 --- a/dvc/exceptions.py +++ b/dvc/exceptions.py @@ -61,10 +61,9 @@ class OutputNotFoundError(DvcException): def __init__(self, output, repo=None): self.repo = repo - self.failed_output = output super(OutputNotFoundError, self).__init__( "unable to find DVC-file with output '{path}'".format( - path=relpath(self.failed_output) + path=relpath(output) ) ) @@ -343,9 +342,7 @@ class RemoteNotSpecifiedInExternalRepoError(DvcException): class NoOutputInExternalRepoError(DvcException): - def __init__(self, repo_url, path): + def __init__(self): super(NoOutputInExternalRepoError, self).__init__( - "Output '{}' not found in target repository: '{}'".format( - path, repo_url - ) + "Output not found in target repository." ) diff --git a/dvc/external_repo.py b/dvc/external_repo.py index d528af6a5..e86c02926 100644 --- a/dvc/external_repo.py +++ b/dvc/external_repo.py @@ -29,7 +29,7 @@ def external_repo(url=None, rev=None, rev_lock=None, cache_dir=None): raise RemoteNotSpecifiedInExternalRepoError(url, cause=exc) except OutputNotFoundError as exc: if exc.repo is repo: - raise NoOutputInExternalRepoError(url, exc.failed_output) + raise NoOutputInExternalRepoError() raise repo.close() diff --git a/dvc/repo/__init__.py b/dvc/repo/__init__.py index 86d6a343c..9f6284ef4 100644 --- a/dvc/repo/__init__.py +++ b/dvc/repo/__init__.py @@ -418,13 +418,10 @@ class Repo(object): return get_stages(self.graph) def find_outs_by_path(self, path, outs=None, recursive=False): - abs_path = ( - path if os.path.isabs(path) else os.path.join(self.root_dir, path) - ) - if not outs: outs = [out for stage in self.stages for out in stage.outs] + abs_path = os.path.abspath(path) is_dir = self.tree.isdir(abs_path) def func(out): @@ -438,15 +435,12 @@ class Repo(object): matched = list(filter(func, outs)) if not matched: - if abs_path.startswith(self.root_dir): - failed_output = relpath(abs_path) - else: - failed_output = path - raise OutputNotFoundError(failed_output, self) + raise OutputNotFoundError(path, self) return matched - def find_out_by_path(self, path): + def find_out_by_relpath(self, relpath): + path = os.path.join(self.root_dir, relpath) out, = self.find_outs_by_path(path) return out diff --git a/dvc/repo/fetch.py b/dvc/repo/fetch.py index 0440dddae..531fd4d53 100644 --- a/dvc/repo/fetch.py +++ b/dvc/repo/fetch.py @@ -81,7 +81,7 @@ def _fetch_external(self, repo_url, repo_rev, files): cache = NamedCache() for name in files: try: - out = repo.find_out_by_path(name) + out = repo.find_out_by_relpath(name) except OutputNotFoundError: failed += 1 logger.exception( diff --git a/dvc/repo/get.py b/dvc/repo/get.py index 64ca5eaf0..21d01ed7e 100644 --- a/dvc/repo/get.py +++ b/dvc/repo/get.py @@ -49,7 +49,7 @@ def get(url, path, out=None, rev=None): # the same cache file might be used a few times in a directory. repo.cache.local.cache_types = ["reflink", "hardlink", "copy"] - o = repo.find_out_by_path(path) + o = repo.find_out_by_relpath(path) with repo.state: repo.cloud.pull(o.get_used_cache()) o.path_info = PathInfo(os.path.abspath(out)) diff --git a/tests/func/test_import.py b/tests/func/test_import.py index 06e8f8c83..067d5be8e 100644 --- a/tests/func/test_import.py +++ b/tests/func/test_import.py @@ -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") From d1094c41b183690e32e3c8b0454eba4f8f1a7567 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Redzy=C5=84ski?= Date: Tue, 19 Nov 2019 14:58:16 +0100 Subject: [PATCH 17/20] external repo: make NoOutputInExternalRepo path-aware --- dvc/exceptions.py | 9 ++++++--- dvc/external_repo.py | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/dvc/exceptions.py b/dvc/exceptions.py index ce30ffa88..92f46a882 100644 --- a/dvc/exceptions.py +++ b/dvc/exceptions.py @@ -60,10 +60,11 @@ class OutputNotFoundError(DvcException): """ 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) ) ) @@ -342,7 +343,9 @@ class RemoteNotSpecifiedInExternalRepoError(DvcException): class NoOutputInExternalRepoError(DvcException): - def __init__(self): + def __init__(self, path, external_repo_path, external_repo_url): super(NoOutputInExternalRepoError, self).__init__( - "Output not found in target repository." + "Output '{}' not found in target repository '{}'".format( + relpath(path, external_repo_path), external_repo_url + ) ) diff --git a/dvc/external_repo.py b/dvc/external_repo.py index e86c02926..0555f2d75 100644 --- a/dvc/external_repo.py +++ b/dvc/external_repo.py @@ -29,7 +29,7 @@ def external_repo(url=None, rev=None, rev_lock=None, cache_dir=None): raise RemoteNotSpecifiedInExternalRepoError(url, cause=exc) except OutputNotFoundError as exc: if exc.repo is repo: - raise NoOutputInExternalRepoError() + raise NoOutputInExternalRepoError(exc.output, repo.root_dir, url) raise repo.close() From 7fae34ee5d88361615370b46c9dc8540d31753fb Mon Sep 17 00:00:00 2001 From: Ruslan Kuprieiev Date: Tue, 19 Nov 2019 18:52:10 +0200 Subject: [PATCH 18/20] test: freeze pytest-mock version To address failing tests. --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index d8f08940a..c79c482d8 100644 --- a/setup.py +++ b/setup.py @@ -117,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", From 404620e267a43b9d13aaf15854b8e38f76b02895 Mon Sep 17 00:00:00 2001 From: Ruslan Kuprieiev Date: Tue, 19 Nov 2019 19:12:49 +0200 Subject: [PATCH 19/20] test: update: use dvc_repo fixture To fix test failure. --- tests/unit/command/test_update.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/command/test_update.py b/tests/unit/command/test_update.py index bd741c825..c44def6fa 100644 --- a/tests/unit/command/test_update.py +++ b/tests/unit/command/test_update.py @@ -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 From f563892760018a3e2ccb807558df99043d097252 Mon Sep 17 00:00:00 2001 From: Ruslan Kuprieiev Date: Wed, 20 Nov 2019 08:29:12 +0200 Subject: [PATCH 20/20] dvc: bump to 0.70.0 --- dvc/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dvc/version.py b/dvc/version.py index 6af6b2b5a..3814a9699 100644 --- a/dvc/version.py +++ b/dvc/version.py @@ -7,7 +7,7 @@ import os import subprocess -_BASE_VERSION = "0.69.0" +_BASE_VERSION = "0.70.0" def _generate_version(base_version):