Skip to content

Commit fb2686f

Browse files
committed
Parse "-" as a plain argument
1 parent f92d839 commit fb2686f

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

lib/elixir/lib/option_parser.ex

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,14 @@ defmodule OptionParser do
206206
{:error, argv}
207207
end
208208

209+
defp next(["-"|_]=argv, _aliases, _switches, _strict) do
210+
{:error, argv}
211+
end
212+
213+
defp next(["- " <> _|_]=argv, _aliases, _switches, _strict) do
214+
{:error, argv}
215+
end
216+
209217
defp next(["-" <> option|rest], aliases, switches, strict) do
210218
{option, value} = split_option(option)
211219
opt = tag_option(option, value, switches, aliases)
@@ -353,9 +361,11 @@ defmodule OptionParser do
353361
{value, kinds, t}
354362
end
355363

356-
defp value_in_tail?(["-" <> _|_]), do: false
357-
defp value_in_tail?([]), do: false
358-
defp value_in_tail?(_), do: true
364+
defp value_in_tail?(["-"|_]), do: true
365+
defp value_in_tail?(["- " <> _|_]), do: true
366+
defp value_in_tail?(["-" <> _|_]), do: false
367+
defp value_in_tail?([]), do: false
368+
defp value_in_tail?(_), do: true
359369

360370
defp split_option(option) do
361371
case :binary.split(option, "=") do

lib/elixir/test/elixir/option_parser_test.exs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,12 @@ defmodule OptionParserTest do
172172
== {[source: "from_docs/", docs: "show"], [], []}
173173
end
174174

175+
test "collects multiple invalid options" do
176+
args = ["--bad", "opt", "foo", "-o", "bad", "bar"]
177+
assert OptionParser.parse(args, switches: [bad: :integer])
178+
== {[], ["foo", "bar"], [bad: "opt", o: "bad"]}
179+
end
180+
175181
test "parses more than one key/value options using strict" do
176182
assert OptionParser.parse(["--source", "from_docs/", "--docs", "show"],
177183
strict: [source: :string, docs: :string])
@@ -180,6 +186,18 @@ defmodule OptionParserTest do
180186
assert OptionParser.parse(["--source", "from_docs/", "--doc", "show"],
181187
strict: [source: :string, docs: :string])
182188
== {[source: "from_docs/"], ["show"], [doc: nil]}
189+
190+
assert OptionParser.parse(["--source", "from_docs/", "--doc=show"],
191+
strict: [source: :string, docs: :string])
192+
== {[source: "from_docs/"], [], [doc: "show"]}
193+
end
194+
195+
test "parses - as argument" do
196+
assert OptionParser.parse(["-a", "-", "-", "-b", "-"], aliases: [b: :boo])
197+
== {[boo: "-"], ["-"], [a: "-"]}
198+
199+
assert OptionParser.parse(["--foo", "-", "-b", "-"], strict: [foo: :boolean, boo: :string], aliases: [b: :boo])
200+
== {[foo: true, boo: "-"], ["-"], []}
183201
end
184202

185203
test "next strict: good options" do

0 commit comments

Comments
 (0)