Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/borg/helpers/parseformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1418,9 +1418,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):
Expand Down
29 changes: 29 additions & 0 deletions src/borg/testsuite/helpers/parseformat_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import json
import os

import re
Expand Down Expand Up @@ -718,3 +719,31 @@ def test_valid_chunkerparams(chunker_params, expected_return):
def test_invalid_chunkerparams(invalid_chunker_params):
with pytest.raises(ArgumentTypeError):
ChunkerParams(invalid_chunker_params)


@pytest.mark.parametrize(
"env_value, expect_newlines",
[
(None, True), # default indent=4
("none", False), # compact single-line
("0", True), # newlines only, no spaces
("4", True), # explicit pretty-print
("", True), # empty string, newlines only
("\t", True), # tab indent string
],
)
def test_json_dump_indent(monkeypatch, env_value, expect_newlines):
from ...helpers.parseformat import json_dump

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
Loading