-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerator.elm
508 lines (411 loc) · 16.9 KB
/
Generator.elm
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
module Docs.Generator
exposing
( Module
, Alias
, Union
, Value
, Case
, moduleDecoder
, generate
)
{-| Render code documentation in Markdown.
@docs Module, Alias, Union, Value, Case, moduleDecoder, generate
-}
import Dict exposing (Dict)
import Json.Decode as Decode
import Json.Decode.Extra as Decode
import List.Extra as List
import Maybe.Extra as Maybe
import StringUtils exposing (..)
import Node.Encoding as Encoding
import Node.Error as Error
import Node.FileSystem as FileSystem
import Node.Path as NodePath
import Regex
import Result.Extra as Result
import Task exposing (Task)
import Utils.Ops exposing (..)
import Utils.Regex exposing (..)
import Utils.Match exposing (..)
import Utils.Dict exposing (..)
import Docs.SignatureExtractor exposing (..)
bold : String -> String
bold s =
"**"
++ (s
|> replaceAll "\\*" "\\*"
)
++ "**"
definitionHeader : String -> String
definitionHeader s =
"### " ++ s ++ "\n"
elmCode : String -> String
elmCode s =
("```elm\n" ++ s ++ "\n```")
|> removeRedundantTypes
operatorize : String -> String
operatorize name =
Regex.contains (Regex.regex "[a-z_A-Z]") name
? ( name, "(" ++ name ++ ")" )
{-| removeRedundantTypes like `Maybe.Maybe` and `Result.Result`, and just make them `Maybe` and `Result`
-}
removeRedundantTypes : String -> String
removeRedundantTypes code =
code
|> Regex.replace (Regex.All)
(Regex.regex "(\\b\\w+\\b)\\.(\\b\\w+\\b)")
(\match ->
match
|> getSubmatches2
|> (\( w1, w2 ) -> (w1 == w2) ? ( w1, w1 ++ "." ++ w2 ))
)
{-| Render code documentation files in Markdown.
sourceDirectory : String
sourceDirectory =
"."
destinationDirectory : String
destinationDirectory =
"elm-docs"
generate "/" sourceDirectory destinationDirectory
-}
generate : String -> String -> String -> Task String ()
generate pathSep source destination =
getSourceCodeFilenames (NodePath.dirname source)
|> Task.andThen
(\sourcePaths ->
(FileSystem.readFileAsString source Encoding.Utf8 |> Task.mapError Error.message)
|> Task.andThen
(\content ->
Decode.decodeString (Decode.list moduleDecoder) content
-- |> Result.map (List.map moduleToMarkdown)
|> Result.map
(\modules ->
modules
|> List.map
(\module_ ->
getModuleSignatures sourcePaths module_.name
|> Task.andThen
(\moduleSignatures ->
moduleToMarkdown moduleSignatures module_
|> Task.succeed
)
)
)
|> Result.unpack Task.fail Task.sequence
)
|> Task.andThen
(\files ->
files
|> List.map
(\file ->
FileSystem.writeFileFromString
(destination ++ pathSep ++ (Tuple.first file) ++ ".md")
FileSystem.defaultMode
FileSystem.defaultEncoding
(Tuple.second file)
|> Task.mapError (\_ -> "File write error")
)
|> Task.sequence
)
|> Task.andThen (\_ -> Task.succeed ())
)
-- Module -> Markdown String
-- name becomes `# name`
-- comment needs each @docs line replaced
moduleToMarkdown : Dict ModuleName (Dict Name Signature) -> Module -> ( String, String )
moduleToMarkdown signatures module_ =
( module_.name
, ("# " ++ module_.name ++ "\n\n")
++ (processComments (Dict.get module_.name signatures ?= Dict.empty) module_)
++ "\n\n"
)
type alias LinkDict =
Dict String ( String, Int )
makeUnique : LinkDict -> Int -> String -> String
makeUnique dict index name =
(name ++ "-" +++ index)
|> (\newName ->
(newName
|> flip Dict.get dict
)
|?-> ( newName, \_ -> makeUnique dict (index + 1) name )
)
{-| Follow link name logic described here: <https://gist.github.com/asabaylus/3071099>
-}
makeLinkName : LinkDict -> String -> String
makeLinkName dict name =
name
|> String.toLower
|> replaceAll "[^a-zA-Z0-9- ]" ""
|> (\linkName ->
(linkName
|> flip Dict.get dict
)
|?-> ( linkName, \_ -> makeUnique dict 1 linkName )
)
makeLink : ( String, String ) -> String
makeLink ( link, name ) =
"- [" ++ name ++ "]" ++ "(#" ++ link ++ ")"
makeTableOfContents : LinkDict -> Int -> List String -> String
makeTableOfContents dict index names =
(dict
|> Dict.filter (\_ ( _, index2 ) -> index2 == index)
|> Dict.map (\key ( name, _ ) -> name)
|> swap
)
|??->
( \_ -> Debug.crash "BUG: non-unique name"
, \dict ->
names
|> List.filterMap (\name -> Dict.get name dict |?-> ( Nothing, \link -> Just ( link, name ) ))
|> List.map makeLink
|> String.join "\n"
|> flip (++) "\n\n"
)
docsRegex : Regex.Regex
docsRegex =
Regex.regex "\\@docs (.*)?,?"
processComments : Dict Name Signature -> Module -> String
processComments signatures { comment, aliases, unions, values } =
comment
|> String.trim
|> Regex.find Regex.All docsRegex
|> List.foldl
(\match dict ->
(match
|> extract1
)
|?!->
( \_ -> Debug.crash "BUG: bad regex"
, flip (|?->)
( dict
, \matchStr ->
matchStr
|> Regex.replace Regex.All (Regex.regex "\\@docs\\s*") (always "")
|> Regex.split Regex.All (Regex.regex "\\s*,\\s*")
|> List.unique
|> List.foldl (\name dict -> Dict.insert (makeLinkName dict name) ( name, match.index ) dict) dict
)
)
)
Dict.empty
|> (\pageDict ->
(Regex.replace Regex.All docsRegex)
(\match ->
match.match
|> Regex.replace Regex.All (Regex.regex "\\@docs\\s*") (always "")
|> Regex.split Regex.All (Regex.regex "\\s*,\\s*")
|> List.unique
|> (\names ->
names
|> makeTableOfContents pageDict match.index
|> (\tableOfContents ->
-- take each name
-- find which type name is
tableOfContents
++ (List.map
(\name ->
name
|> replaceFirst "^\\(" ""
|> replaceFirst "\\)$" ""
|> (\name ->
Maybe.values
[ List.find (.name >> (==) name) aliases |> Maybe.map (aliasToMarkdown signatures)
, List.find (.name >> (==) name) unions |> Maybe.map (unionToMarkdown signatures)
, List.find (.name >> (==) name) values |> Maybe.map (valueToMarkdown signatures)
]
|> List.head
|> Maybe.withDefault (name ++ " : Not Found!!!")
)
)
names
|> String.join "\n\n---\n\n"
)
)
)
)
(String.trim comment)
)
-- ALIAS
{-| Exposed type aliases
-}
type alias Alias =
{ name : String
, comment : String
, args : List String
, type_ : String
}
aliasDecoder : Decode.Decoder Alias
aliasDecoder =
Decode.succeed Alias
|> Decode.andMap (Decode.field "name" Decode.string)
|> Decode.andMap (Decode.field "comment" Decode.string |> Decode.andThen (Decode.succeed << fixCodeBlocks))
|> Decode.andMap (Decode.field "args" <| Decode.list Decode.string)
|> Decode.andMap (Decode.field "type" Decode.string)
aliasSignature : Dict Name Signature -> Alias -> String
aliasSignature signatures alias_ =
(("type alias " ++ alias_.name)
|> (definitionHeader << bold)
)
++ (("type alias " ++ alias_.name ++ " " ++ (String.join " " alias_.args) ++ " =")
++ (Dict.get alias_.name signatures ?= (newLine ++ tab ++ alias_.type_))
|> elmCode
)
aliasToMarkdown : Dict Name Signature -> Alias -> String
aliasToMarkdown signatures alias_ =
aliasSignature signatures alias_ ++ "\n\n" ++ (String.trim alias_.comment)
-- UNION
{-| Case of a union type
-}
type alias Case =
( String, List String )
caseDecoder : Decode.Decoder Case
caseDecoder =
Decode.map2 (\name args -> ( name, args ))
(Decode.index 0 Decode.string)
(Decode.index 1 <| Decode.list Decode.string)
{-| Exposed union types
-}
type alias Union =
{ name : String
, comment : String
, args : List String
, tags : List Case
}
unionDecoder : Decode.Decoder Union
unionDecoder =
Decode.succeed Union
|> Decode.andMap (Decode.field "name" Decode.string)
|> Decode.andMap (Decode.field "comment" Decode.string |> Decode.andThen (Decode.succeed << fixCodeBlocks))
|> Decode.andMap (Decode.field "args" <| Decode.list Decode.string)
|> Decode.andMap (Decode.field "cases" <| Decode.list caseDecoder)
caseToMarkdown : Case -> String
caseToMarkdown tag =
(Tuple.first tag) ++ " " ++ (String.join " " <| Tuple.second tag)
unionSignature : Dict Name Signature -> Union -> String
unionSignature signatures union =
(("type " ++ union.name)
|> (definitionHeader << bold)
)
++ (("type " ++ union.name ++ " " ++ (String.join " " union.args) ++ newLine)
++ Dict.get union.name signatures
?= (tab
++ "= "
++ (List.map caseToMarkdown union.tags
|> String.join (newLine ++ tab ++ "| ")
)
)
|> elmCode
)
unionToMarkdown : Dict Name Signature -> Union -> String
unionToMarkdown signatures union =
unionSignature signatures union
++ "\n\n"
++ (String.trim union.comment)
-- VALUE
{-| Exposed values
-}
type alias Value =
{ name : String
, comment : String
, type_ : String
}
valueDecoder : Decode.Decoder Value
valueDecoder =
Decode.succeed Value
|> Decode.andMap (Decode.field "name" Decode.string)
|> Decode.andMap (Decode.field "comment" Decode.string |> Decode.andThen (Decode.succeed << fixCodeBlocks))
|> Decode.andMap (Decode.field "type" Decode.string)
valueSignature : Dict Name Signature -> Value -> String
valueSignature signatures value =
(operatorize value.name
|> (definitionHeader << bold)
)
++ ((operatorize value.name ++ " : " ++ (Dict.get value.name signatures ?= value.type_))
|> elmCode
)
valueToMarkdown : Dict Name Signature -> Value -> String
valueToMarkdown signatures value =
valueSignature signatures value
++ "\n\n"
++ (String.trim value.comment)
{-| Module doc info
-}
type alias Module =
{ name : String
, comment : String
, aliases : List Alias
, unions : List Union
, values : List Value
}
{-| Decoder for a single module
Use with Json.Decode.list since Elm's output for documentation JSON is a list of Modules.
-}
moduleDecoder : Decode.Decoder Module
moduleDecoder =
Decode.succeed Module
|> Decode.andMap (Decode.field "name" Decode.string)
|> Decode.andMap (Decode.field "comment" Decode.string |> Decode.andThen (Decode.succeed << fixCodeBlocks))
|> Decode.andMap (Decode.field "aliases" <| Decode.list aliasDecoder)
|> Decode.andMap (Decode.field "types" <| Decode.list unionDecoder)
|> Decode.andMap (Decode.field "values" <| Decode.list valueDecoder)
{-| Fix code blocks
elm-format removes ```elm blocks for syntax coloring so we want to put that back
-}
type alias EditCodeBlockState =
{ inBlock : Bool
, comment : List String
, trailingBlankLineCount : Int
}
fixCodeBlocks : String -> String
fixCodeBlocks comment =
( String.length >> (==) 0
-- , String.startsWith " "
, Regex.contains (Regex.regex "^ [^ ]")
, (==) "†"
, \state -> { state | comment = List.append (List.repeat state.trailingBlankLineCount "") state.comment, trailingBlankLineCount = 0 }
, \state -> { state | inBlock = False, comment = "```\n" :: state.comment }
, String.dropLeft 4
)
|> (\( isBlank, isCode, isEnd, addTrailing, endBlock, unindent ) ->
comment
|> String.split "\n"
|> flip List.append [ "†" ]
|> List.foldl
(\line state ->
isEnd line
? ( state.inBlock
? ( state |> endBlock |> addTrailing
, state
)
, state.inBlock
? ( isBlank line
? ( { state | trailingBlankLineCount = state.trailingBlankLineCount + 1 }
, isCode line
? ( state |> addTrailing |> \state -> { state | comment = unindent line :: state.comment }
, state |> addTrailing |> endBlock |> \state -> { state | comment = line :: state.comment }
)
)
, isCode line
? ( { state | inBlock = True, comment = ("```elm\n" ++ unindent line) :: state.comment, trailingBlankLineCount = 0 }
, { state | comment = line :: state.comment }
)
)
)
)
(EditCodeBlockState False [] 0)
|> .comment
|> List.reverse
|> String.join "\n"
)
-- UTILS
newLine : String
newLine =
" \n"
space : Int -> String
space number =
List.repeat number " "
|> String.join ""
tab : String
tab =
space 4