-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathformat-eeps.erl
More file actions
executable file
·386 lines (365 loc) · 14.3 KB
/
Copy pathformat-eeps.erl
File metadata and controls
executable file
·386 lines (365 loc) · 14.3 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
%% This escript converts a set of EEPs from the style in the
%% EEP repository to the style needed by jekyll. Mostly it is the
%% metadata that is needed, but also some minor things in the styling
%% is fixed.
-module('format-eeps').
-export([main/1]).
main([Target,EEP0|EEPs]) ->
file:make_dir(Target),
[fix_eep(Target, EEP0, EEP) || EEP <- EEPs].
fix_eep(Target, EEP0, EEP) ->
% io:format("Parse eep: ~p~n",[EEP]),
{ok, Content} = file:read_file(EEP),
Basename = filename:basename(EEP),
"eep-" ++ Num = filename:rootname(Basename),
{FrontMatterStr, Matter} = gulp_frontmatter(Content),
FrontMatter0 = parse_frontmatter(Num, iolist_to_binary(FrontMatterStr)),
FrontMatter1 = maybe_add_title(FrontMatter0, Matter),
FrontMatter = maybe_add_date(FrontMatter1),
NewContent =
case list_to_integer(Num) =/= 0 of
true ->
[render_frontmatter(FrontMatter), gulp_matter(Matter)];
false ->
{ok, EEP0Bin} = file:read_file(EEP0),
[_IgnoreFrontMatter, HtmlMatter] = string:split(EEP0Bin,"<hr />"),
[render_frontmatter(FrontMatter),
re:replace(HtmlMatter,"(href=\")(eep-[0-9]+.md\")",
"\\1https://github.com/erlang/eep/blob/master/eeps/\\2")]
end,
%% Check if we can output the new content
try iolist_to_binary(NewContent) of
_ -> ok
catch _:_ ->
%% Flatten binaries and integers
Flat =
lists:foldl(
fun(E,{Curr,Acc}) when is_binary(E) ->
{<<Curr/binary,E/binary>>,Acc};
(E,{Curr,Acc}) when E =< 255, 0 =< E ->
{<<Curr/binary,E>>,Acc};
(E,{<<>>,Acc}) ->
{<<>>,Acc ++ [E]};
(E,{Curr,Acc}) ->
{<<>>,Acc ++ [Curr,E]}
end,{<<>>,[]},lists:flatten(NewContent)),
io:format("~p~n",[Flat])
end,
ok = file:write_file(filename:join(Target, Basename), NewContent).
%%
%% Replace the EEP style front matter (i.e. RFC 822):
%%
%% Author: John Doe
%% ****
%%
%% with jekyll style frontmatter (i.e. yaml)
%%
%% ---
%% Author: John Doe
%% ---
%%
gulp_frontmatter(B) ->
[Line | Lines] = string:split(string:trim(B),"\n",all),
gulp_frontmatter(Lines, string:trim(Line),[]).
%% RFC 2822 specifies that if the next line start with " " or "\t"
%% it is a continuation of the previous line.
gulp_frontmatter([<<" ",WSC,Line/binary>>|Rest],CurrLine,Acc)
when WSC =:= $ ; WSC =:= $\t ->
gulp_frontmatter(Rest, [CurrLine, " ", string:trim(Line)],Acc);
gulp_frontmatter([<<" ",Line/binary>>|Rest],CurrLine,Acc) when Line =/= <<>> ->
gulp_frontmatter(Rest, string:trim(Line),[CurrLine|Acc]);
gulp_frontmatter(Rest, CurrLine, Acc) ->
{[[Line,$\n] || Line <- lists:reverse([CurrLine | Acc])], lists:join($\n,Rest)}.
%% Escape any '{{' with {% raw %} in order for liquid templates to work
gulp_matter(Matter) ->
gulp_erlang_code(iolist_to_binary(add_raw_tags(Matter))).
add_raw_tags(Matter) ->
re:replace(Matter,"{{","{% raw %}{{{% endraw %}",[global]).
%% Convert all code blocks to erlang code blocks.
%% i.e.
%% foo() ->
%% bar.
%%
%% to
%% ```erlang
%% foo() ->
%% bar().
%% ```
gulp_erlang_code(<<" ",_/binary>> = Matter) ->
%% Some EEPs (like EEP 2) are one large code block. We do not want
%% to make those into an erlang code block.
Matter;
gulp_erlang_code(Matter) when is_binary(Matter) ->
[FirstLine | Rest] = string:split(string:trim(Matter),"\n",all),
Lines =
case re:run(FirstLine,"^\\*+$") of
{match,_} ->
Rest;
nomatch ->
[FirstLine | Rest]
end,
lists:join($\n,gulp_erlang_code(Lines, [])).
gulp_erlang_code([],[]) ->
[];
gulp_erlang_code([<<"\t",B/binary>>|Rest],list) ->
gulp_erlang_code([<<" ",B/binary>>|Rest],list);
%% Handle when we are inside a list
gulp_erlang_code([<<" ",_/binary>> = Line|Rest],list) ->
[Line | gulp_erlang_code(Rest,list)];
gulp_erlang_code([<<" ">> = Line|Rest],list) ->
[Line | gulp_erlang_code(Rest,list)];
gulp_erlang_code([<<" ">> = Line|Rest],list) ->
[Line | gulp_erlang_code(Rest,list)];
gulp_erlang_code([<<" ">> = Line|Rest],list) ->
[Line | gulp_erlang_code(Rest,list)];
gulp_erlang_code([<<"">> = Line|Rest],list) ->
[Line | gulp_erlang_code(Rest,list)];
gulp_erlang_code([Line|Rest],list) ->
case is_bullet_list(Line) of
true ->
[Line | gulp_erlang_code(Rest,list)];
false ->
[Line | gulp_erlang_code(Rest,[])]
end;
gulp_erlang_code([<<"```",_/binary>> = Line|Rest],[]) ->
[Line | gulp_erlang_code(Rest,fence)];
gulp_erlang_code([<<"```",_/binary>> = Line|Rest],fence) ->
[Line | gulp_erlang_code(Rest,[])];
gulp_erlang_code([Line|Rest],fence) ->
[Line | gulp_erlang_code(Rest,fence)];
gulp_erlang_code([<<" ",Line/binary>>|Rest],CodeBlock) ->
gulp_erlang_code(Rest,[Line|CodeBlock]);
gulp_erlang_code([<<"\t",Line/binary>>|Rest],CodeBlock) ->
gulp_erlang_code(Rest,[Line|CodeBlock]);
gulp_erlang_code([Line|Rest],[]) ->
case {is_bullet_list(Line),is_md_reference(Line)} of
{true, false} ->
[Line | gulp_erlang_code(Rest,list)];
{false, true} ->
case Rest of
[<<" ",Title/binary>> | T] ->
[[Line," ",Title] | gulp_erlang_code(T, [])];
[<<"\t",Title/binary>> | T] ->
[[Line," ",Title] | gulp_erlang_code(T, [])];
_ ->
[Line | gulp_erlang_code(Rest, [])]
end;
{false, false} ->
[Line | gulp_erlang_code(Rest,[])]
end;
gulp_erlang_code(Rest,CodeBlock) ->
case length(Rest) > 0 andalso re:run(hd(Rest),"^\\s*$") of
{match,_} ->
gulp_erlang_code(tl(Rest),[hd(Rest)|CodeBlock]);
_ ->
%% Check if the codeblock is only whitespace, if so ignore it
case re:run(CodeBlock,"^\\s*$") of
{match,_} ->
lists:reverse(CodeBlock) ++ gulp_erlang_code(Rest,[]);
nomatch ->
{TrimmedBlock, Tail} = trim(CodeBlock, []),
%% Fence the code block with ```erlang
["```erlang"] ++ TrimmedBlock ++ ["```"]
++ gulp_erlang_code(Tail ++ Rest,[])
end
end.
%% This trim expects a list in reverse and returns all trimmed
%% whitespace elements in the front of the list
%% (i.e. the back of the string)
trim([Line | Rest], Trimmed) ->
case re:run(Line,"^\\s*$") of
{match,_} ->
trim(Rest, [Line | Trimmed]);
_ ->
{lists:dropwhile(
fun(L) -> is_tuple(re:run(L,"^\\s*$")) end,
lists:reverse([Line|Rest])),
lists:reverse(Trimmed)}
end;
trim(List, Trimmed) ->
{lists:reverse(List), lists:reverse(Trimmed)}.
is_bullet_list(Line) ->
case re:run(Line,"^\\s*([0-9]+\\.|\\*|-)\\s{1,4}") of
{match,_} ->
true;
nomatch ->
false
end.
is_md_reference(Line) ->
case re:run(Line,"^\\[[^\\]]+\\]:") of
{match,_} ->
true;
nomatch ->
false
end.
%% Extract the EEP title from the body's first heading and add it to
%% the frontmatter if not already present. Most upstream EEPs put the
%% title in the body as `EEP N: Title\n----` (setext) and leave the
%% `Title:` frontmatter field unset; EEPs 2 and 3 carry an explicit
%% `Title:` because they are PEP-template-derived. Synthesize the
%% missing field so `page.Title` works uniformly across all EEPs.
maybe_add_title(#{ <<"Title">> := _ } = FrontMatter, _Matter) ->
FrontMatter;
maybe_add_title(FrontMatter, Matter) ->
MatterBin = iolist_to_binary(Matter),
%% Skip a possible leading `****` separator (the upstream EEP frontmatter
%% terminator) and any leading ATX heading marks. Capture the rest of the
%% title line.
case re:run(MatterBin,
"^\\s*(?:\\*+\\s*\\n\\s*)?(?:#+\\s+)?EEP\\s+[0-9]+\\s*:\\s*([^\\n]+?)\\s*(?:\\n|$)",
[{capture, all_but_first, binary}]) of
{match, [Title]} ->
FrontMatter#{ <<"Title">> => Title };
nomatch ->
FrontMatter
end.
%% Parse the upstream `Created:` field (formats like `01-Jul-2024`,
%% `1-Jun-2023`, `01-Sept-2019`, `07-may-2008`, or `DD-MM-YYYY` numeric)
%% into a Jekyll-friendly ISO `date:` field. Used to slot EEPs into the
%% index news reel alongside posts/news, which sort by `date`.
maybe_add_date(#{ <<"Created">> := Created } = FrontMatter) ->
case parse_created_date(Created) of
undefined -> FrontMatter;
Iso -> FrontMatter#{ <<"date">> => Iso }
end;
maybe_add_date(FrontMatter) ->
FrontMatter.
parse_created_date(Created) ->
Trimmed = string:trim(iolist_to_binary(Created)),
%% Try DD-Mon-YYYY (alphabetic month, case-insensitive)
case re:run(Trimmed, "^([0-9]{1,2})-([A-Za-z]+)-([0-9]{4})$",
[{capture, all_but_first, binary}]) of
{match, [DayB, MonB, YearB]} ->
case month_to_num(string:lowercase(MonB)) of
undefined -> undefined;
Mon ->
Day = binary_to_integer(DayB),
iolist_to_binary(io_lib:format("~s-~2..0w-~2..0w",
[YearB, Mon, Day]))
end;
nomatch ->
%% Fall back to DD-MM-YYYY numeric
case re:run(Trimmed, "^([0-9]{1,2})-([0-9]{1,2})-([0-9]{4})$",
[{capture, all_but_first, binary}]) of
{match, [DayB, MonB, YearB]} ->
Day = binary_to_integer(DayB),
Mon = binary_to_integer(MonB),
iolist_to_binary(io_lib:format("~s-~2..0w-~2..0w",
[YearB, Mon, Day]));
nomatch ->
undefined
end
end.
month_to_num(<<"jan">>) -> 1;
month_to_num(<<"feb">>) -> 2;
month_to_num(<<"mar">>) -> 3;
month_to_num(<<"apr">>) -> 4;
month_to_num(<<"may">>) -> 5;
month_to_num(<<"jun">>) -> 6;
month_to_num(<<"jul">>) -> 7;
month_to_num(<<"aug">>) -> 8;
month_to_num(<<"sep">>) -> 9;
month_to_num(<<"sept">>) -> 9;
month_to_num(<<"oct">>) -> 10;
month_to_num(<<"nov">>) -> 11;
month_to_num(<<"dec">>) -> 12;
month_to_num(_) -> undefined.
parse_frontmatter(NumStr, FrontMatterStr) ->
%% Strip any leading 0s from NumStr
Num = case string:trim(NumStr, leading, "0") of
"" -> "0";
N -> N
end,
FrontMatter
= lists:foldl(
fun
(<<>>,M) ->
M;
(Line,M) ->
case string:split(string:trim(Line),":") of
[Key,Value] ->
M#{ Key => parse_frontmatter_value(
string:trim(Key),
string:trim(Value)) }
end
end, #{ <<"Num">> => Num, <<"layout">> => "eep" },
string:split(FrontMatterStr,"\n",all)),
maps:fold(
fun(<<"Author">>,[{Owner,_}|_], M) ->
M#{ <<"Owner">> => Owner };
(<<"Type">>,Type, M) ->
M#{ <<"ShortType">> => short_type(Type) };
(<<"Status">>, Status, M) ->
maps:merge(M, Status);
(_,_,M) ->
M
end, FrontMatter, FrontMatter).
parse_frontmatter_value(<<"Author">>, Value) ->
Authors = string:split(Value,", ",all),
lists:map(
fun(Author) ->
case re:run(Author, "^([^<]+)(<([^>]+)>)?$",[{capture,all_but_first,binary}]) of
{match,[Name,_,Email]} ->
{ string:trim(Name), string:trim(Email) };
{match,[Name]} ->
{ string:trim(Name), undefined }
end
end, Authors);
parse_frontmatter_value(<<"Status">>, Value) ->
%% This regexp matches "SomeStatus/SomeTag Some Description
case re:run(Value,"^([^/]+)(/?[^\s]*)\s*(.*)$",[{capture,all_but_first,binary}]) of
{match,[Status, Tag, Descr]} ->
#{ <<"Status">> => Status,
<<"ShortStatus">> => short_status(Status),
<<"StatusTag">> => Tag,
<<"StatusDescription">> => Descr }
end;
parse_frontmatter_value(_, Value) ->
Value.
short_status(Status) ->
maps:get(Status,
#{ <<"Active">> => "",
<<"Draft">> => "",
<<"Accepted">> => "A",
<<"Rejected">> => "R",
<<"Replaced">> => "Rep",
<<"Withdrawn">> => "W",
<<"Deferred">> => "D",
<<"Final">> => "F"}).
short_type(Type) ->
maps:get(Type,
#{ <<"Standards Track">> => "S",
<<"Process">> => "P" }).
%% Wrap a YAML string in double quotes, escaping `\` and `"`.
yaml_quote(Value) ->
Bin = iolist_to_binary(Value),
Escaped0 = re:replace(Bin, <<"\\\\">>, <<"\\\\\\\\">>, [global, {return, binary}]),
Escaped = re:replace(Escaped0, <<"\"">>, <<"\\\\\"">>, [global, {return, binary}]),
<<$", Escaped/binary, $">>.
render_frontmatter(FrontMatter) ->
FM =
["---"] ++
lists:map(
fun({<<"Author">> = Key,Value}) ->
%% We create a yaml array out of the authors
[Key,":",$\n,
lists:join(
$\n,
lists:map(
fun
({Name,undefined}) ->
[" - ",Name];
({Name,Email}) ->
[" - ",Name," <",Email,">"]
end,Value))
];
({<<"Title">> = Key, Value}) ->
%% Always emit Title as a double-quoted YAML string —
%% titles can contain ': ' (e.g. "B-trees: balanced...")
%% which would otherwise be parsed as a nested mapping.
[Key, ": ", yaml_quote(Value)];
({Key,Value}) ->
[Key,": ",Value]
end, maps:to_list(FrontMatter)) ++
["---"],
[[Line,$\n] || Line <- FM].