{ "instance_id": "iterative__dvc-2164", "patch": "diff --git a/dvc/repo/destroy.py b/dvc/repo/destroy.py\n--- a/dvc/repo/destroy.py\n+++ b/dvc/repo/destroy.py\n@@ -3,6 +3,6 @@\n \n def destroy(self):\n for stage in self.stages():\n- stage.remove()\n+ stage.remove(remove_outs=False)\n \n shutil.rmtree(self.dvc_dir)\ndiff --git a/dvc/stage.py b/dvc/stage.py\n--- a/dvc/stage.py\n+++ b/dvc/stage.py\n@@ -296,8 +296,11 @@ def unprotect_outs(self):\n for out in self.outs:\n out.unprotect()\n \n- def remove(self, force=False):\n- self.remove_outs(ignore_remove=True, force=force)\n+ def remove(self, force=False, remove_outs=True):\n+ if remove_outs:\n+ self.remove_outs(ignore_remove=True, force=force)\n+ else:\n+ self.unprotect_outs()\n os.unlink(self.path)\n \n def reproduce(\n", "repo": "iterative/dvc", "base_commit": "074ea612f612608c5fc66d9c558a2bce2cbee3f9", "hints_text": "@efiop , `destroy` should work as `rm -rf .dvc`?\r\n\r\nI was thinking about adding the `--all` option that will work as `rm -rf .dvc *.dvc Dvcfile`.\r\n\r\nIs that the expected behavior?\nCurrently `destroy` removes both .dvc/ directory and *.dvc files with their outputs. Starting from 1.0, it should leave outputs intact(in symlink case, it should remove symlinks and replace them by copies), so that user at least has his data back.\nWe should use `unprotect` as described in https://github.com/iterative/dvc/issues/1802", "test_patch": "diff --git a/tests/func/test_destroy.py b/tests/func/test_destroy.py\n--- a/tests/func/test_destroy.py\n+++ b/tests/func/test_destroy.py\n@@ -1,21 +1,28 @@\n import os\n \n-from dvc.main import main\n+from dvc.system import System\n \n-from tests.func.test_repro import TestRepro\n \n+def test_destroy(repo_dir, dvc_repo):\n+ # NOTE: using symlink to ensure that data was unprotected after `destroy`\n+ dvc_repo.config.set(\"cache\", \"type\", \"symlink\")\n \n-class TestDestroyNoConfirmation(TestRepro):\n- def test(self):\n- ret = main([\"destroy\"])\n- self.assertNotEqual(ret, 0)\n+ foo_stage, = dvc_repo.add(repo_dir.FOO)\n+ data_dir_stage, = dvc_repo.add(repo_dir.DATA_DIR)\n \n+ dvc_repo.destroy()\n \n-class TestDestroyForce(TestRepro):\n- def test(self):\n- ret = main([\"destroy\", \"-f\"])\n- self.assertEqual(ret, 0)\n+ assert not os.path.exists(dvc_repo.dvc_dir)\n+ assert not os.path.exists(foo_stage.path)\n+ assert not os.path.exists(data_dir_stage.path)\n \n- self.assertFalse(os.path.exists(self.dvc.dvc_dir))\n- self.assertFalse(os.path.exists(self.file1_stage))\n- self.assertFalse(os.path.exists(self.file1))\n+ assert os.path.isfile(repo_dir.FOO)\n+ assert os.path.isdir(repo_dir.DATA_DIR)\n+ assert os.path.isfile(repo_dir.DATA)\n+ assert os.path.isdir(repo_dir.DATA_SUB_DIR)\n+ assert os.path.isfile(repo_dir.DATA_SUB)\n+\n+ assert not System.is_symlink(repo_dir.FOO)\n+ assert not System.is_symlink(repo_dir.DATA_DIR)\n+ assert not System.is_symlink(repo_dir.DATA)\n+ assert not System.is_symlink(repo_dir.DATA_SUB)\n", "problem_statement": "destroy: don't remove data files by default in the workspace\nWill have to add some option to destroy data files as well.\n", "version": "0.0", "environment_setup_commit": "074ea612f612608c5fc66d9c558a2bce2cbee3f9", "FAIL_TO_PASS": [ "tests/func/test_destroy.py::test_destroy" ], "PASS_TO_PASS": [], "meta": { "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }, "created_at": "2019-06-21 10:14:17+00:00", "license": "apache-2.0", "__index_level_0__": 2936, "source_code_files": { "dvc/repo/destroy.py": "import shutil\n\n\ndef destroy(self):\n for stage in self.stages():\n stage.remove()\n\n shutil.rmtree(self.dvc_dir)\n", "dvc/stage.py": "from __future__ import unicode_literals\n\nfrom dvc.utils.compat import str\n\nimport copy\nimport re\nimport os\nimport subprocess\nimport logging\nimport signal\n\nfrom dvc.utils import relpath\nfrom dvc.utils.compat import pathlib\nfrom dvc.utils.fs import contains_symlink_up_to\nfrom schema import Schema, SchemaError, Optional, Or, And\n\nimport dvc.prompt as prompt\nimport dvc.dependency as dependency\nimport dvc.output as output\nfrom dvc.exceptions import DvcException\nfrom dvc.utils import dict_md5, fix_env\nfrom dvc.utils.collections import apply_diff\nfrom dvc.utils.stage import load_stage_fd, dump_stage_file\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass StageCmdFailedError(DvcException):\n def __init__(self, stage):\n msg = \"stage '{}' cmd {} failed\".format(stage.relpath, stage.cmd)\n super(StageCmdFailedError, self).__init__(msg)\n\n\nclass StageFileFormatError(DvcException):\n def __init__(self, fname, e):\n msg = \"stage file '{}' format error: {}\".format(fname, str(e))\n super(StageFileFormatError, self).__init__(msg)\n\n\nclass StageFileDoesNotExistError(DvcException):\n def __init__(self, fname):\n msg = \"'{}' does not exist.\".format(fname)\n\n sname = fname + Stage.STAGE_FILE_SUFFIX\n if Stage.is_stage_file(sname):\n msg += \" Do you mean '{}'?\".format(sname)\n\n super(StageFileDoesNotExistError, self).__init__(msg)\n\n\nclass StageFileAlreadyExistsError(DvcException):\n def __init__(self, relpath):\n msg = \"stage '{}' already exists\".format(relpath)\n super(StageFileAlreadyExistsError, self).__init__(msg)\n\n\nclass StageFileIsNotDvcFileError(DvcException):\n def __init__(self, fname):\n msg = \"'{}' is not a DVC-file\".format(fname)\n\n sname = fname + Stage.STAGE_FILE_SUFFIX\n if Stage.is_stage_file(sname):\n msg += \" Do you mean '{}'?\".format(sname)\n\n super(StageFileIsNotDvcFileError, self).__init__(msg)\n\n\nclass StageFileBadNameError(DvcException):\n def __init__(self, msg):\n super(StageFileBadNameError, self).__init__(msg)\n\n\nclass StagePathOutsideError(DvcException):\n def __init__(self, path):\n msg = \"stage working or file path '{}' is outside of dvc repo\"\n super(StagePathOutsideError, self).__init__(msg.format(path))\n\n\nclass StagePathNotFoundError(DvcException):\n def __init__(self, path):\n msg = \"stage working or file path '{}' does not exist\"\n super(StagePathNotFoundError, self).__init__(msg.format(path))\n\n\nclass StagePathNotDirectoryError(DvcException):\n def __init__(self, path):\n msg = \"stage working or file path '{}' is not directory\"\n super(StagePathNotDirectoryError, self).__init__(msg.format(path))\n\n\nclass StageCommitError(DvcException):\n pass\n\n\nclass MissingDep(DvcException):\n def __init__(self, deps):\n assert len(deps) > 0\n\n if len(deps) > 1:\n dep = \"dependencies\"\n else:\n dep = \"dependency\"\n\n msg = \"missing {}: {}\".format(dep, \", \".join(map(str, deps)))\n super(MissingDep, self).__init__(msg)\n\n\nclass MissingDataSource(DvcException):\n def __init__(self, missing_files):\n assert len(missing_files) > 0\n\n source = \"source\"\n if len(missing_files) > 1:\n source += \"s\"\n\n msg = \"missing data {}: {}\".format(source, \", \".join(missing_files))\n super(MissingDataSource, self).__init__(msg)\n\n\nclass Stage(object):\n STAGE_FILE = \"Dvcfile\"\n STAGE_FILE_SUFFIX = \".dvc\"\n\n PARAM_MD5 = \"md5\"\n PARAM_CMD = \"cmd\"\n PARAM_WDIR = \"wdir\"\n PARAM_DEPS = \"deps\"\n PARAM_OUTS = \"outs\"\n PARAM_LOCKED = \"locked\"\n PARAM_META = \"meta\"\n\n SCHEMA = {\n Optional(PARAM_MD5): Or(str, None),\n Optional(PARAM_CMD): Or(str, None),\n Optional(PARAM_WDIR): Or(str, None),\n Optional(PARAM_DEPS): Or(And(list, Schema([dependency.SCHEMA])), None),\n Optional(PARAM_OUTS): Or(And(list, Schema([output.SCHEMA])), None),\n Optional(PARAM_LOCKED): bool,\n Optional(PARAM_META): object,\n }\n\n TAG_REGEX = r\"^(?P.*)@(?P[^\\\\/@:]*)$\"\n\n def __init__(\n self,\n repo,\n path=None,\n cmd=None,\n wdir=os.curdir,\n deps=None,\n outs=None,\n md5=None,\n locked=False,\n tag=None,\n state=None,\n ):\n if deps is None:\n deps = []\n if outs is None:\n outs = []\n\n self.repo = repo\n self.path = path\n self.cmd = cmd\n self.wdir = wdir\n self.outs = outs\n self.deps = deps\n self.md5 = md5\n self.locked = locked\n self.tag = tag\n self._state = state or {}\n\n def __repr__(self):\n return \"Stage: '{path}'\".format(\n path=self.relpath if self.path else \"No path\"\n )\n\n @property\n def relpath(self):\n return relpath(self.path)\n\n @property\n def is_data_source(self):\n \"\"\"Whether the stage file was created with `dvc add` or `dvc import`\"\"\"\n return self.cmd is None\n\n @staticmethod\n def is_valid_filename(path):\n return (\n # path.endswith doesn't work for encoded unicode filenames on\n # Python 2 and since Stage.STAGE_FILE_SUFFIX is ascii then it is\n # not needed to decode the path from py2's str\n path[-len(Stage.STAGE_FILE_SUFFIX) :] == Stage.STAGE_FILE_SUFFIX\n or os.path.basename(path) == Stage.STAGE_FILE\n )\n\n @staticmethod\n def is_stage_file(path):\n return os.path.isfile(path) and Stage.is_valid_filename(path)\n\n def changed_md5(self):\n return self.md5 != self._compute_md5()\n\n @property\n def is_callback(self):\n \"\"\"\n A callback stage is always considered as changed,\n so it runs on every `dvc repro` call.\n \"\"\"\n return not self.is_data_source and len(self.deps) == 0\n\n @property\n def is_import(self):\n \"\"\"Whether the stage file was created with `dvc import`.\"\"\"\n return not self.cmd and len(self.deps) == 1 and len(self.outs) == 1\n\n @property\n def is_repo_import(self):\n if not self.is_import:\n return False\n\n return isinstance(self.deps[0], dependency.DependencyREPO)\n\n def _changed_deps(self):\n if self.locked:\n return False\n\n if self.is_callback:\n logger.warning(\n \"DVC-file '{fname}' is a 'callback' stage \"\n \"(has a command and no dependencies) and thus always \"\n \"considered as changed.\".format(fname=self.relpath)\n )\n return True\n\n for dep in self.deps:\n status = dep.status()\n if status:\n logger.warning(\n \"Dependency '{dep}' of '{stage}' changed because it is \"\n \"'{status}'.\".format(\n dep=dep, stage=self.relpath, status=status[str(dep)]\n )\n )\n return True\n\n return False\n\n def _changed_outs(self):\n for out in self.outs:\n status = out.status()\n if status:\n logger.warning(\n \"Output '{out}' of '{stage}' changed because it is \"\n \"'{status}'\".format(\n out=out, stage=self.relpath, status=status[str(out)]\n )\n )\n return True\n\n return False\n\n def _changed_md5(self):\n if self.changed_md5():\n logger.warning(\"DVC-file '{}' changed.\".format(self.relpath))\n return True\n return False\n\n def changed(self):\n ret = any(\n [self._changed_deps(), self._changed_outs(), self._changed_md5()]\n )\n\n if ret:\n logger.warning(\"Stage '{}' changed.\".format(self.relpath))\n else:\n logger.info(\"Stage '{}' didn't change.\".format(self.relpath))\n\n return ret\n\n def remove_outs(self, ignore_remove=False, force=False):\n \"\"\"Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`.\"\"\"\n for out in self.outs:\n if out.persist and not force:\n out.unprotect()\n else:\n logger.debug(\n \"Removing output '{out}' of '{stage}'.\".format(\n out=out, stage=self.relpath\n )\n )\n out.remove(ignore_remove=ignore_remove)\n\n def unprotect_outs(self):\n for out in self.outs:\n out.unprotect()\n\n def remove(self, force=False):\n self.remove_outs(ignore_remove=True, force=force)\n os.unlink(self.path)\n\n def reproduce(\n self, force=False, dry=False, interactive=False, no_commit=False\n ):\n if not self.changed() and not force:\n return None\n\n msg = (\n \"Going to reproduce '{stage}'. \"\n \"Are you sure you want to continue?\".format(stage=self.relpath)\n )\n\n if interactive and not prompt.confirm(msg):\n raise DvcException(\"reproduction aborted by the user\")\n\n logger.info(\"Reproducing '{stage}'\".format(stage=self.relpath))\n\n self.run(dry=dry, no_commit=no_commit, force=force)\n\n logger.debug(\"'{stage}' was reproduced\".format(stage=self.relpath))\n\n return self\n\n @staticmethod\n def validate(d, fname=None):\n from dvc.utils import convert_to_unicode\n\n try:\n Schema(Stage.SCHEMA).validate(convert_to_unicode(d))\n except SchemaError as exc:\n raise StageFileFormatError(fname, exc)\n\n @classmethod\n def _stage_fname(cls, outs, add):\n if not outs:\n return cls.STAGE_FILE\n\n out = outs[0]\n fname = out.path_info.name + cls.STAGE_FILE_SUFFIX\n\n if (\n add\n and out.is_in_repo\n and not contains_symlink_up_to(out.fspath, out.repo.root_dir)\n ):\n fname = out.path_info.with_name(fname).fspath\n\n return fname\n\n @staticmethod\n def _check_stage_path(repo, path):\n assert repo is not None\n\n real_path = os.path.realpath(path)\n if not os.path.exists(real_path):\n raise StagePathNotFoundError(path)\n\n if not os.path.isdir(real_path):\n raise StagePathNotDirectoryError(path)\n\n proj_dir = os.path.realpath(repo.root_dir) + os.path.sep\n if not (real_path + os.path.sep).startswith(proj_dir):\n raise StagePathOutsideError(path)\n\n @property\n def is_cached(self):\n \"\"\"\n Checks if this stage has been already ran and stored\n \"\"\"\n from dvc.remote.local import RemoteLOCAL\n from dvc.remote.s3 import RemoteS3\n\n old = Stage.load(self.repo, self.path)\n if old._changed_outs():\n return False\n\n # NOTE: need to save checksums for deps in order to compare them\n # with what is written in the old stage.\n for dep in self.deps:\n dep.save()\n\n old_d = old.dumpd()\n new_d = self.dumpd()\n\n # NOTE: need to remove checksums from old dict in order to compare\n # it to the new one, since the new one doesn't have checksums yet.\n old_d.pop(self.PARAM_MD5, None)\n new_d.pop(self.PARAM_MD5, None)\n outs = old_d.get(self.PARAM_OUTS, [])\n for out in outs:\n out.pop(RemoteLOCAL.PARAM_CHECKSUM, None)\n out.pop(RemoteS3.PARAM_CHECKSUM, None)\n\n if old_d != new_d:\n return False\n\n # NOTE: committing to prevent potential data duplication. For example\n #\n # $ dvc config cache.type hardlink\n # $ echo foo > foo\n # $ dvc add foo\n # $ rm -f foo\n # $ echo foo > foo\n # $ dvc add foo # should replace foo with a link to cache\n #\n old.commit()\n\n return True\n\n @staticmethod\n def create(\n repo=None,\n cmd=None,\n deps=None,\n outs=None,\n outs_no_cache=None,\n metrics=None,\n metrics_no_cache=None,\n fname=None,\n cwd=None,\n wdir=None,\n locked=False,\n add=False,\n overwrite=True,\n ignore_build_cache=False,\n remove_outs=False,\n validate_state=True,\n outs_persist=None,\n outs_persist_no_cache=None,\n erepo=None,\n ):\n if outs is None:\n outs = []\n if deps is None:\n deps = []\n if outs_no_cache is None:\n outs_no_cache = []\n if metrics is None:\n metrics = []\n if metrics_no_cache is None:\n metrics_no_cache = []\n if outs_persist is None:\n outs_persist = []\n if outs_persist_no_cache is None:\n outs_persist_no_cache = []\n\n # Backward compatibility for `cwd` option\n if wdir is None and cwd is not None:\n if fname is not None and os.path.basename(fname) != fname:\n raise StageFileBadNameError(\n \"stage file name '{fname}' may not contain subdirectories\"\n \" if '-c|--cwd' (deprecated) is specified. Use '-w|--wdir'\"\n \" along with '-f' to specify stage file path and working\"\n \" directory.\".format(fname=fname)\n )\n wdir = cwd\n else:\n wdir = os.curdir if wdir is None else wdir\n\n stage = Stage(repo=repo, wdir=wdir, cmd=cmd, locked=locked)\n\n Stage._fill_stage_outputs(\n stage,\n outs,\n outs_no_cache,\n metrics,\n metrics_no_cache,\n outs_persist,\n outs_persist_no_cache,\n )\n stage.deps = dependency.loads_from(stage, deps, erepo=erepo)\n\n stage._check_circular_dependency()\n stage._check_duplicated_arguments()\n\n if not fname:\n fname = Stage._stage_fname(stage.outs, add=add)\n wdir = os.path.abspath(wdir)\n\n if cwd is not None:\n path = os.path.join(wdir, fname)\n else:\n path = os.path.abspath(fname)\n\n Stage._check_stage_path(repo, wdir)\n Stage._check_stage_path(repo, os.path.dirname(path))\n\n stage.wdir = wdir\n stage.path = path\n\n # NOTE: remove outs before we check build cache\n if remove_outs:\n logger.warning(\n \"--remove-outs is deprecated.\"\n \" It is now the default behavior,\"\n \" so there's no need to use this option anymore.\"\n )\n stage.remove_outs(ignore_remove=False)\n logger.warning(\"Build cache is ignored when using --remove-outs.\")\n ignore_build_cache = True\n else:\n stage.unprotect_outs()\n\n if os.path.exists(path) and any(out.persist for out in stage.outs):\n logger.warning(\"Build cache is ignored when persisting outputs.\")\n ignore_build_cache = True\n\n if validate_state:\n if os.path.exists(path):\n if not ignore_build_cache and stage.is_cached:\n logger.info(\"Stage is cached, skipping.\")\n return None\n\n msg = (\n \"'{}' already exists. Do you wish to run the command and \"\n \"overwrite it?\".format(stage.relpath)\n )\n\n if not overwrite and not prompt.confirm(msg):\n raise StageFileAlreadyExistsError(stage.relpath)\n\n os.unlink(path)\n\n return stage\n\n @staticmethod\n def _fill_stage_outputs(\n stage,\n outs,\n outs_no_cache,\n metrics,\n metrics_no_cache,\n outs_persist,\n outs_persist_no_cache,\n ):\n stage.outs = output.loads_from(stage, outs, use_cache=True)\n stage.outs += output.loads_from(\n stage, metrics, use_cache=True, metric=True\n )\n stage.outs += output.loads_from(\n stage, outs_persist, use_cache=True, persist=True\n )\n stage.outs += output.loads_from(stage, outs_no_cache, use_cache=False)\n stage.outs += output.loads_from(\n stage, metrics_no_cache, use_cache=False, metric=True\n )\n stage.outs += output.loads_from(\n stage, outs_persist_no_cache, use_cache=False, persist=True\n )\n\n @staticmethod\n def _check_dvc_filename(fname):\n if not Stage.is_valid_filename(fname):\n raise StageFileBadNameError(\n \"bad stage filename '{}'. Stage files should be named\"\n \" 'Dvcfile' or have a '.dvc' suffix (e.g. '{}.dvc').\".format(\n relpath(fname), os.path.basename(fname)\n )\n )\n\n @staticmethod\n def _check_file_exists(repo, fname):\n if not repo.tree.exists(fname):\n raise StageFileDoesNotExistError(fname)\n\n @staticmethod\n def _check_isfile(repo, fname):\n if not repo.tree.isfile(fname):\n raise StageFileIsNotDvcFileError(fname)\n\n @classmethod\n def _get_path_tag(cls, s):\n regex = re.compile(cls.TAG_REGEX)\n match = regex.match(s)\n if not match:\n return s, None\n return match.group(\"path\"), match.group(\"tag\")\n\n @staticmethod\n def load(repo, fname):\n fname, tag = Stage._get_path_tag(fname)\n\n # it raises the proper exceptions by priority:\n # 1. when the file doesn't exists\n # 2. filename is not a DVC-file\n # 3. path doesn't represent a regular file\n Stage._check_file_exists(repo, fname)\n Stage._check_dvc_filename(fname)\n Stage._check_isfile(repo, fname)\n\n with repo.tree.open(fname) as fd:\n d = load_stage_fd(fd, fname)\n # Making a deepcopy since the original structure\n # looses keys in deps and outs load\n state = copy.deepcopy(d)\n\n Stage.validate(d, fname=relpath(fname))\n path = os.path.abspath(fname)\n\n stage = Stage(\n repo=repo,\n path=path,\n wdir=os.path.abspath(\n os.path.join(\n os.path.dirname(path), d.get(Stage.PARAM_WDIR, \".\")\n )\n ),\n cmd=d.get(Stage.PARAM_CMD),\n md5=d.get(Stage.PARAM_MD5),\n locked=d.get(Stage.PARAM_LOCKED, False),\n tag=tag,\n state=state,\n )\n\n stage.deps = dependency.loadd_from(stage, d.get(Stage.PARAM_DEPS, []))\n stage.outs = output.loadd_from(stage, d.get(Stage.PARAM_OUTS, []))\n\n return stage\n\n def dumpd(self):\n rel_wdir = relpath(self.wdir, os.path.dirname(self.path))\n return {\n key: value\n for key, value in {\n Stage.PARAM_MD5: self.md5,\n Stage.PARAM_CMD: self.cmd,\n Stage.PARAM_WDIR: pathlib.PurePath(rel_wdir).as_posix(),\n Stage.PARAM_LOCKED: self.locked,\n Stage.PARAM_DEPS: [d.dumpd() for d in self.deps],\n Stage.PARAM_OUTS: [o.dumpd() for o in self.outs],\n Stage.PARAM_META: self._state.get(\"meta\"),\n }.items()\n if value\n }\n\n def dump(self):\n fname = self.path\n\n self._check_dvc_filename(fname)\n\n logger.info(\n \"Saving information to '{file}'.\".format(file=relpath(fname))\n )\n d = self.dumpd()\n apply_diff(d, self._state)\n dump_stage_file(fname, self._state)\n\n self.repo.scm.track_file(relpath(fname))\n\n def _compute_md5(self):\n from dvc.output.base import OutputBase\n\n d = self.dumpd()\n\n # NOTE: removing md5 manually in order to not affect md5s in deps/outs\n if self.PARAM_MD5 in d.keys():\n del d[self.PARAM_MD5]\n\n # Ignore the wdir default value. In this case stage file w/o\n # wdir has the same md5 as a file with the default value specified.\n # It's important for backward compatibility with pipelines that\n # didn't have WDIR in their stage files.\n if d.get(self.PARAM_WDIR) == \".\":\n del d[self.PARAM_WDIR]\n\n # NOTE: excluding parameters that don't affect the state of the\n # pipeline. Not excluding `OutputLOCAL.PARAM_CACHE`, because if\n # it has changed, we might not have that output in our cache.\n m = dict_md5(\n d,\n exclude=[\n self.PARAM_LOCKED,\n OutputBase.PARAM_METRIC,\n OutputBase.PARAM_TAGS,\n OutputBase.PARAM_PERSIST,\n ],\n )\n logger.debug(\"Computed stage '{}' md5: '{}'\".format(self.relpath, m))\n return m\n\n def save(self):\n for dep in self.deps:\n dep.save()\n\n for out in self.outs:\n out.save()\n\n self.md5 = self._compute_md5()\n\n @staticmethod\n def _changed_entries(entries):\n return [\n str(entry)\n for entry in entries\n if entry.checksum and entry.changed_checksum()\n ]\n\n def check_can_commit(self, force):\n changed_deps = self._changed_entries(self.deps)\n changed_outs = self._changed_entries(self.outs)\n\n if changed_deps or changed_outs or self.changed_md5():\n msg = (\n \"dependencies {}\".format(changed_deps) if changed_deps else \"\"\n )\n msg += \" and \" if (changed_deps and changed_outs) else \"\"\n msg += \"outputs {}\".format(changed_outs) if changed_outs else \"\"\n msg += \"md5\" if not (changed_deps or changed_outs) else \"\"\n msg += \" of '{}' changed. Are you sure you commit it?\".format(\n self.relpath\n )\n if not force and not prompt.confirm(msg):\n raise StageCommitError(\n \"unable to commit changed '{}'. Use `-f|--force` to \"\n \"force.`\".format(self.relpath)\n )\n self.save()\n\n def commit(self):\n for out in self.outs:\n out.commit()\n\n def _check_missing_deps(self):\n missing = [dep for dep in self.deps if not dep.exists]\n\n if any(missing):\n raise MissingDep(missing)\n\n @staticmethod\n def _warn_if_fish(executable): # pragma: no cover\n if (\n executable is None\n or os.path.basename(os.path.realpath(executable)) != \"fish\"\n ):\n return\n\n logger.warning(\n \"DVC detected that you are using fish as your default \"\n \"shell. Be aware that it might cause problems by overwriting \"\n \"your current environment variables with values defined \"\n \"in '.fishrc', which might affect your command. See \"\n \"https://github.com/iterative/dvc/issues/1307. \"\n )\n\n def _check_circular_dependency(self):\n from dvc.exceptions import CircularDependencyError\n\n circular_dependencies = set(d.path_info for d in self.deps) & set(\n o.path_info for o in self.outs\n )\n\n if circular_dependencies:\n raise CircularDependencyError(str(circular_dependencies.pop()))\n\n def _check_duplicated_arguments(self):\n from dvc.exceptions import ArgumentDuplicationError\n from collections import Counter\n\n path_counts = Counter(edge.path_info for edge in self.deps + self.outs)\n\n for path, occurrence in path_counts.items():\n if occurrence > 1:\n raise ArgumentDuplicationError(str(path))\n\n def _run(self):\n self._check_missing_deps()\n executable = os.getenv(\"SHELL\") if os.name != \"nt\" else None\n self._warn_if_fish(executable)\n\n old_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)\n p = None\n\n try:\n p = subprocess.Popen(\n self.cmd,\n cwd=self.wdir,\n shell=True,\n env=fix_env(os.environ),\n executable=executable,\n )\n p.communicate()\n finally:\n signal.signal(signal.SIGINT, old_handler)\n\n if (p is None) or (p.returncode != 0):\n raise StageCmdFailedError(self)\n\n def run(self, dry=False, resume=False, no_commit=False, force=False):\n if (self.cmd or self.is_import) and not self.locked and not dry:\n self.remove_outs(ignore_remove=False, force=False)\n\n if self.locked:\n logger.info(\n \"Verifying outputs in locked stage '{stage}'\".format(\n stage=self.relpath\n )\n )\n if not dry:\n self.check_missing_outputs()\n\n elif self.is_import:\n logger.info(\n \"Importing '{dep}' -> '{out}'\".format(\n dep=self.deps[0], out=self.outs[0]\n )\n )\n if not dry:\n if self._already_cached() and not force:\n self.outs[0].checkout()\n else:\n self.deps[0].download(self.outs[0], resume=resume)\n\n elif self.is_data_source:\n msg = \"Verifying data sources in '{}'\".format(self.relpath)\n logger.info(msg)\n if not dry:\n self.check_missing_outputs()\n\n else:\n logger.info(\"Running command:\\n\\t{}\".format(self.cmd))\n if not dry:\n if (\n not force\n and not self.is_callback\n and self._already_cached()\n ):\n self.checkout()\n else:\n self._run()\n\n if not dry:\n self.save()\n if not no_commit:\n self.commit()\n\n def check_missing_outputs(self):\n paths = [str(out) for out in self.outs if not out.exists]\n if paths:\n raise MissingDataSource(paths)\n\n def checkout(self, force=False, progress_callback=None):\n for out in self.outs:\n out.checkout(\n force=force, tag=self.tag, progress_callback=progress_callback\n )\n\n @staticmethod\n def _status(entries):\n ret = {}\n\n for entry in entries:\n ret.update(entry.status())\n\n return ret\n\n def status(self):\n ret = []\n\n if not self.locked:\n deps_status = self._status(self.deps)\n if deps_status:\n ret.append({\"changed deps\": deps_status})\n\n outs_status = self._status(self.outs)\n if outs_status:\n ret.append({\"changed outs\": outs_status})\n\n if self.changed_md5():\n ret.append(\"changed checksum\")\n\n if self.is_callback:\n ret.append(\"always changed\")\n\n if ret:\n return {self.relpath: ret}\n\n return {}\n\n def _already_cached(self):\n return (\n not self.changed_md5()\n and all(not dep.changed() for dep in self.deps)\n and all(\n not out.changed_cache() if out.use_cache else not out.changed()\n for out in self.outs\n )\n )\n\n def get_all_files_number(self):\n return sum(out.get_files_number() for out in self.outs)\n" }, "source_test_files": { "tests/func/test_destroy.py": "import os\n\nfrom dvc.main import main\n\nfrom tests.func.test_repro import TestRepro\n\n\nclass TestDestroyNoConfirmation(TestRepro):\n def test(self):\n ret = main([\"destroy\"])\n self.assertNotEqual(ret, 0)\n\n\nclass TestDestroyForce(TestRepro):\n def test(self):\n ret = main([\"destroy\", \"-f\"])\n self.assertEqual(ret, 0)\n\n self.assertFalse(os.path.exists(self.dvc.dvc_dir))\n self.assertFalse(os.path.exists(self.file1_stage))\n self.assertFalse(os.path.exists(self.file1))\n" } }