| 1 |
|
%% Copyright (c) 2022 Peter Morgan <peter.james.morgan@gmail.com> |
| 2 |
|
%% |
| 3 |
|
%% Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
|
%% you may not use this file except in compliance with the License. |
| 5 |
|
%% You may obtain a copy of the License at |
| 6 |
|
%% |
| 7 |
|
%% http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
|
%% |
| 9 |
|
%% Unless required by applicable law or agreed to in writing, software |
| 10 |
|
%% distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
|
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
|
%% See the License for the specific language governing permissions and |
| 13 |
|
%% limitations under the License. |
| 14 |
|
|
| 15 |
|
|
| 16 |
|
-module(mcd_re). |
| 17 |
|
|
| 18 |
|
|
| 19 |
|
-export([run/1]). |
| 20 |
|
|
| 21 |
|
|
| 22 |
|
run(#{subject := Subject, re := RE} = Arg) -> |
| 23 |
188 |
{ok, MP} = re:compile(RE), |
| 24 |
188 |
{namelist, NL} = re:inspect(MP, namelist), |
| 25 |
188 |
case re:run( |
| 26 |
|
Subject, |
| 27 |
|
MP, |
| 28 |
|
options(Arg)) of |
| 29 |
|
|
| 30 |
|
{match, Matches} -> |
| 31 |
188 |
maps:filtermap( |
| 32 |
|
mapper(Arg), |
| 33 |
|
initial(NL, Matches, Arg)); |
| 34 |
|
|
| 35 |
|
nomatch -> |
| 36 |
:-( |
error(client_error) |
| 37 |
|
end. |
| 38 |
|
|
| 39 |
|
|
| 40 |
|
initial(NL, Matches, Arg) -> |
| 41 |
188 |
maps:merge( |
| 42 |
|
maps:get(acc0, Arg, maps:with([command, meta], Arg)), |
| 43 |
|
maps:from_list( |
| 44 |
518 |
lists:zip([binary_to_existing_atom(N) || N <- NL], Matches))). |
| 45 |
|
|
| 46 |
|
|
| 47 |
|
mapper(#{mapping := Mapping}) -> |
| 48 |
185 |
fun |
| 49 |
|
(K, V) -> |
| 50 |
697 |
case maps:find(K, Mapping) of |
| 51 |
|
{ok, Mapper} -> |
| 52 |
374 |
case erlang:fun_info(Mapper, arity) of |
| 53 |
|
{arity, 1} -> |
| 54 |
326 |
{true, Mapper(V)}; |
| 55 |
|
|
| 56 |
|
{arity, 2} -> |
| 57 |
48 |
Mapper(K, V) |
| 58 |
|
end; |
| 59 |
|
|
| 60 |
|
error -> |
| 61 |
323 |
{true, V} |
| 62 |
|
end |
| 63 |
|
end; |
| 64 |
|
|
| 65 |
|
mapper(_) -> |
| 66 |
3 |
fun |
| 67 |
|
(_, V) -> |
| 68 |
9 |
{true, V} |
| 69 |
|
end. |
| 70 |
|
|
| 71 |
|
options(#{options := Options}) -> |
| 72 |
:-( |
Options; |
| 73 |
|
|
| 74 |
|
options(#{}) -> |
| 75 |
188 |
[{capture, all_names, binary}]. |