Skip to content

Commit ea1bf2c

Browse files
Merge pull request #14773 from lukebakken/lukebakken/rabbitmq-server-14511-followup
Yet another JSON CLI formatter fix
2 parents bc8a030 + 4072326 commit ea1bf2c

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

deps/rabbitmq_cli/lib/rabbitmq/cli/formatters/json.ex

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,13 +91,29 @@ defmodule RabbitMQ.CLI.Formatters.Json do
9191
"Ref(#{inspect(data)})"
9292
end
9393

94+
defp convert_erlang_strings(data) when is_binary(data) do
95+
convert_binary(data)
96+
end
97+
9498
defp convert_erlang_strings([]), do: []
9599

96-
defp convert_erlang_strings([b | _rest]=data) when is_binary(b) do
97-
# Assume this is a list of strings already converted
100+
defp convert_erlang_strings([val]=data) when is_integer(val) and val > 255 do
101+
# This is likely a value like [5672], which we don't want
102+
# to convert to the equivalent unicode codepoint.
103+
data
104+
end
105+
106+
defp convert_erlang_strings([v0, v1]=data) when
107+
is_integer(v0) and v0 > 255 and is_integer(v1) and v1 > 255 do
108+
# This is likely a value like [5672, 5682], which we don't want
109+
# to convert to the equivalent unicode codepoint.
98110
data
99111
end
100112

113+
defp convert_erlang_strings([b | rest]) when is_binary(b) do
114+
[convert_binary(b) | convert_erlang_strings(rest)]
115+
end
116+
101117
defp convert_erlang_strings(data) when is_list(data) do
102118
try do
103119
case :unicode.characters_to_binary(data, :utf8) do
@@ -129,4 +145,21 @@ defmodule RabbitMQ.CLI.Formatters.Json do
129145
end
130146

131147
defp convert_erlang_strings(data), do: data
148+
149+
defp convert_binary(data) when is_binary(data) do
150+
try do
151+
case :unicode.characters_to_binary(data, :utf8) do
152+
binary when is_binary(binary) ->
153+
# Successfully converted - it was a valid Unicode string
154+
binary
155+
_ ->
156+
# Conversion failed - not a Unicode string
157+
Base.encode64(data)
158+
end
159+
rescue
160+
ArgumentError ->
161+
# badarg exception - just base64 encode it.
162+
Base.encode64(data)
163+
end
164+
end
132165
end

deps/rabbitmq_cli/test/json_formatting_test.exs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,5 +100,9 @@ defmodule JSONFormattingTest do
100100
assert Map.has_key?(rabbit, "data_dir")
101101
data_dir = rabbit["data_dir"]
102102
assert is_binary(data_dir)
103+
104+
assert Map.has_key?(rabbit, "tcp_listeners")
105+
tcp_listeners = rabbit["tcp_listeners"]
106+
assert is_list(tcp_listeners)
103107
end
104108
end

0 commit comments

Comments
 (0)