diff --git a/src/borg/helpers/parseformat.py b/src/borg/helpers/parseformat.py index 89e8cfbc5..459703a38 100644 --- a/src/borg/helpers/parseformat.py +++ b/src/borg/helpers/parseformat.py @@ -1039,9 +1039,25 @@ def basic_json_data(manifest, *, cache=None, extra=None): return data +def _json_indent_from_env(): + """Parse BORG_JSON_INDENT env var for json.dumps indent parameter.""" + value = os.environ.get("BORG_JSON_INDENT") + if value is None: + return 4 + if value.lower() == "none": + return None + if value == "": + return "" + try: + return int(value) + except ValueError: + return value + + def json_dump(obj): """Dump using BorgJSONEncoder.""" - return json.dumps(obj, sort_keys=True, indent=4, cls=BorgJsonEncoder) + indent = _json_indent_from_env() + return json.dumps(obj, sort_keys=True, indent=indent, cls=BorgJsonEncoder) def json_print(obj): diff --git a/src/borg/testsuite/helpers.py b/src/borg/testsuite/helpers.py index 7eba166b8..1449d0a68 100644 --- a/src/borg/testsuite/helpers.py +++ b/src/borg/testsuite/helpers.py @@ -1239,3 +1239,31 @@ def test_ec_invalid(): )) def test_max_ec(ec1, ec2, ec_max): assert max_ec(ec1, ec2) == ec_max + +@pytest.mark.parametrize( + 'env_value, expect_newlines', + [ + (None, True), + ('none', False), + ('0', True), + ('4', True), + ('', True), + ('\t', True), + ], +) +def test_json_dump_indent(monkeypatch, env_value, expect_newlines): + from ..helpers import json_dump + import json + + obj = {'key': 'value', 'number': 42} + if env_value is not None: + monkeypatch.setenv('BORG_JSON_INDENT', env_value) + else: + monkeypatch.delenv('BORG_JSON_INDENT', raising=False) + + result = json_dump(obj) + if expect_newlines: + assert '\n' in result + else: + assert '\n' not in result + assert json.loads(result) == obj