From e917ce0ae8a2522e64b8fc130dcaa44a5fbafcf2 Mon Sep 17 00:00:00 2001 From: Gunnlaugur Thor Briem Date: Mon, 29 Jul 2019 13:26:49 +0000 Subject: [PATCH] dvc: hooks only act in branches where dvc active (#2338) * dvc: hooks only act in branches where dvc active In a branch where DVC hasn't been initialized (as detected by `git ls-files .dvc` not listing any files), don't invoke dvc in the git hooks. This avoids trouble when switching between branches with and without dvc initialized. Fixes #2208 * dvc: simplify hooks per PR comment --- dvc/scm/git/__init__.py | 8 +++----- tests/func/test_install.py | 11 +++++++++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/dvc/scm/git/__init__.py b/dvc/scm/git/__init__.py index c0592e896..883c75afd 100644 --- a/dvc/scm/git/__init__.py +++ b/dvc/scm/git/__init__.py @@ -216,19 +216,17 @@ class Git(Base): return [t.name for t in self.git.tags] def _install_hook(self, name, cmd): - command = "dvc {}".format(cmd) + command = '[ -z "$(git ls-files .dvc)" ] || exec dvc {}'.format(cmd) hook = os.path.join(self.root_dir, self.GIT_DIR, "hooks", name) if os.path.isfile(hook): with open(hook, "r+") as fobj: if command not in fobj.read(): - fobj.write("exec {command}\n".format(command=command)) + fobj.write("{command}\n".format(command=command)) else: with open(hook, "w+") as fobj: - fobj.write( - "#!/bin/sh\n" "exec {command}\n".format(command=command) - ) + fobj.write("#!/bin/sh\n" "{command}\n".format(command=command)) os.chmod(hook, 0o777) diff --git a/tests/func/test_install.py b/tests/func/test_install.py index 5e5efee29..1e3c7b8ba 100644 --- a/tests/func/test_install.py +++ b/tests/func/test_install.py @@ -36,7 +36,11 @@ class TestInstall(object): assert main(["install"]) == 0 - expected_script = "#!/bin/sh\n" "echo hello\n" "exec dvc checkout\n" + expected_script = ( + "#!/bin/sh\n" + "echo hello\n" + '[ -z "$(git ls-files .dvc)" ] || exec dvc checkout\n' + ) with open(self._hook("post-checkout"), "r") as fobj: assert fobj.read() == expected_script @@ -45,7 +49,10 @@ class TestInstall(object): assert main(["install"]) == 0 assert main(["install"]) == 0 - expected_script = "#!/bin/sh\n" "exec dvc checkout\n" + expected_script = ( + "#!/bin/sh\n" + '[ -z "$(git ls-files .dvc)" ] || exec dvc checkout\n' + ) with open(self._hook("post-checkout"), "r") as fobj: assert fobj.read() == expected_script