Skip to content

Commit

Permalink
Merge pull request #9 from kevinschweikert/feature/newlines
Browse files Browse the repository at this point in the history
Multiline Curl commands
  • Loading branch information
derekkraan authored Jun 16, 2024
2 parents d92bc9a + 1a3c12e commit 6fb6302
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Changelog

## 0.98.5
- Multiline Curl commands are now supported

## 0.98.4
- Add CurlReq.Plugin
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ The docs can be found at <https://hexdocs.pm/curl_req>.

Contributions are welcome! There are gaps in the library, and this is open source, so let's work together to fill them!

- [ ] ~CURL sigil handles newlines
- [x] ~CURL sigil handles newlines
- [x] curl [url]
- [x] curl -H
- [x] curl -X
Expand Down
17 changes: 12 additions & 5 deletions lib/curl_req/macro.ex
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
defmodule CurlReq.Macro do
@moduledoc false

# TODO: handle newlines

@spec parse(String.t()) :: Req.Request.t()
def parse(command) do
command =
command
|> String.trim()
|> String.trim_leading("curl")

{options, [url], _invalid} =
{options, rest, _invalid} =
command
|> OptionParser.split()
|> OptionParser.parse(
Expand All @@ -36,10 +34,19 @@ defmodule CurlReq.Macro do
]
)

url = String.trim(url)
[url] =
rest
|> Enum.flat_map(fn part ->
case URI.new(part) do
{:ok, uri} -> [uri]
_ -> []
end
end)

%Req.Request{}
|> Req.merge(url: url)
# Req would accept an URI struct but here we use to_string/1 because Req uses URI.parse/1 which sets the deprecated `authority` field which upsets the test assertions.
# Can be removed the Req uses URI.new/1
|> Req.merge(url: URI.to_string(url))
|> add_header(options)
|> add_method(options)
|> add_body(options)
Expand Down
35 changes: 35 additions & 0 deletions test/curl_req/macro_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,39 @@ defmodule CurlReq.MacroTest do
}
end
end

describe "newlines" do
test "sigil_CURL supports newlines" do
curl = ~CURL"""
curl -X POST \
--location \
https://example.com
"""

assert curl == %Req.Request{
method: :post,
url: URI.parse("https://example.com"),
registered_options: MapSet.new([:redirect]),
options: %{redirect: true},
response_steps: [redirect: &Req.Steps.redirect/1]
}
end

test "from_curl supports newlines" do
curl =
from_curl("""
curl -X POST \
--location \
https://example.com
""")

assert curl == %Req.Request{
method: :post,
url: URI.parse("https://example.com"),
registered_options: MapSet.new([:redirect]),
options: %{redirect: true},
response_steps: [redirect: &Req.Steps.redirect/1]
}
end
end
end

0 comments on commit 6fb6302

Please sign in to comment.