-
Notifications
You must be signed in to change notification settings - Fork 158
/
BuildCommand.fs
2117 lines (1828 loc) · 102 KB
/
BuildCommand.fs
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace fsdocs
open System.Collections.Concurrent
open CommandLine
open System
open System.Diagnostics
open System.IO
open System.Globalization
open System.Net
open System.Reflection
open System.Text
open FSharp.Formatting.Common
open FSharp.Formatting.HtmlModel
open FSharp.Formatting.HtmlModel.Html
open FSharp.Formatting.Literate
open FSharp.Formatting.ApiDocs
open FSharp.Formatting.Literate.Evaluation
open fsdocs.Common
open FSharp.Formatting.Templating
open Suave
open Suave.Sockets
open Suave.Sockets.Control
open Suave.WebSocket
open Suave.Operators
open Suave.Filters
open Suave.Logging
open FSharp.Formatting.Markdown
#nowarn "44" // Obsolete WebClient
/// Convert markdown, script and other content into a static site
type internal DocContent
(
rootOutputFolderAsGiven,
previous: Map<_, _>,
lineNumbers,
evaluate,
substitutions,
saveImages,
watch,
root,
crefResolver,
onError
) =
let createImageSaver (rootOutputFolderAsGiven) =
// Download images so that they can be embedded
let wc = new WebClient()
let mutable counter = 0
fun (url: string) ->
if
url.StartsWith("http", StringComparison.Ordinal)
|| url.StartsWith("https", StringComparison.Ordinal)
then
counter <- counter + 1
let ext = Path.GetExtension(url)
let url2 = sprintf "savedimages/saved%d%s" counter ext
let fn = sprintf "%s/%s" rootOutputFolderAsGiven url2
ensureDirectory (sprintf "%s/savedimages" rootOutputFolderAsGiven)
printfn "downloading %s --> %s" url fn
wc.DownloadFile(url, fn)
url2
else
url
let getOutputFileNames (inputFileFullPath: string) (outputKind: OutputKind) outputFolderRelativeToRoot =
let inputFileName = Path.GetFileName(inputFileFullPath)
let isFsx = inputFileFullPath.EndsWith(".fsx", true, CultureInfo.InvariantCulture)
let isMd = inputFileFullPath.EndsWith(".md", true, CultureInfo.InvariantCulture)
let isPynb = inputFileFullPath.EndsWith(".ipynb", true, CultureInfo.InvariantCulture)
let ext = outputKind.Extension
let outputFileRelativeToRoot =
if isFsx || isMd || isPynb then
let basename = Path.GetFileNameWithoutExtension(inputFileFullPath)
Path.Combine(outputFolderRelativeToRoot, sprintf "%s.%s" basename ext)
else
Path.Combine(outputFolderRelativeToRoot, inputFileName)
let outputFileFullPath = Path.GetFullPath(Path.Combine(rootOutputFolderAsGiven, outputFileRelativeToRoot))
outputFileRelativeToRoot, outputFileFullPath
// Check if a sub-folder is actually the output directory
let subFolderIsOutput subInputFolderFullPath =
let subFolderFullPath = Path.GetFullPath(subInputFolderFullPath)
let rootOutputFolderFullPath = Path.GetFullPath(rootOutputFolderAsGiven)
(subFolderFullPath = rootOutputFolderFullPath)
let allCultures =
CultureInfo.GetCultures(CultureTypes.AllCultures)
|> Array.choose (fun x ->
if x.TwoLetterISOLanguageName.Length <> 2 then
None
else
Some x.TwoLetterISOLanguageName)
|> Array.distinct
let makeMarkdownLinkResolver
(inputFolderAsGiven, outputFolderRelativeToRoot, fullPathFileMap: Map<(string * OutputKind), string>, outputKind)
(markdownReference: string)
=
let markdownReferenceAsFullInputPathOpt =
try
Path.GetFullPath(Path.Combine(inputFolderAsGiven, markdownReference)) |> Some
with _ ->
None
match markdownReferenceAsFullInputPathOpt with
| None -> None
| Some markdownReferenceFullInputPath ->
match fullPathFileMap.TryFind(markdownReferenceFullInputPath, outputKind) with
| None -> None
| Some markdownReferenceFullOutputPath ->
try
let outputFolderFullPath =
Path.GetFullPath(Path.Combine(rootOutputFolderAsGiven, outputFolderRelativeToRoot))
let uri =
Uri(outputFolderFullPath + "/")
.MakeRelativeUri(Uri(markdownReferenceFullOutputPath))
.ToString()
Some uri
with _ ->
printfn
$"Couldn't map markdown reference %s{markdownReference} that seemed to correspond to an input file"
None
/// Prepare the map of input file to output file. This map is used to make substitutions through markdown
/// source such A.md --> A.html or A.fsx --> A.html. The substitutions depend on the output kind.
let prepFile (inputFileFullPath: string) (outputKind: OutputKind) outputFolderRelativeToRoot =
[ let inputFileName = Path.GetFileName(inputFileFullPath)
if
not (inputFileName.StartsWith('.'))
&& not (inputFileName.StartsWith("_template", StringComparison.Ordinal))
then
let inputFileFullPath = Path.GetFullPath(inputFileFullPath)
let _relativeOutputFile, outputFileFullPath =
getOutputFileNames inputFileFullPath outputKind outputFolderRelativeToRoot
yield ((inputFileFullPath, outputKind), outputFileFullPath) ]
/// Likewise prepare the map of input files to output files
let rec prepFolder (inputFolderAsGiven: string) outputFolderRelativeToRoot =
[ let inputs = Directory.GetFiles(inputFolderAsGiven, "*")
for input in inputs do
yield! prepFile input OutputKind.Html outputFolderRelativeToRoot
yield! prepFile input OutputKind.Latex outputFolderRelativeToRoot
yield! prepFile input OutputKind.Pynb outputFolderRelativeToRoot
yield! prepFile input OutputKind.Fsx outputFolderRelativeToRoot
yield! prepFile input OutputKind.Markdown outputFolderRelativeToRoot
for subInputFolderFullPath in Directory.EnumerateDirectories(inputFolderAsGiven) do
let subInputFolderName = Path.GetFileName(subInputFolderFullPath)
let subFolderIsSkipped = subInputFolderName.StartsWith '.'
let subFolderIsOutput = subFolderIsOutput subInputFolderFullPath
if not subFolderIsOutput && not subFolderIsSkipped then
yield!
prepFolder
(Path.Combine(inputFolderAsGiven, subInputFolderName))
(Path.Combine(outputFolderRelativeToRoot, subInputFolderName)) ]
let processFile
rootInputFolder
(isOtherLang: bool)
(inputFileFullPath: string)
outputKind
template
outputFolderRelativeToRoot
imageSaver
mdlinkResolver
(filesWithFrontMatter: FrontMatterFile array)
=
[ let name = Path.GetFileName(inputFileFullPath)
if name.StartsWith('.') then
printfn "skipping file %s" inputFileFullPath
elif not (name.StartsWith("_template", StringComparison.Ordinal)) then
let isFsx = inputFileFullPath.EndsWith(".fsx", StringComparison.OrdinalIgnoreCase)
let isMd = inputFileFullPath.EndsWith(".md", StringComparison.OrdinalIgnoreCase)
let isPynb = inputFileFullPath.EndsWith(".ipynb", StringComparison.OrdinalIgnoreCase)
// A _template.tex or _template.pynb is needed to generate those files
match outputKind, template with
| OutputKind.Pynb, None -> ()
| OutputKind.Latex, None -> ()
| OutputKind.Fsx, None -> ()
| OutputKind.Markdown, None -> ()
| _ ->
let imageSaverOpt =
match outputKind with
| OutputKind.Pynb when saveImages <> Some false -> Some imageSaver
| OutputKind.Latex when saveImages <> Some false -> Some imageSaver
| OutputKind.Fsx when saveImages = Some true -> Some imageSaver
| OutputKind.Html when saveImages = Some true -> Some imageSaver
| OutputKind.Markdown when saveImages = Some true -> Some imageSaver
| _ -> None
let outputFileRelativeToRoot, outputFileFullPath =
getOutputFileNames inputFileFullPath outputKind outputFolderRelativeToRoot
// Update only when needed - template or file or tool has changed
let changed =
let fileChangeTime =
try
File.GetLastWriteTime(inputFileFullPath)
with _ ->
DateTime.MaxValue
let templateChangeTime =
match template with
| Some t when isFsx || isMd || isPynb ->
try
let fi = FileInfo(t)
let input = fi.Directory.Name
let headPath = Path.Combine(input, "_head.html")
let bodyPath = Path.Combine(input, "_body.html")
[ yield File.GetLastWriteTime(t)
if Menu.isTemplatingAvailable input then
yield! Menu.getLastWriteTimes input
if File.Exists headPath then
yield File.GetLastWriteTime headPath
if File.Exists bodyPath then
yield File.GetLastWriteTime bodyPath ]
|> List.max
with _ ->
DateTime.MaxValue
| _ -> DateTime.MinValue
let toolChangeTime =
try
File.GetLastWriteTime(Assembly.GetExecutingAssembly().Location)
with _ ->
DateTime.MaxValue
let changeTime = fileChangeTime |> max templateChangeTime |> max toolChangeTime
let generateTime =
try
File.GetLastWriteTime(outputFileFullPath)
with _ ->
System.DateTime.MinValue
changeTime > generateTime
// If it's changed or we don't know anything about it
// we have to compute the model to get the global substitutions right
let mainRun = (outputKind = OutputKind.Html)
let haveModel = previous.TryFind inputFileFullPath
if changed || (watch && mainRun && haveModel.IsNone) then
if isFsx then
printfn " generating model for %s --> %s" inputFileFullPath outputFileRelativeToRoot
let fsiEvaluator =
(if evaluate then
Some(
FsiEvaluator(onError = onError, options = [| "--multiemit-" |]) :> IFsiEvaluator
)
else
None)
let model =
Literate.ParseAndTransformScriptFile(
inputFileFullPath,
output = outputFileRelativeToRoot,
outputKind = outputKind,
prefix = None,
fscOptions = None,
lineNumbers = lineNumbers,
references = Some false,
fsiEvaluator = fsiEvaluator,
substitutions = substitutions,
generateAnchors = Some true,
imageSaver = imageSaverOpt,
rootInputFolder = rootInputFolder,
crefResolver = crefResolver,
mdlinkResolver = mdlinkResolver,
onError = Some onError,
filesWithFrontMatter = filesWithFrontMatter
)
yield
((if mainRun then
Some(inputFileFullPath, isOtherLang, model)
else
None),
(fun p ->
printfn " writing %s --> %s" inputFileFullPath outputFileRelativeToRoot
ensureDirectory (Path.GetDirectoryName(outputFileFullPath))
SimpleTemplating.UseFileAsSimpleTemplate(
p @ model.Substitutions,
template,
outputFileFullPath
)))
elif isMd then
printfn " preparing %s --> %s" inputFileFullPath outputFileRelativeToRoot
let model =
Literate.ParseAndTransformMarkdownFile(
inputFileFullPath,
output = outputFileRelativeToRoot,
outputKind = outputKind,
prefix = None,
fscOptions = None,
lineNumbers = lineNumbers,
references = Some false,
substitutions = substitutions,
generateAnchors = Some true,
imageSaver = imageSaverOpt,
rootInputFolder = rootInputFolder,
crefResolver = crefResolver,
mdlinkResolver = mdlinkResolver,
parseOptions = MarkdownParseOptions.AllowYamlFrontMatter,
onError = Some onError,
filesWithFrontMatter = filesWithFrontMatter
)
yield
((if mainRun then
Some(inputFileFullPath, isOtherLang, model)
else
None),
(fun p ->
printfn " writing %s --> %s" inputFileFullPath outputFileRelativeToRoot
ensureDirectory (Path.GetDirectoryName(outputFileFullPath))
SimpleTemplating.UseFileAsSimpleTemplate(
p @ model.Substitutions,
template,
outputFileFullPath
)))
elif isPynb then
printfn " preparing %s --> %s" inputFileFullPath outputFileRelativeToRoot
let evaluateNotebook ipynbFile =
let args =
$"repl --run %s{ipynbFile} --default-kernel fsharp --exit-after-run --output-path %s{ipynbFile}"
let psi =
ProcessStartInfo(
fileName = "dotnet",
arguments = args,
UseShellExecute = false,
CreateNoWindow = true
)
try
let p = Process.Start(psi)
p.WaitForExit()
with _ ->
let msg =
$"Failed to evaluate notebook %s{ipynbFile} using dotnet-repl\n"
+ $"""try running "%s{args}" at the command line and inspect the error"""
failwith msg
let checkDotnetReplInstall () =
let failmsg =
"'dotnet-repl' is not installed. Please install it using 'dotnet tool install dotnet-repl'"
try
let psi =
ProcessStartInfo(
fileName = "dotnet",
arguments = "tool list --local",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
)
let p = Process.Start(psi)
let ol = p.StandardOutput.ReadToEnd()
p.WaitForExit()
psi.Arguments <- "tool list --global"
p.Start() |> ignore
let og = p.StandardOutput.ReadToEnd()
let output = $"%s{ol}\n%s{og}"
if not (output.Contains("dotnet-repl")) then
failwith failmsg
p.WaitForExit()
with _ ->
failwith failmsg
if evaluate then
checkDotnetReplInstall ()
printfn $" evaluating %s{inputFileFullPath} with dotnet-repl"
evaluateNotebook inputFileFullPath
let model =
Literate.ParseAndTransformPynbFile(
inputFileFullPath,
output = outputFileRelativeToRoot,
outputKind = outputKind,
prefix = None,
fscOptions = None,
lineNumbers = lineNumbers,
references = Some false,
substitutions = substitutions,
generateAnchors = Some true,
imageSaver = imageSaverOpt,
rootInputFolder = rootInputFolder,
crefResolver = crefResolver,
mdlinkResolver = mdlinkResolver,
onError = Some onError,
filesWithFrontMatter = filesWithFrontMatter
)
yield
((if mainRun then
Some(inputFileFullPath, isOtherLang, model)
else
None),
(fun p ->
printfn " writing %s --> %s" inputFileFullPath outputFileRelativeToRoot
ensureDirectory (Path.GetDirectoryName(outputFileFullPath))
SimpleTemplating.UseFileAsSimpleTemplate(
p @ model.Substitutions,
template,
outputFileFullPath
)))
else if mainRun then
yield
(None,
(fun _p ->
printfn " copying %s --> %s" inputFileFullPath outputFileRelativeToRoot
ensureDirectory (Path.GetDirectoryName(outputFileFullPath))
// check the file still exists for the incremental case
if (File.Exists inputFileFullPath) then
// ignore errors in watch mode
try
File.Copy(inputFileFullPath, outputFileFullPath, true)
File.SetLastWriteTime(outputFileFullPath, DateTime.Now)
with _ when watch ->
()))
//printfn "skipping unchanged file %s" inputFileFullPath
else if mainRun && watch then
match haveModel with
| None -> ()
| Some haveModel -> yield (Some(inputFileFullPath, isOtherLang, haveModel), (fun _ -> ())) ]
let rec processFolder
(htmlTemplate, texTemplate, pynbTemplate, fsxTemplate, mdTemplate, isOtherLang, rootInputFolder, fullPathFileMap)
(inputFolderAsGiven: string)
outputFolderRelativeToRoot
(filesWithFrontMatter: FrontMatterFile array)
=
[
// Look for the presence of the _template.* files to activate the
// generation of the content.
let indirName = Path.GetFileName(inputFolderAsGiven).ToLower()
// Two-letter directory names (e.g. 'ja') with 'docs' count as multi-language and are suppressed from table-of-content
// generation and site search index
let isOtherLang = isOtherLang || (indirName.Length = 2 && allCultures |> Array.contains indirName)
let possibleNewHtmlTemplate = Path.Combine(inputFolderAsGiven, "_template.html")
let htmlTemplate =
if File.Exists(possibleNewHtmlTemplate) then
Some possibleNewHtmlTemplate
else
htmlTemplate
let possibleNewPynbTemplate = Path.Combine(inputFolderAsGiven, "_template.ipynb")
let pynbTemplate =
if File.Exists(possibleNewPynbTemplate) then
Some possibleNewPynbTemplate
else
pynbTemplate
let possibleNewFsxTemplate = Path.Combine(inputFolderAsGiven, "_template.fsx")
let fsxTemplate =
if File.Exists(possibleNewFsxTemplate) then
Some possibleNewFsxTemplate
else
fsxTemplate
let possibleNewMdTemplate = Path.Combine(inputFolderAsGiven, "_template.md")
let mdTemplate =
if File.Exists(possibleNewMdTemplate) then
Some possibleNewMdTemplate
else
mdTemplate
let possibleNewLatexTemplate = Path.Combine(inputFolderAsGiven, "_template.tex")
let texTemplate =
if File.Exists(possibleNewLatexTemplate) then
Some possibleNewLatexTemplate
else
texTemplate
ensureDirectory (Path.Combine(rootOutputFolderAsGiven, outputFolderRelativeToRoot))
let inputs = Directory.GetFiles(inputFolderAsGiven, "*")
let imageSaver = createImageSaver (Path.Combine(rootOutputFolderAsGiven, outputFolderRelativeToRoot))
// Look for the four different kinds of content
for input in inputs do
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Html
htmlTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Html
))
filesWithFrontMatter
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Latex
texTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Latex
))
filesWithFrontMatter
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Pynb
pynbTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Pynb
))
filesWithFrontMatter
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Fsx
fsxTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Fsx
))
filesWithFrontMatter
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Markdown
mdTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Markdown
))
filesWithFrontMatter
for subInputFolderFullPath in Directory.EnumerateDirectories(inputFolderAsGiven) do
let subInputFolderName = Path.GetFileName(subInputFolderFullPath)
let subFolderIsSkipped = subInputFolderName.StartsWith '.'
let subFolderIsOutput = subFolderIsOutput subInputFolderFullPath
if subFolderIsOutput || subFolderIsSkipped then
printfn " skipping directory %s" subInputFolderFullPath
else
yield!
processFolder
(htmlTemplate,
texTemplate,
pynbTemplate,
fsxTemplate,
mdTemplate,
isOtherLang,
rootInputFolder,
fullPathFileMap)
(Path.Combine(inputFolderAsGiven, subInputFolderName))
(Path.Combine(outputFolderRelativeToRoot, subInputFolderName))
filesWithFrontMatter ]
member _.Convert(rootInputFolderAsGiven, htmlTemplate, extraInputs) =
let inputDirectories = extraInputs @ [ (rootInputFolderAsGiven, ".") ]
// Maps full input paths to full output paths
let fullPathFileMap =
[ for (rootInputFolderAsGiven, outputFolderRelativeToRoot) in inputDirectories do
yield! prepFolder rootInputFolderAsGiven outputFolderRelativeToRoot ]
|> Map.ofList
// In order to create {{next-page-url}} and {{previous-page-url}}
// We need to scan all *.fsx and *.md files for their frontmatter.
let filesWithFrontMatter =
fullPathFileMap
|> Map.keys
|> Seq.map fst
|> Seq.distinct
|> Seq.choose (fun fileName ->
let ext = Path.GetExtension fileName
if ext = ".fsx" then
ParseScript.ParseFrontMatter(fileName)
elif ext = ".md" then
File.ReadLines fileName |> FrontMatterFile.ParseFromLines fileName
elif ext = ".ipynb" then
ParsePynb.parseFrontMatter fileName
else
None)
|> Seq.sortBy (fun { Index = idx; CategoryIndex = cIdx } -> cIdx, idx)
|> Seq.toArray
[ for (rootInputFolderAsGiven, outputFolderRelativeToRoot) in inputDirectories do
yield!
processFolder
(htmlTemplate, None, None, None, None, false, Some rootInputFolderAsGiven, fullPathFileMap)
rootInputFolderAsGiven
outputFolderRelativeToRoot
filesWithFrontMatter ]
member _.GetSearchIndexEntries(docModels: (string * bool * LiterateDocModel) list) =
[| for (_inputFile, isOtherLang, model) in docModels do
if not isOtherLang then
match model.IndexText with
| Some(IndexText(fullContent, headings)) ->
{ title = model.Title
content = fullContent
headings = headings
uri = model.Uri(root)
``type`` = "content" }
| _ -> () |]
member _.GetNavigationEntries
(
input,
docModels: (string * bool * LiterateDocModel) list,
currentPagePath: string option
) =
let modelsForList =
[ for thing in docModels do
match thing with
| (inputFileFullPath, isOtherLang, model) when
not isOtherLang
&& model.OutputKind = OutputKind.Html
&& (Path.GetFileNameWithoutExtension(inputFileFullPath) <> "index")
->
{ model with
IsActive =
match currentPagePath with
| None -> false
| Some currentPagePath -> currentPagePath = inputFileFullPath }
| _ -> () ]
let modelsByCategory =
modelsForList
|> List.groupBy (fun (model) -> model.Category)
|> List.sortBy (fun (_, ms) ->
match ms.[0].CategoryIndex with
| Some s ->
(try
int32 s
with _ ->
Int32.MaxValue)
| None -> Int32.MaxValue)
let orderList (list: (LiterateDocModel) list) =
list
|> List.sortBy (fun model -> Option.defaultValue Int32.MaxValue model.Index)
if Menu.isTemplatingAvailable input then
let createGroup (isCategoryActive: bool) (header: string) (items: LiterateDocModel list) : string =
//convert items into menuitem list
let menuItems =
orderList items
|> List.map (fun (model: LiterateDocModel) ->
let link = model.Uri(root)
let title = System.Web.HttpUtility.HtmlEncode model.Title
{ Menu.MenuItem.Link = link
Menu.MenuItem.Content = title
Menu.MenuItem.IsActive = model.IsActive })
Menu.createMenu input isCategoryActive header menuItems
// No categories specified
if modelsByCategory.Length = 1 && (fst modelsByCategory.[0]) = None then
let _, items = modelsByCategory.[0]
createGroup false "Documentation" items
else
modelsByCategory
|> List.map (fun (header, items) ->
let header = Option.defaultValue "Other" header
let isActive = items |> List.exists (fun m -> m.IsActive)
createGroup isActive header items)
|> String.concat "\n"
else
[
// No categories specified
if modelsByCategory.Length = 1 && (fst modelsByCategory.[0]) = None then
li [ Class "nav-header" ] [ !! "Documentation" ]
for model in snd modelsByCategory.[0] do
let link = model.Uri(root)
let activeClass = if model.IsActive then "active" else ""
li
[ Class $"nav-item %s{activeClass}" ]
[ a [ Class "nav-link"; (Href link) ] [ encode model.Title ] ]
else
// At least one category has been specified. Sort each category by index and emit
// Use 'Other' as a header for uncategorised things
for (cat, modelsInCategory) in modelsByCategory do
let modelsInCategory = orderList modelsInCategory
let categoryActiveClass =
if modelsInCategory |> List.exists (fun m -> m.IsActive) then
"active"
else
""
match cat with
| Some c -> li [ Class $"nav-header %s{categoryActiveClass}" ] [ !!c ]
| None -> li [ Class $"nav-header %s{categoryActiveClass}" ] [ !! "Other" ]
for model in modelsInCategory do
let link = model.Uri(root)
let activeClass = if model.IsActive then "active" else ""
li
[ Class $"nav-item %s{activeClass}" ]
[ a [ Class "nav-link"; (Href link) ] [ encode model.Title ] ] ]
|> List.map (fun html -> html.ToString())
|> String.concat " \n"
/// Processes and runs Suave server to host them on localhost
module Serve =
let refreshEvent = FSharp.Control.Event<string>()
/// generate the script to inject into html to enable hot reload during development
let generateWatchScript (port: int) =
let tag =
"""
<script type="text/javascript">
var wsUri = "ws://localhost:{{PORT}}/websocket";
function init()
{
websocket = new WebSocket(wsUri);
websocket.onmessage = function(evt) {
const data = evt.data;
if (data.endsWith(".css")) {
console.log(`Trying to reload ${data}`);
const link = document.querySelector(`link[href*='${data}']`);
if (link) {
const href = new URL(link.href);
const ticks = new Date().getTime();
href.searchParams.set("v", ticks);
link.href = href.toString();
}
}
else {
console.log('closing');
websocket.close();
document.location.reload();
}
}
}
window.addEventListener("load", init, false);
</script>
"""
tag.Replace("{{PORT}}", string<int> port)
let connectedClients = ConcurrentDictionary<WebSocket, unit>()
let socketHandler (webSocket: WebSocket) (context: HttpContext) =
context.runtime.logger.info (Message.eventX "New websocket connection")
connectedClients.TryAdd(webSocket, ()) |> ignore
socket {
let! msg = webSocket.read ()
match msg with
| Close, _, _ ->
context.runtime.logger.info (Message.eventX "Closing connection")
connectedClients.TryRemove webSocket |> ignore
let emptyResponse = [||] |> ByteSegment
do! webSocket.send Close emptyResponse true
| _ -> ()
}
let broadCastReload (msg: string) =
let msg = msg |> Encoding.UTF8.GetBytes |> ByteSegment
connectedClients.Keys
|> Seq.map (fun client ->
async {
let! _ = client.send Text msg true
()
})
|> Async.Parallel
|> Async.Ignore
|> Async.RunSynchronously
refreshEvent.Publish
|> Event.add (fun fileName ->
if Path.HasExtension fileName then
let fileName = fileName.Replace("\\", "/").TrimEnd('~')
broadCastReload fileName)
let startWebServer rootOutputFolderAsGiven localPort =
let mimeTypesMap ext =
match ext with
| ".323" -> Writers.createMimeType "text/h323" false
| ".3g2" -> Writers.createMimeType "video/3gpp2" false
| ".3gp2" -> Writers.createMimeType "video/3gpp2" false
| ".3gp" -> Writers.createMimeType "video/3gpp" false
| ".3gpp" -> Writers.createMimeType "video/3gpp" false
| ".aac" -> Writers.createMimeType "audio/aac" false
| ".aaf" -> Writers.createMimeType "application/octet-stream" false
| ".aca" -> Writers.createMimeType "application/octet-stream" false
| ".accdb" -> Writers.createMimeType "application/msaccess" false
| ".accde" -> Writers.createMimeType "application/msaccess" false
| ".accdt" -> Writers.createMimeType "application/msaccess" false
| ".acx" -> Writers.createMimeType "application/internet-property-stream" false
| ".adt" -> Writers.createMimeType "audio/vnd.dlna.adts" false
| ".adts" -> Writers.createMimeType "audio/vnd.dlna.adts" false
| ".afm" -> Writers.createMimeType "application/octet-stream" false
| ".ai" -> Writers.createMimeType "application/postscript" false
| ".aif" -> Writers.createMimeType "audio/x-aiff" false
| ".aifc" -> Writers.createMimeType "audio/aiff" false
| ".aiff" -> Writers.createMimeType "audio/aiff" false
| ".appcache" -> Writers.createMimeType "text/cache-manifest" false
| ".application" -> Writers.createMimeType "application/x-ms-application" false
| ".art" -> Writers.createMimeType "image/x-jg" false
| ".asd" -> Writers.createMimeType "application/octet-stream" false
| ".asf" -> Writers.createMimeType "video/x-ms-asf" false
| ".asi" -> Writers.createMimeType "application/octet-stream" false
| ".asm" -> Writers.createMimeType "text/plain" false
| ".asr" -> Writers.createMimeType "video/x-ms-asf" false
| ".asx" -> Writers.createMimeType "video/x-ms-asf" false
| ".atom" -> Writers.createMimeType "application/atom+xml" false
| ".au" -> Writers.createMimeType "audio/basic" false
| ".avi" -> Writers.createMimeType "video/x-msvideo" false
| ".axs" -> Writers.createMimeType "application/olescript" false
| ".bas" -> Writers.createMimeType "text/plain" false
| ".bcpio" -> Writers.createMimeType "application/x-bcpio" false
| ".bin" -> Writers.createMimeType "application/octet-stream" false
| ".bmp" -> Writers.createMimeType "image/bmp" false
| ".c" -> Writers.createMimeType "text/plain" false
| ".cab" -> Writers.createMimeType "application/vnd.ms-cab-compressed" false
| ".calx" -> Writers.createMimeType "application/vnd.ms-office.calx" false
| ".cat" -> Writers.createMimeType "application/vnd.ms-pki.seccat" false
| ".cdf" -> Writers.createMimeType "application/x-cdf" false
| ".chm" -> Writers.createMimeType "application/octet-stream" false
| ".class" -> Writers.createMimeType "application/x-java-applet" false
| ".clp" -> Writers.createMimeType "application/x-msclip" false
| ".cmx" -> Writers.createMimeType "image/x-cmx" false
| ".cnf" -> Writers.createMimeType "text/plain" false
| ".cod" -> Writers.createMimeType "image/cis-cod" false
| ".cpio" -> Writers.createMimeType "application/x-cpio" false
| ".cpp" -> Writers.createMimeType "text/plain" false
| ".crd" -> Writers.createMimeType "application/x-mscardfile" false
| ".crl" -> Writers.createMimeType "application/pkix-crl" false
| ".crt" -> Writers.createMimeType "application/x-x509-ca-cert" false
| ".csh" -> Writers.createMimeType "application/x-csh" false
| ".css" -> Writers.createMimeType "text/css" false
| ".csv" -> Writers.createMimeType "text/csv" false
| ".cur" -> Writers.createMimeType "application/octet-stream" false
| ".dcr" -> Writers.createMimeType "application/x-director" false
| ".deploy" -> Writers.createMimeType "application/octet-stream" false
| ".der" -> Writers.createMimeType "application/x-x509-ca-cert" false
| ".dib" -> Writers.createMimeType "image/bmp" false
| ".dir" -> Writers.createMimeType "application/x-director" false
| ".disco" -> Writers.createMimeType "text/xml" false
| ".dlm" -> Writers.createMimeType "text/dlm" false
| ".doc" -> Writers.createMimeType "application/msword" false
| ".docm" -> Writers.createMimeType "application/vnd.ms-word.document.macroEnabled.12" false
| ".docx" ->
Writers.createMimeType "application/vnd.openxmlformats-officedocument.wordprocessingml.document" false
| ".dot" -> Writers.createMimeType "application/msword" false
| ".dotm" -> Writers.createMimeType "application/vnd.ms-word.template.macroEnabled.12" false
| ".dotx" ->
Writers.createMimeType "application/vnd.openxmlformats-officedocument.wordprocessingml.template" false
| ".dsp" -> Writers.createMimeType "application/octet-stream" false
| ".dtd" -> Writers.createMimeType "text/xml" false
| ".dvi" -> Writers.createMimeType "application/x-dvi" false
| ".dvr-ms" -> Writers.createMimeType "video/x-ms-dvr" false
| ".dwf" -> Writers.createMimeType "drawing/x-dwf" false
| ".dwp" -> Writers.createMimeType "application/octet-stream" false
| ".dxr" -> Writers.createMimeType "application/x-director" false
| ".eml" -> Writers.createMimeType "message/rfc822" false
| ".emz" -> Writers.createMimeType "application/octet-stream" false
| ".eot" -> Writers.createMimeType "application/vnd.ms-fontobject" false
| ".eps" -> Writers.createMimeType "application/postscript" false
| ".etx" -> Writers.createMimeType "text/x-setext" false
| ".evy" -> Writers.createMimeType "application/envoy" false
| ".exe" -> Writers.createMimeType "application/vnd.microsoft.portable-executable" false
| ".fdf" -> Writers.createMimeType "application/vnd.fdf" false
| ".fif" -> Writers.createMimeType "application/fractals" false
| ".fla" -> Writers.createMimeType "application/octet-stream" false
| ".flr" -> Writers.createMimeType "x-world/x-vrml" false
| ".flv" -> Writers.createMimeType "video/x-flv" false
| ".gif" -> Writers.createMimeType "image/gif" false
| ".gtar" -> Writers.createMimeType "application/x-gtar" false
| ".gz" -> Writers.createMimeType "application/x-gzip" false
| ".h" -> Writers.createMimeType "text/plain" false
| ".hdf" -> Writers.createMimeType "application/x-hdf" false
| ".hdml" -> Writers.createMimeType "text/x-hdml" false
| ".hhc" -> Writers.createMimeType "application/x-oleobject" false
| ".hhk" -> Writers.createMimeType "application/octet-stream" false
| ".hhp" -> Writers.createMimeType "application/octet-stream" false
| ".hlp" -> Writers.createMimeType "application/winhlp" false
| ".hqx" -> Writers.createMimeType "application/mac-binhex40" false
| ".hta" -> Writers.createMimeType "application/hta" false
| ".htc" -> Writers.createMimeType "text/x-component" false
| ".htm" -> Writers.createMimeType "text/html" false
| ".html" -> Writers.createMimeType "text/html" false
| ".htt" -> Writers.createMimeType "text/webviewhtml" false
| ".hxt" -> Writers.createMimeType "text/html" false
| ".ical" -> Writers.createMimeType "text/calendar" false
| ".icalendar" -> Writers.createMimeType "text/calendar" false
| ".ico" -> Writers.createMimeType "image/x-icon" false
| ".ics" -> Writers.createMimeType "text/calendar" false
| ".ief" -> Writers.createMimeType "image/ief" false
| ".ifb" -> Writers.createMimeType "text/calendar" false
| ".iii" -> Writers.createMimeType "application/x-iphone" false
| ".inf" -> Writers.createMimeType "application/octet-stream" false
| ".ins" -> Writers.createMimeType "application/x-internet-signup" false
| ".isp" -> Writers.createMimeType "application/x-internet-signup" false
| ".IVF" -> Writers.createMimeType "video/x-ivf" false
| ".jar" -> Writers.createMimeType "application/java-archive" false
| ".java" -> Writers.createMimeType "application/octet-stream" false
| ".jck" -> Writers.createMimeType "application/liquidmotion" false
| ".jcz" -> Writers.createMimeType "application/liquidmotion" false
| ".jfif" -> Writers.createMimeType "image/pjpeg" false
| ".jpb" -> Writers.createMimeType "application/octet-stream" false
| ".jpe" -> Writers.createMimeType "image/jpeg" false
| ".jpeg" -> Writers.createMimeType "image/jpeg" false
| ".jpg" -> Writers.createMimeType "image/jpeg" false
| ".js" -> Writers.createMimeType "text/javascript" false
| ".json" -> Writers.createMimeType "application/json" false
| ".jsx" -> Writers.createMimeType "text/jscript" false
| ".latex" -> Writers.createMimeType "application/x-latex" false
| ".lit" -> Writers.createMimeType "application/x-ms-reader" false
| ".lpk" -> Writers.createMimeType "application/octet-stream" false