File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -231,6 +231,36 @@ defmodule OptionParser do
231
231
{ :error , argv }
232
232
end
233
233
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
+
234
264
@ doc ~S"""
235
265
Splits a string into argv chunks.
236
266
Original file line number Diff line number Diff line change @@ -314,4 +314,12 @@ defmodule OptionParserTest do
314
314
assert OptionParser . split ( ~S[ foo '\"bar"\'\ '] )
315
315
== [ "foo" , "\\ \" bar\" '\\ " ]
316
316
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
317
325
end
You can’t perform that action at this time.
0 commit comments