From fed9f088ca40edb73819944c9a91134a9f8a64fc Mon Sep 17 00:00:00 2001 From: eggqq007 <32856938+eggqq007@users.noreply.github.com> Date: Wed, 29 Sep 2021 10:59:33 +0800 Subject: [PATCH] command: Show dvc list output with pretty JSON format if output to tty (#6647) 1. update ls __init__.py to output pretty JSON format 2. introduce write_json function into ui __init__.py Co-authored-by: Zhenyu Gao --- dvc/command/ls/__init__.py | 4 +--- dvc/ui/__init__.py | 14 ++++++++++++++ requirements/default.txt | 2 +- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/dvc/command/ls/__init__.py b/dvc/command/ls/__init__.py index 1b2317c6f..fb9b6463e 100644 --- a/dvc/command/ls/__init__.py +++ b/dvc/command/ls/__init__.py @@ -35,9 +35,7 @@ class CmdList(CmdBaseNoRepo): dvc_only=self.args.dvc_only, ) if self.args.show_json: - import json - - ui.write(json.dumps(entries)) + ui.write_json(entries) elif entries: entries = _prettify(entries, with_color=True) ui.write("\n".join(entries)) diff --git a/dvc/ui/__init__.py b/dvc/ui/__init__.py index 9b515f252..dbfbbf0bf 100644 --- a/dvc/ui/__init__.py +++ b/dvc/ui/__init__.py @@ -82,6 +82,20 @@ class Console: styled=styled, ) + def write_json( + self, + data: Any, + indent: int = 2, + ) -> None: + if sys.stdout.isatty(): + from rich.json import JSON + + j = JSON.from_data(data, indent=indent) + return self.write(j, styled=True) + import json + + return self.write(json.dumps(data)) + def write( self, *objects: Any, diff --git a/requirements/default.txt b/requirements/default.txt index 609856256..40d160f42 100644 --- a/requirements/default.txt +++ b/requirements/default.txt @@ -34,7 +34,7 @@ tabulate>=0.8.7 pygtrie>=2.3.2 dpath>=2.0.2,<3 shtab>=1.3.4,<2 -rich>=10.0.0 +rich>=10.9.0 dictdiffer>=0.8.1 python-benedict>=0.21.1 pyparsing==2.4.7