Skip to content

Commit a4ade13

Browse files
author
Mr. Outis
committed
diff: add JSON output
1 parent b251682 commit a4ade13

File tree

2 files changed

+34
-11
lines changed

2 files changed

+34
-11
lines changed

dvc/command/diff.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import argparse
2+
import json
23
import logging
34

45
from dvc.command.base import CmdBase, append_doc_link
@@ -11,9 +12,16 @@
1112
class CmdDiff(CmdBase):
1213
def run(self):
1314
try:
14-
self.repo.diff(
15+
diff = self.repo.diff(
1516
self.args.a_ref, self.args.b_ref, target=self.args.target
1617
)
18+
if not any(diff.values()):
19+
return 0
20+
21+
if self.args.json:
22+
print(json.dumps(diff))
23+
return 0
24+
1725
except DvcException:
1826
logger.exception("failed to get 'diff {}'")
1927
return 1
@@ -56,4 +64,10 @@ def add_parser(subparsers, parent_parser):
5664
"that are under DVC control in the current working space."
5765
),
5866
)
67+
diff_parser.add_argument(
68+
"--json",
69+
help=("Format the output into a JSON"),
70+
action="store_true",
71+
default=False,
72+
)
5973
diff_parser.set_defaults(func=CmdDiff)

tests/func/test_diff.py

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import hashlib
2+
import json
23
import os
34
import pytest
45

6+
from dvc.main import main
7+
58

69
def digest(text):
710
return hashlib.md5(bytes(text, "utf-8")).hexdigest()
@@ -126,7 +129,7 @@ def test_directories(tmp_dir, scm, dvc):
126129
assert dvc.diff(":/init", ":/directory") == {
127130
"added": [
128131
{
129-
"filename": os.path.dir("dir", ""),
132+
"filename": os.path.join("dir", ""),
130133
"checksum": "5fb6b29836c388e093ca0715c872fe2a.dir",
131134
},
132135
{"filename": os.path.join("dir", "1"), "checksum": digest("1")},
@@ -179,13 +182,19 @@ def test_cli(tmp_dir, scm, dvc):
179182
pytest.skip("TODO: define output structure")
180183

181184

182-
def test_json(tmp_dir, scm, dvc):
183-
# result = {
184-
# "added": {...},
185-
# "renamed": {...},
186-
# "modified": {...},
187-
# "deleted": {...},
188-
# }
185+
def test_json(tmp_dir, scm, dvc, capsys):
186+
assert 0 == main(["diff", "--json"])
187+
assert not capsys.readouterr().out
189188

190-
# main(["diff", "--json"])
191-
pytest.skip("TODO: define output structure")
189+
tmp_dir.dvc_gen("file", "text")
190+
assert 0 == main(["diff", "--json"])
191+
assert (
192+
json.dumps(
193+
{
194+
"added": [{"filename": "file", "checksum": digest("text")}],
195+
"deleted": [],
196+
"modified": [],
197+
}
198+
)
199+
in capsys.readouterr().out
200+
)

0 commit comments

Comments
 (0)