rabbitmq-server/deps/rabbitmq_cli/lib/rabbitmq/cli/formatters/csv.ex

111 lines
3.2 KiB
Elixir
Raw Normal View History

2016-11-15 19:14:44 +08:00
## The contents of this file are subject to the Mozilla Public License
## Version 1.1 (the "License"); you may not use this file except in
## compliance with the License. You may obtain a copy of the License
## at http://www.mozilla.org/MPL/
##
## Software distributed under the License is distributed on an "AS IS"
## basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
## the License for the specific language governing rights and
## limitations under the License.
##
## The Original Code is RabbitMQ.
##
## The Initial Developer of the Original Code is GoPivotal, Inc.
## Copyright (c) 2007-2016 Pivotal Software, Inc. All rights reserved.
alias RabbitMQ.CLI.Formatters.FormatterHelpers, as: FormatterHelpers
defmodule RabbitMQ.CLI.Formatters.Csv do
@behaviour RabbitMQ.CLI.FormatterBehaviour
def format_stream(stream, _) do
## Flatten list_consumers
Stream.flat_map(stream,
fn({:error, msg}) ->
[{:error, msg}];
([first | _] = element) ->
case Keyword.keyword?(first) or is_map(first) do
true -> element;
false -> [element]
end
(other) ->
other
end)
## Add info_items names
|> Stream.transform(:init,
fn
({:error, msg}, _) ->
{:error, msg};
(element, :init) ->
{
case keys(element) do
nil -> [values(element)];
ks -> [ks, values(element)]
end,
:next
};
(element, :next) ->
{[values(element)], :next}
end)
|> CSV.encode([delimiter: ""])
end
def format_output(output, _) do
case keys(output) do
nil -> [values(output)];
ks -> [ks, values(output)]
end
|> CSV.encode
end
def keys(map) when is_map(map) do
Map.keys(map)
end
def keys(list) when is_list(list) do
case Keyword.keyword?(list) do
true -> Keyword.keys(list);
false -> nil
end
end
def keys(_other) do
nil
end
def values(map) when is_map(map) do
Map.values(map)
end
def values([]) do
[]
end
def values(list) when is_list(list) do
case Keyword.keyword?(list) do
true -> Keyword.values(list);
false -> list
end
end
def values(other) do
other
end
end
defimpl CSV.Encode, for: PID do
def encode(pid, env \\ []) do
:rabbit_misc.pid_to_string(pid) |> CSV.Encode.encode(env)
end
end
defimpl CSV.Encode, for: List do
def encode(list, env \\ [])
def encode([{key, type, _table_entry_value} | _] = value, env)
when is_binary(key) and is_atom(type) do
:io_lib.format("~1000000000000tp",
[FormatterHelpers.prettify_amqp_table(value, true)])
|> CSV.Encode.encode(env)
end
def encode(list, env) do
to_string(list) |> CSV.Encode.encode(env)
end
end