diff --git a/changelogs/fragments/warnings-remove-extra-newline-better.yaml b/changelogs/fragments/warnings-remove-extra-newline-better.yaml new file mode 100644 index 00000000000000..20ddb5b3de2ab2 --- /dev/null +++ b/changelogs/fragments/warnings-remove-extra-newline-better.yaml @@ -0,0 +1,2 @@ +bugfixes: + - display - Improve method of removing extra new line after warnings so it does not break Tower/Runner (https://github.com/ansible/ansible/pull/68517) diff --git a/lib/ansible/utils/display.py b/lib/ansible/utils/display.py index a24d2cd0d7a5a4..fe939868511b3c 100644 --- a/lib/ansible/utils/display.py +++ b/lib/ansible/utils/display.py @@ -153,14 +153,19 @@ def display(self, msg, color=None, stderr=False, screen_only=False, log_only=Fal nocolor = msg if not log_only: - if not msg.endswith(u'\n') and newline: - msg2 = msg + u'\n' + + has_newline = msg.endswith(u'\n') + if has_newline: + msg2 = msg[:-1] else: msg2 = msg if color: msg2 = stringc(msg2, color) + if has_newline or newline: + msg2 = msg2 + u'\n' + msg2 = to_bytes(msg2, encoding=self._output_encoding(stderr=stderr)) if sys.version_info >= (3,): # Convert back to text string on python3 diff --git a/test/units/utils/display/test_warning.py b/test/units/utils/display/test_warning.py index 2183005a0f12a5..be63c348bcad8b 100644 --- a/test/units/utils/display/test_warning.py +++ b/test/units/utils/display/test_warning.py @@ -27,7 +27,7 @@ def test_warning(capsys, mocker, warning_message): d.warning(warning_message) out, err = capsys.readouterr() assert d._warns == {expected_warning_message: 1} - assert err == '\x1b[1;35m{0}\x1b[0m\n\x1b[1;35m\x1b[0m'.format(expected_warning_message.rstrip('\n')) + assert err == '\x1b[1;35m{0}\x1b[0m\n'.format(expected_warning_message.rstrip('\n')) def test_warning_no_color(capsys, mocker, warning_message):