Skip to content

Commit ce3674d

Browse files
author
José Valim
committed
Add OptionParser.to_argv/1
1 parent e4cfb62 commit ce3674d

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/elixir/lib/option_parser.ex

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,36 @@ defmodule OptionParser do
231231
{:error, argv}
232232
end
233233

234+
@doc """
235+
Receives a key-value enumerable and convert it to argv.
236+
237+
Keys must be atoms. Keys with nil value are discarded,
238+
boolean values are converted to `--key` or `--no-key`
239+
and all other values are converted using `to_string/1`.
240+
241+
## Examples
242+
243+
iex> OptionParser.to_argv([foo_bar: "baz"])
244+
["--foo-bar", "baz"]
245+
246+
iex> OptionParser.to_argv([bool: true, bool: false, discarded: nil])
247+
["--bool", "--no-bool"]
248+
249+
"""
250+
@spec to_argv(Enumerable.t) :: argv
251+
def to_argv(enum) do
252+
Enum.flat_map(enum, fn
253+
{_key, nil} -> []
254+
{key, true} -> [to_switch(key)]
255+
{key, false} -> [to_switch(key, "--no-")]
256+
{key, value} -> [to_switch(key), to_string(value)]
257+
end)
258+
end
259+
260+
defp to_switch(key, prefix \\ "--") when is_atom(key) do
261+
prefix <> String.replace(Atom.to_string(key), "_", "-")
262+
end
263+
234264
@doc ~S"""
235265
Splits a string into argv chunks.
236266

lib/elixir/test/elixir/option_parser_test.exs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,4 +314,12 @@ defmodule OptionParserTest do
314314
assert OptionParser.split(~S[foo '\"bar"\'\ '])
315315
== ["foo", "\\\"bar\"'\\ "]
316316
end
317+
318+
test "to_argv" do
319+
assert OptionParser.to_argv([foo_bar: "baz"]) ==
320+
["--foo-bar", "baz"]
321+
322+
assert OptionParser.to_argv([bool: true, bool: false, discarded: nil]) ==
323+
["--bool", "--no-bool"]
324+
end
317325
end

0 commit comments

Comments
 (0)