diff --git a/dvc/command/diff.py b/dvc/command/diff.py index 7ec4f24f3..7f03b1c5c 100644 --- a/dvc/command/diff.py +++ b/dvc/command/diff.py @@ -1,4 +1,5 @@ import argparse +import json import logging from dvc.command.base import CmdBase, append_doc_link @@ -11,9 +12,16 @@ logger = logging.getLogger(__name__) class CmdDiff(CmdBase): def run(self): try: - self.repo.diff( + diff = self.repo.diff( self.args.a_ref, self.args.b_ref, target=self.args.target ) + if not any(diff.values()): + return 0 + + if self.args.json: + print(json.dumps(diff)) + return 0 + except DvcException: logger.exception("failed to get 'diff {}'") return 1 @@ -56,4 +64,10 @@ def add_parser(subparsers, parent_parser): "that are under DVC control in the current working space." ), ) + diff_parser.add_argument( + "--json", + help=("Format the output into a JSON"), + action="store_true", + default=False, + ) diff_parser.set_defaults(func=CmdDiff) diff --git a/tests/func/test_diff.py b/tests/func/test_diff.py index ce92caa4b..192b56887 100644 --- a/tests/func/test_diff.py +++ b/tests/func/test_diff.py @@ -1,7 +1,10 @@ import hashlib +import json import os import pytest +from dvc.main import main + def digest(text): return hashlib.md5(bytes(text, "utf-8")).hexdigest() @@ -126,7 +129,7 @@ def test_directories(tmp_dir, scm, dvc): assert dvc.diff(":/init", ":/directory") == { "added": [ { - "filename": os.path.dir("dir", ""), + "filename": os.path.join("dir", ""), "checksum": "5fb6b29836c388e093ca0715c872fe2a.dir", }, {"filename": os.path.join("dir", "1"), "checksum": digest("1")}, @@ -179,13 +182,19 @@ def test_cli(tmp_dir, scm, dvc): pytest.skip("TODO: define output structure") -def test_json(tmp_dir, scm, dvc): - # result = { - # "added": {...}, - # "renamed": {...}, - # "modified": {...}, - # "deleted": {...}, - # } +def test_json(tmp_dir, scm, dvc, capsys): + assert 0 == main(["diff", "--json"]) + assert not capsys.readouterr().out - # main(["diff", "--json"]) - pytest.skip("TODO: define output structure") + tmp_dir.dvc_gen("file", "text") + assert 0 == main(["diff", "--json"]) + assert ( + json.dumps( + { + "added": [{"filename": "file", "checksum": digest("text")}], + "deleted": [], + "modified": [], + } + ) + in capsys.readouterr().out + )