forked from elixir-plug/plug
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ex
More file actions
302 lines (232 loc) · 8.8 KB
/
Copy pathutils.ex
File metadata and controls
302 lines (232 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
defmodule Plug.Router.InvalidSpecError do
defexception message: "invalid route specification"
end
defmodule Plug.Router.MalformedURIError do
defexception message: "malformed URI", plug_status: 400
end
defmodule Plug.Router.Utils do
@moduledoc false
@doc """
Decodes path information for dispatching.
"""
def decode_path_info!(conn) do
Enum.map(conn.path_info, &URI.decode/1)
end
@doc """
Converts a given method to its connection representation.
The request method is stored in the `Plug.Conn` struct as an uppercase string
(like `"GET"` or `"POST"`). This function converts `method` to that
representation.
## Examples
iex> Plug.Router.Utils.normalize_method(:get)
"GET"
"""
def normalize_method(method) do
method |> to_string |> String.upcase()
end
@doc ~S"""
Builds the pattern that will be used to match against the request's host
(provided via the `:host`) option.
If `host` is `nil`, a wildcard match (`_`) will be returned. If `host` ends
with a dot, a match like `"host." <> _` will be returned.
## Examples
iex> Plug.Router.Utils.build_host_match(nil)
{:_, [], Plug.Router.Utils}
iex> Plug.Router.Utils.build_host_match("foo.com")
"foo.com"
iex> "api." |> Plug.Router.Utils.build_host_match() |> Macro.to_string()
"\"api.\" <> _"
"""
def build_host_match(host) do
cond do
is_nil(host) -> quote do: _
String.last(host) == "." -> quote do: unquote(host) <> _
is_binary(host) -> host
end
end
@doc """
Generates a representation that will only match routes
according to the given `spec`.
If a non-binary spec is given, it is assumed to be
custom match arguments and they are simply returned.
## Examples
iex> Plug.Router.Utils.build_path_match("/foo/:id")
{[:id], ["foo", {:id, [], nil}]}
"""
def build_path_match(path, context \\ nil) when is_binary(path) do
case build_path_clause(path, true, context) do
{params, match, true, _post_match} ->
{Enum.map(params, &String.to_atom(&1)), match}
{_, _, _, _} ->
raise Plug.Router.InvalidSpecError,
"invalid dynamic path. Only letters, numbers, and underscore are allowed after : in " <>
inspect(path)
end
end
@doc """
Builds a list of path param names and var match pairs.
This is used to build parameter maps from existing variables.
Excludes variables with underscore.
## Examples
iex> Plug.Router.Utils.build_path_params_match(["id"])
[{"id", {:id, [], nil}}]
iex> Plug.Router.Utils.build_path_params_match(["_id"])
[]
iex> Plug.Router.Utils.build_path_params_match([:id])
[{"id", {:id, [], nil}}]
iex> Plug.Router.Utils.build_path_params_match([:_id])
[]
"""
def build_path_params_match(params, context \\ nil)
def build_path_params_match([param | _] = params, context) when is_binary(param) do
params
|> Enum.reject(&match?("_" <> _, &1))
|> Enum.map(&{&1, Macro.var(String.to_atom(&1), context)})
end
def build_path_params_match([param | _] = params, context) when is_atom(param) do
params
|> Enum.map(&{Atom.to_string(&1), Macro.var(&1, context)})
|> Enum.reject(&match?({"_" <> _var, _macro}, &1))
end
def build_path_params_match([], _context) do
[]
end
@doc """
Builds a clause with match, guards, and post matches,
including the known parameters.
"""
def build_path_clause(path, guard, context \\ nil) when is_binary(path) do
compiled = :binary.compile_pattern(["\\:", ":", "*"])
{params, match, guards, post_match} =
path
|> split()
|> build_path_clause([], [], [], [], context, compiled)
if guard != true and guards != [] do
raise ArgumentError, "cannot use \"when\" guards in route when using suffix matches"
end
params = params |> Enum.uniq() |> Enum.reverse()
guards = Enum.reduce(guards, guard, "e(do: unquote(&1) and unquote(&2)))
{params, match, guards, post_match}
end
defp build_path_clause([segment | rest], params, match, guards, post_match, context, compiled) do
case :binary.matches(segment, compiled) do
[] ->
build_path_clause(rest, params, [segment | match], guards, post_match, context, compiled)
[{prefix_size, match_length}] when match_length == 2 ->
suffix_size = byte_size(segment) - prefix_size - 2
<<prefix::binary-size(prefix_size), matched::binary-size(match_length),
suffix::binary-size(suffix_size)>> = segment
case matched do
"\\:" ->
escaped_segment = prefix <> ":" <> suffix
build_path_clause(
rest,
params,
[escaped_segment | match],
guards,
post_match,
context,
compiled
)
_ ->
raise Plug.Router.InvalidSpecError,
"the path segment contains invalid characters, got: " <> inspect(segment)
end
[{prefix_size, _}] ->
suffix_size = byte_size(segment) - prefix_size - 1
<<prefix::binary-size(prefix_size), char, suffix::binary-size(suffix_size)>> = segment
{param, suffix} = parse_suffix(suffix)
params = [param | params]
var = Macro.var(String.to_atom(param), context)
case char do
?* when suffix != "" ->
raise Plug.Router.InvalidSpecError,
"globs (*var) cannot be followed by suffixes, got: #{inspect(segment)}"
?* when rest != [] ->
raise Plug.Router.InvalidSpecError,
"globs (*var) must always be in the last path, got glob in: #{inspect(segment)}"
?* ->
submatch =
if prefix != "" do
IO.warn("""
doing a prefix match with globs is deprecated, invalid segment #{inspect(segment)}.
You can either replace by a single segment match:
/foo/bar-:var
Or by mixing single segment match with globs:
/foo/bar-:var/*rest
""")
quote do: [unquote(prefix) <> _ | _] = unquote(var)
else
var
end
match =
case match do
[] ->
submatch
[last | match] ->
Enum.reverse([quote(do: unquote(last) | unquote(submatch)) | match])
end
{params, match, guards, post_match}
?: ->
match =
if prefix == "",
do: [var | match],
else: [quote(do: unquote(prefix) <> unquote(var)) | match]
{post_match, guards} =
if suffix == "" do
{post_match, guards}
else
guard =
quote do
binary_part(
unquote(var),
byte_size(unquote(var)) - unquote(byte_size(suffix)),
unquote(byte_size(suffix))
) == unquote(suffix)
end
trim =
quote do
unquote(var) = String.trim_trailing(unquote(var), unquote(suffix))
end
{[trim | post_match], [guard | guards]}
end
build_path_clause(rest, params, match, guards, post_match, context, compiled)
end
[_ | _] ->
raise Plug.Router.InvalidSpecError,
"only one dynamic entry (:var or *glob) per path segment is allowed, got: " <>
inspect(segment)
end
end
defp build_path_clause([], params, match, guards, post_match, _context, _compiled) do
{params, Enum.reverse(match), guards, post_match}
end
defp parse_suffix(<<h, t::binary>>) when h in ?a..?z or h == ?_,
do: parse_suffix(t, <<h>>)
defp parse_suffix(suffix) do
raise Plug.Router.InvalidSpecError,
"invalid dynamic path. The characters : and * must be immediately followed by " <>
"lowercase letters or underscore, got: :#{suffix}"
end
defp parse_suffix(<<h, t::binary>>, acc)
when h in ?a..?z or h in ?A..?Z or h in ?0..?9 or h == ?_,
do: parse_suffix(t, <<acc::binary, h>>)
defp parse_suffix(rest, acc),
do: {acc, rest}
@doc """
Splits the given path into several segments.
It ignores both leading and trailing slashes in the path.
## Examples
iex> Plug.Router.Utils.split("/foo/bar")
["foo", "bar"]
iex> Plug.Router.Utils.split("/:id/*")
[":id", "*"]
iex> Plug.Router.Utils.split("/foo//*_bar")
["foo", "*_bar"]
"""
def split(bin) do
for segment <- String.split(bin, "/"), segment != "", do: segment
end
@deprecated "Use Plug.forward/4 instead"
defdelegate forward(conn, new_path, target, opts), to: Plug
end