-
Notifications
You must be signed in to change notification settings - Fork 158
/
BuildCommand.fs
1448 lines (1185 loc) · 59.7 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 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 FSharp.Formatting.Markdown
#nowarn "44" // Obsolete WebClient
/// Convert markdown, script and other content into a static site
type internal DocContent
(
rootOutputFolderAsGiven,
previous: Map<_, _>,
lineNumbers,
fsiEvaluator,
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") || url.StartsWith("https") 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 ext = outputKind.Extension
let outputFileRelativeToRoot =
if isFsx || isMd 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 =
System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures)
|> Array.map (fun x -> x.TwoLetterISOLanguageName)
|> Array.filter (fun x -> x.Length = 2)
|> Array.distinct
let makeMarkdownLinkResolver
(inputFolderAsGiven, outputFolderRelativeToRoot, fullPathFileMap: Map<(string * OutputKind), string>, outputKind)
(markdownReference: string)
=
let markdownReferenceAsFullInputPathOpt =
try
Path.GetFullPath(markdownReference, inputFolderAsGiven) |> 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 {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")
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
=
[ let name = Path.GetFileName(inputFileFullPath)
if name.StartsWith(".") then
printfn "skipping file %s" inputFileFullPath
elif not (name.StartsWith "_template") then
let isFsx = inputFileFullPath.EndsWith(".fsx", true, CultureInfo.InvariantCulture)
let isMd = inputFileFullPath.EndsWith(".md", true, CultureInfo.InvariantCulture)
// 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 ->
try
File.GetLastWriteTime(t)
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 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
)
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
)
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 -> ()))
else if mainRun && watch then
//printfn "skipping unchanged file %s" inputFileFullPath
yield (Some(inputFileFullPath, isOtherLang, haveModel.Value), (fun _ -> ())) ]
let rec processFolder
(htmlTemplate, texTemplate, pynbTemplate, fsxTemplate, mdTemplate, isOtherLang, rootInputFolder, fullPathFileMap)
(inputFolderAsGiven: string)
outputFolderRelativeToRoot
=
[
// 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
))
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Latex
texTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Latex
))
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Pynb
pynbTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Pynb
))
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Fsx
fsxTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Fsx
))
yield!
processFile
rootInputFolder
isOtherLang
input
OutputKind.Markdown
mdTemplate
outputFolderRelativeToRoot
imageSaver
(makeMarkdownLinkResolver (
inputFolderAsGiven,
outputFolderRelativeToRoot,
fullPathFileMap,
OutputKind.Markdown
))
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)) ]
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
[ for (rootInputFolderAsGiven, outputFolderRelativeToRoot) in inputDirectories do
yield!
processFolder
(htmlTemplate, None, None, None, None, false, Some rootInputFolderAsGiven, fullPathFileMap)
rootInputFolderAsGiven
outputFolderRelativeToRoot ]
member _.GetSearchIndexEntries(docModels: (string * bool * LiterateDocModel) list) =
[| for (_inputFile, isOtherLang, model) in docModels do
if not isOtherLang then
match model.IndexText with
| Some text ->
{ title = model.Title
content = text
uri = model.Uri(root) }
| _ -> () |]
member _.GetNavigationEntries(docModels: (string * bool * LiterateDocModel) list) =
let modelsForList =
[ for thing in docModels do
match thing with
| (inputFileFullPath, isOtherLang, model) when
not isOtherLang
&& model.OutputKind = OutputKind.Html
&& not (Path.GetFileNameWithoutExtension(inputFileFullPath) = "index")
->
model
| _ -> () ]
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)
[
// 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)
li [ Class "nav-item" ] [ 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 =
modelsInCategory
|> List.sortBy (fun model ->
match model.Index with
| Some s ->
(try
int32 s
with
| _ -> Int32.MaxValue)
| None -> Int32.MaxValue)
match cat with
| Some c -> li [ Class "nav-header" ] [ !!c ]
| None -> li [ Class "nav-header" ] [ !! "Other" ]
for model in modelsInCategory do
let link = model.Uri(root)
li [ Class "nav-item" ] [ 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 =
//not sure what this was needed for
//let refreshEvent = new Event<_>()
/// 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.onclose = function(evt) { onClose(evt) };
}
function onClose(evt)
{
console.log('closing');
websocket.close();
document.location.reload();
}
window.addEventListener("load", init, false);
</script>
"""
tag.Replace("{{PORT}}", string port)
let signalHotReload = new System.Threading.ManualResetEvent(false)
let socketHandler (webSocket: WebSocket) _ =
socket {
signalHotReload.WaitOne() |> ignore
signalHotReload.Reset() |> ignore
let emptyResponse = [||] |> ByteSegment
printfn "Triggering hot reload on the client"
do! webSocket.send Close emptyResponse true
}
let startWebServer rootOutputFolderAsGiven localPort =
let defaultBinding = defaultConfig.bindings.[0]
let withPort = { defaultBinding.socketBinding with port = uint16 localPort }
let serverConfig =
{ defaultConfig with
bindings = [ { defaultBinding with socketBinding = withPort } ]
homeFolder = Some rootOutputFolderAsGiven }
let app =
choose
[ path "/" >=> Redirection.redirect "/index.html"
path "/websocket" >=> handShake socketHandler
Writers.setHeader "Cache-Control" "no-cache, no-store, must-revalidate"
>=> Writers.setHeader "Pragma" "no-cache"
>=> Writers.setHeader "Expires" "0"
>=> Files.browseHome ]
startWebServerAsync serverConfig app |> snd |> Async.Start
type CoreBuildOptions(watch) =
[<Option("input", Required = false, Default = "docs", HelpText = "Input directory of documentation content.")>]
member val input = "" with get, set
[<Option("projects",
Required = false,
HelpText = "Project files to build API docs for outputs, defaults to all packable projects.")>]
member val projects = Seq.empty<string> with get, set
[<Option("output",
Required = false,
HelpText = "Output Folder (default 'output' for 'build' and 'tmp/watch' for 'watch'.")>]
member val output = "" with get, set
[<Option("noapidocs", Default = false, Required = false, HelpText = "Disable generation of API docs.")>]
member val noapidocs = false with get, set
[<Option("ignoreprojects", Default = false, Required = false, HelpText = "Disable project cracking.")>]
member val ignoreprojects = false with get, set
[<Option("strict", Default = false, Required = false, HelpText = "Fail if there is a problem generating docs.")>]
member val strict = false with get, set
[<Option("eval", Default = false, Required = false, HelpText = "Evaluate F# fragments in scripts.")>]
member val eval = false with get, set
[<Option("qualify",
Default = false,
Required = false,
HelpText = "In API doc generation qualify the output by the collection name, e.g. 'reference/FSharp.Core/...' instead of 'reference/...' .")>]
member val qualify = false with get, set
[<Option("saveimages",
Default = "none",
Required = false,
HelpText = "Save images referenced in docs (some|none|all). If 'some' then image links in formatted results are saved for latex and ipynb output docs.")>]
member val saveImages = "none" with get, set
[<Option("sourcefolder",
Required = false,
HelpText = "Source folder at time of component build (defaults to value of `<FsDocsSourceFolder>` from project file, else current directory)")>]
member val sourceFolder = "" with get, set
[<Option("sourcerepo",
Required = false,
HelpText = "Source repository for github links (defaults to value of `<FsDocsSourceRepository>` from project file, else `<RepositoryUrl>/tree/<RepositoryBranch>` for Git repositories)")>]
member val sourceRepo = "" with get, set
[<Option("linenumbers", Default = false, Required = false, HelpText = "Add line numbers.")>]
member val linenumbers = false with get, set
[<Option("nonpublic",
Default = false,
Required = false,
HelpText = "The tool will also generate documentation for non-public members")>]
member val nonpublic = false with get, set
[<Option("mdcomments",
Default = false,
Required = false,
HelpText = "Assume /// comments in F# code are markdown style (defaults to value of `<UsesMarkdownComments>` from project file)")>]
member val mdcomments = false with get, set
[<Option("parameters",
Required = false,
HelpText = "Additional substitution substitutions for templates, e.g. --parameters key1 value1 key2 value2")>]
member val parameters = Seq.empty<string> with get, set
[<Option("nodefaultcontent",
Required = false,
HelpText = "Do not copy default content styles, javascript or use default templates.")>]
member val nodefaultcontent = false with get, set
[<Option("properties",
Required = false,
HelpText = "Provide properties to dotnet msbuild, e.g. --properties Configuration=Release Version=3.4")>]
member val extraMsbuildProperties = Seq.empty<string> with get, set
[<Option("fscoptions",
Required = false,
HelpText = "Extra flags for F# compiler analysis, e.g. dependency resolution.")>]
member val fscoptions = Seq.empty<string> with get, set
[<Option("clean", Required = false, Default = false, HelpText = "Clean the output directory.")>]
member val clean = false with get, set
member this.Execute() =
let onError msg =
if this.strict then
printfn "%s" msg
exit 1
let protect phase f =
try
f ()
true
with
| ex ->
printfn "Error : \n%O" ex
onError (sprintf "%s failed, and --strict is on : \n%O" phase ex)
false
/// The substitutions as given by the user
let userParameters =
let parameters = Array.ofSeq this.parameters
if parameters.Length % 2 = 1 then
printfn "The --parameters option's arguments' count has to be an even number"
exit 1
evalPairwiseStringsNoOption parameters
|> List.map (fun (a, b) -> (ParamKey a, b))
let userParametersDict = readOnlyDict userParameters
// Adjust the user substitutions for 'watch' mode root
let userRoot, userParameters =
if watch then
let userRoot = sprintf "http://localhost:%d/" this.port_option
if userParametersDict.ContainsKey(ParamKeys.root) then
printfn "ignoring user-specified root since in watch mode, root = %s" userRoot
let userParameters =
[ ParamKeys.root, userRoot ]
@ (userParameters |> List.filter (fun (a, _) -> a <> ParamKeys.root))
Some userRoot, userParameters
else
let r =
match userParametersDict.TryGetValue(ParamKeys.root) with
| true, v -> Some v
| _ -> None
r, userParameters
let userCollectionName =
match (dict userParameters)
.TryGetValue(ParamKeys.``fsdocs-collection-name``)
with
| true, v -> Some v
| _ -> None
// See https://github.com/ionide/proj-info/issues/123
let prevDotnetHostPath = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH")
let (root, collectionName, crackedProjects, paths, docsSubstitutions), _key =
let projects = Seq.toList this.projects
let cacheFile = ".fsdocs/cache"
let getTime p =
try
File.GetLastWriteTimeUtc(p)
with
| _ -> DateTime.Now
let key1 =
(userRoot,
this.parameters,
projects,
getTime (typeof<CoreBuildOptions>.Assembly.Location),
(projects |> List.map getTime |> List.toArray))
Utils.cacheBinary
cacheFile
(fun (_, key2) -> key1 = key2)
(fun () ->
let props =
this.extraMsbuildProperties
|> Seq.toList
|> List.map (fun s ->
let arr = s.Split("=")
if arr.Length > 1 then
arr.[0], String.concat "=" arr.[1..]
else
failwith "properties must be of the form 'PropName=PropValue'")
Crack.crackProjects (
onError,
props,
userRoot,
userCollectionName,
userParameters,
projects,
this.ignoreprojects
),
key1)
// See https://github.com/ionide/proj-info/issues/123
System.Environment.SetEnvironmentVariable("DOTNET_HOST_PATH", prevDotnetHostPath)
if crackedProjects.Length > 0 then
printfn ""
printfn "Inputs for API Docs:"
for (dllFile, _, _, _, _, _, _, _, _, _) in crackedProjects do
printfn " %s" dllFile
//printfn "Comand lines for API Docs:"
//for (_, runArguments, _, _, _, _, _, _, _, _) in crackedProjects do
// printfn " %O" runArguments
for (dllFile, _, _, _, _, _, _, _, _, _) in crackedProjects do
if not (File.Exists dllFile) then
let msg =
sprintf
"*** %s does not exist, has it been built? You may need to provide --properties Configuration=Release."
dllFile
if this.strict then
failwith msg
else
printfn "%s" msg
if crackedProjects.Length > 0 then
printfn ""
printfn "Substitutions/parameters:"
// Print the substitutions
for (ParamKey pk, p) in docsSubstitutions do
printfn " %s --> %s" pk p
// The substitutions may differ for some projects due to different settings in the project files, if so show that
let pd = dict docsSubstitutions
for (dllFile, _, _, _, _, _, _, _, _, projectParameters) in crackedProjects do
for (((ParamKey pkv2) as pk2), p2) in projectParameters do
if pd.ContainsKey pk2 && pd.[pk2] <> p2 then
printfn " (%s) %s --> %s" (Path.GetFileNameWithoutExtension(dllFile)) pkv2 p2
let apiDocInputs =
[ for (dllFile,
_,
repoUrlOption,
repoBranchOption,
repoTypeOption,
projectMarkdownComments,
projectWarn,
projectSourceFolder,
projectSourceRepo,
projectParameters) in crackedProjects ->
let sourceRepo =
match projectSourceRepo with
| Some s -> Some s
| None ->
match evalString this.sourceRepo with
| Some v -> Some v
| None ->
//printfn "repoBranchOption = %A" repoBranchOption
match repoUrlOption, repoBranchOption, repoTypeOption with
| Some url, Some branch, Some "git" when not (String.IsNullOrWhiteSpace branch) ->
url + "/" + "tree/" + branch |> Some
| Some url, _, Some "git" -> url + "/" + "tree/" + "master" |> Some
| Some url, _, None -> Some url
| _ -> None
let sourceFolder =
match projectSourceFolder with
| Some s -> s
| None ->
match evalString this.sourceFolder with
| None -> Environment.CurrentDirectory
| Some v -> v
//printfn "sourceFolder = '%s'" sourceFolder
//printfn "sourceRepo = '%A'" sourceRepo
{ Path = dllFile
XmlFile = None
SourceRepo = sourceRepo
SourceFolder = Some sourceFolder
Substitutions = Some projectParameters
MarkdownComments = this.mdcomments || projectMarkdownComments
Warn = projectWarn
PublicOnly = not this.nonpublic } ]
// Compute the merge of all referenced DLLs across all projects
// so they can be resolved during API doc generation.
//
// TODO: This is inaccurate: the different projects might not be referencing the same DLLs.
// We should do doc generation for each output of each proejct separately
let apiDocOtherFlags =
[ for (_dllFile, otherFlags, _, _, _, _, _, _, _, _) in crackedProjects do
for otherFlag in otherFlags do
if otherFlag.StartsWith("-r:") then
if File.Exists(otherFlag.[3..]) then
yield otherFlag
else
printfn "NOTE: the reference '%s' was not seen on disk, ignoring" otherFlag ]
// TODO: This 'distinctBy' is merging references that may be inconsistent across the project set
|> List.distinctBy (fun ref -> Path.GetFileName(ref.[3..]))
let rootOutputFolderAsGiven =
if this.output = "" then
if watch then "tmp/watch" else "output"
else
this.output
// This is in-package
// From .nuget\packages\fsdocs-tool\7.1.7\tools\net6.0\any
// to .nuget\packages\fsdocs-tool\7.1.7\templates
let dir = Path.GetDirectoryName(typeof<CoreBuildOptions>.Assembly.Location)
let defaultTemplateAttempt1 =
Path.GetFullPath(Path.Combine(dir, "..", "..", "..", "templates", "_template.html"))
// This is in-repo only
let defaultTemplateAttempt2 =
Path.GetFullPath(Path.Combine(dir, "..", "..", "..", "..", "..", "docs", "_template.html"))
let defaultTemplate =
if this.nodefaultcontent then
None
else if (try
File.Exists(defaultTemplateAttempt1)
with
| _ -> false) then
Some defaultTemplateAttempt1
elif (try
File.Exists(defaultTemplateAttempt2)
with
| _ -> false) then
Some defaultTemplateAttempt2
else
None
let extraInputs =
[ if not this.nodefaultcontent then
// The "extras" content goes in "."
// From .nuget\packages\fsdocs-tool\7.1.7\tools\net6.0\any
// to .nuget\packages\fsdocs-tool\7.1.7\extras
let attempt1 = Path.GetFullPath(Path.Combine(dir, "..", "..", "..", "extras"))
if (try
Directory.Exists(attempt1)
with
| _ -> false) then
printfn "using extra content from %s" attempt1
(attempt1, ".")
else
// This is for in-repo use only, assuming we are executing directly from
// src\fsdocs-tool\bin\Debug\net6.0\fsdocs.exe
// src\fsdocs-tool\bin\Release\net6.0\fsdocs.exe
let attempt2 =
Path.GetFullPath(Path.Combine(dir, "..", "..", "..", "..", "..", "docs", "content"))
if (try
Directory.Exists(attempt2)
with