Skip to content

Commit 567b995

Browse files
committed
fix multiline strings representation in cli yaml dumper
1 parent a6d2fec commit 567b995

File tree

4 files changed

+43
-4
lines changed

4 files changed

+43
-4
lines changed

nested_diff/cli.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# -*- coding: utf-8 -*-
22
#
3-
# Copyright 2019-2022 Michael Samoglyadov
3+
# Copyright 2019-2023 Michael Samoglyadov
44
#
55
# Licensed under the Apache License, Version 2.0 (the "License");
66
# you may not use this file except in compliance with the License.
@@ -472,12 +472,19 @@ def __init__(self, **kwargs):
472472

473473
import yaml
474474
try:
475-
from yaml import CSafeDumper as YamlDumper
475+
from yaml import CSafeDumper as ImportedYamlDumper
476476
except ImportError:
477-
from yaml import SafeDumper as YamlDumper
477+
from yaml import SafeDumper as ImportedYamlDumper
478+
479+
class _YamlDumper(ImportedYamlDumper):
480+
def represent_scalar(self, tag, value, style=None):
481+
if isinstance(value, str) and '\n' in value:
482+
return super().represent_scalar(tag, value, style='|')
483+
484+
return super().represent_scalar(tag, value, style=style)
478485

479486
self.yaml = yaml
480-
self.yaml_dumper = YamlDumper
487+
self.yaml_dumper = _YamlDumper
481488
self.opts = self.get_opts(kwargs)
482489

483490
def encode(self, data):
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"text_with_single_line": "one",
3+
"text_with_specific_symbols": "one:two\n\\nthree",
4+
"text_with_trailing_lines": "one\n\n\n",
5+
"text_with_two_lines": "one\ntwo"
6+
}

tests/cli/test_diff_tool.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,3 +556,18 @@ def test_values_yaml(capsys, expected, rpath):
556556
assert exit_code == 1
557557

558558
assert captured.out == expected
559+
560+
561+
def test_values_yaml_multiline_strings(capsys, expected, rpath):
562+
exit_code = nested_diff.diff_tool.App(args=(
563+
rpath('shared.multiline_strings.json'),
564+
rpath('shared.multiline_strings.json'),
565+
'-U', '1',
566+
'--values', 'yaml',
567+
)).run()
568+
569+
captured = capsys.readouterr()
570+
assert captured.err == ''
571+
assert exit_code == 0
572+
573+
assert captured.out == expected
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
text_with_single_line: one
2+
text_with_specific_symbols: |-
3+
one:two
4+
\nthree
5+
text_with_trailing_lines: |+
6+
one
7+
8+
9+
text_with_two_lines: |-
10+
one
11+
two

0 commit comments

Comments
 (0)