-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathProjectCracker.fs
More file actions
790 lines (683 loc) · 35.7 KB
/
ProjectCracker.fs
File metadata and controls
790 lines (683 loc) · 35.7 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
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
namespace fsdocs
open System
open System.Diagnostics
open System.IO
open System.Runtime.InteropServices
open System.Runtime.Serialization
open System.Xml
open System.Xml.Linq
open FSharp.Formatting.Templating
open Ionide.ProjInfo
open Ionide.ProjInfo.Types
[<AutoOpen>]
/// General utility helpers shared across the fsdocs tool.
module Utils =
/// <c>true</c> when the current OS is Windows.
let isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
/// The name of the dotnet host executable for the current OS.
let dotnet = if isWindows then "dotnet.exe" else "dotnet"
/// Returns <c>true</c> when a file exists at the given path, silently returning <c>false</c> on error.
let fileExists pathToFile =
try
File.Exists(pathToFile)
with _ ->
false
// Look for global install of dotnet sdk
/// Looks for a globally installed dotnet SDK host at the standard Program Files location.
let getDotnetGlobalHostPath () =
let pf = Environment.GetEnvironmentVariable("ProgramW6432")
let pf =
if String.IsNullOrEmpty(pf) then
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
else
pf
let candidate = Path.Combine(pf, "dotnet", dotnet)
if fileExists candidate then
Some candidate
else
// Can't find it --- give up
None
// from dotnet/fsharp
/// Probes for the dotnet host executable, trying (in order) the <c>DOTNET_HOST_PATH</c>
/// environment variable, the SDK install location relative to the current assembly,
/// and finally the PATH.
let getDotnetHostPath () =
// How to find dotnet.exe --- woe is me; probing rules make me sad.
// Algorithm:
// 1. Look for DOTNET_HOST_PATH environment variable
// this is the main user programable override .. provided by user to find a specific dotnet.exe
// 2. Probe for are we part of an .NetSDK install
// In an sdk install we are always installed in: sdk\3.0.100-rc2-014234\FSharp
// dotnet or dotnet.exe will be found in the directory that contains the sdk directory
// 3. We are loaded in-process to some other application ... Eg. try .net
// See if the host is dotnet.exe ... from net5.0 on this is fairly unlikely
// 4. If it's none of the above we are going to have to rely on the path containing the way to find dotnet.exe
// Use the path to search for dotnet.exe
let probePathForDotnetHost () =
let paths =
let p = Environment.GetEnvironmentVariable("PATH")
if not (isNull p) then p.Split(Path.PathSeparator) else [||]
paths |> Array.tryFind (fun f -> fileExists (Path.Combine(f, dotnet)))
match (Environment.GetEnvironmentVariable("DOTNET_HOST_PATH")) with
// Value set externally
| value when not (String.IsNullOrEmpty(value)) && fileExists value -> Some value
| _ ->
// Probe for netsdk install, dotnet. and dotnet.exe is a constant offset from the location of System.Int32
let candidate =
let assemblyLocation = Path.GetDirectoryName(typeof<Int32>.Assembly.Location)
Path.GetFullPath(Path.Combine(assemblyLocation, "..", "..", "..", dotnet))
if fileExists candidate then
Some candidate
else
match probePathForDotnetHost () with
| Some f -> Some(Path.Combine(f, dotnet))
| None -> getDotnetGlobalHostPath ()
/// Creates the directory at <c>path</c> if it does not already exist.
let ensureDirectory path =
let dir = DirectoryInfo(path)
if not dir.Exists then
dir.Create()
/// Serialises <c>object</c> to <c>fileName</c> using <see cref="DataContractSerializer"/> binary XML format.
let saveBinary (object: 'T) (fileName: string) =
try
Directory.CreateDirectory(Path.GetDirectoryName(fileName)) |> ignore
with _ ->
()
let formatter = DataContractSerializer(typeof<'T>)
use fs = File.Create(fileName)
use xw = XmlDictionaryWriter.CreateBinaryWriter(fs)
formatter.WriteObject(xw, object)
fs.Flush()
/// Deserialises a value from <c>fileName</c> using <see cref="DataContractSerializer"/> binary XML format,
/// returning <c>None</c> on any error.
let loadBinary<'T> (fileName: string) : 'T option =
let formatter = DataContractSerializer(typeof<'T>)
use fs = File.OpenRead(fileName)
use xw = XmlDictionaryReader.CreateBinaryReader(fs, XmlDictionaryReaderQuotas.Max)
try
let object = formatter.ReadObject(xw) :?> 'T
Some object
with _ ->
None
/// Attempts to restore a previously cached value from <c>cacheFile</c>. If the cache
/// is absent or invalid (as judged by <c>cacheValid</c>), calls <c>f</c> to compute
/// a fresh value and saves it to the cache.
let cacheBinary cacheFile cacheValid (f: unit -> 'T) : 'T =
let attempt =
if File.Exists(cacheFile) then
let v = loadBinary cacheFile
match v with
| Some v ->
if cacheValid v then
printfn "restored project state from '%s'" cacheFile
Some v
else
printfn "discarding project state in '%s' as now invalid" cacheFile
None
| None -> None
else
None
match attempt with
| Some r -> r
| None ->
let res = f ()
saveBinary res cacheFile
res
/// Appends a trailing <c>/</c> to a URL or path string if it does not already end with
/// <c>/</c> or <c>.html</c>.
let ensureTrailingSlash (s: string) =
if s.EndsWith '/' || s.EndsWith(".html", StringComparison.Ordinal) then
s
else
s + "/"
/// Thin wrappers around dotnet CLI commands used during project cracking.
module DotNetCli =
/// Run `dotnet msbuild <args>` and receive the trimmed standard output.
let msbuild (pwd: string) (args: string) : string =
let psi = ProcessStartInfo "dotnet"
psi.WorkingDirectory <- pwd
psi.Arguments <- $"msbuild %s{args}"
psi.RedirectStandardOutput <- true
psi.UseShellExecute <- false
use ps = new Process()
ps.StartInfo <- psi
ps.Start() |> ignore
let output = ps.StandardOutput.ReadToEnd()
ps.WaitForExit()
output.Trim()
/// Project-cracking logic: uses Ionide.ProjInfo to load MSBuild project options
/// and extract the fsdocs-specific MSBuild properties.
module Crack =
[<return: Struct>]
let (|ConditionEquals|_|) (str: string) (arg: string) =
if System.String.Compare(str, arg, System.StringComparison.OrdinalIgnoreCase) = 0 then
ValueSome()
else
ValueNone
/// Parses a trimmed MSBuild property string as an optional boolean
/// (<c>None</c> for whitespace-only values, <c>Some true</c> for "True").
let msbuildPropBool (s: string) =
let trimmed = s.Trim()
if String.IsNullOrWhiteSpace trimmed then
None
else
match trimmed with
| ConditionEquals "True" -> Some true
| _ -> Some false
/// Runs an external process, routing stdout and stderr lines to <c>log</c>,
/// and returns the exit code together with the process arguments for diagnostics.
let runProcess (log: string -> unit) (workingDir: string) (exePath: string) (args: string) =
let psi = System.Diagnostics.ProcessStartInfo()
psi.FileName <- exePath
psi.WorkingDirectory <- workingDir
psi.RedirectStandardOutput <- true
psi.RedirectStandardError <- true
psi.Arguments <- args
psi.CreateNoWindow <- true
psi.UseShellExecute <- false
use p = new System.Diagnostics.Process()
p.StartInfo <- psi
p.OutputDataReceived.Add(fun ea -> log (ea.Data))
p.ErrorDataReceived.Add(fun ea -> log (ea.Data))
// printfn "running: %s %s" psi.FileName psi.Arguments
p.Start() |> ignore
p.BeginOutputReadLine()
p.BeginErrorReadLine()
p.WaitForExit()
let exitCode = p.ExitCode
exitCode, (workingDir, exePath, args)
type private CrackErrors = GetProjectOptionsErrors of error: string * messages: string list
/// All fsdocs-relevant MSBuild properties and Ionide project options for a single project,
/// obtained after cracking the project file.
type CrackedProjectInfo =
{ ProjectFileName: string
ProjectOptions: ProjectOptions option
TargetPath: string option
IsTestProject: bool
IsLibrary: bool
IsPackable: bool
RepositoryUrl: string option
RepositoryType: string option
RepositoryBranch: string option
UsesMarkdownComments: bool
FsDocsLicenseLink: string option
FsDocsLogoLink: string option
FsDocsLogoSource: string option
FsDocsLogoAlt: string option
FsDocsReleaseNotesLink: string option
FsDocsSourceFolder: string option
FsDocsSourceRepository: string option
FsDocsFaviconSource: string option
FsDocsTheme: string option
FsDocsWarnOnMissingDocs: bool
FsDocsGenerateLlmsTxt: bool
FsDocsAllowExecutableProject: bool
FsDocsNoInheritedMembers: bool
FsDocsTypeConstraints: FSharp.Formatting.ApiDocs.TypeConstraintDisplayMode
PackageProjectUrl: string option
Authors: string option
GenerateDocumentationFile: bool
//Removed because this is typically a multi-line string and dotnet-proj-info can't handle this
//Description : string option
PackageLicenseExpression: string option
PackageTags: string option
Copyright: string option
PackageVersion: string option
PackageIconUrl: string option
//Removed because this is typically a multi-line string and dotnet-proj-info can't handle this
//PackageReleaseNotes : string option
RepositoryCommit: string option }
/// Uses Ionide.ProjInfo to load the MSBuild project options and custom fsdocs properties
/// for a single project file, returning the target-framework list alongside the cracked info.
let private crackProjectFileAndIncludeTargetFrameworks _slnDir extraMsbuildProperties (projectFile: string) =
let additionalInfo =
[ "OutputType"
"IsTestProject"
"IsPackable"
"RepositoryUrl"
"UsesMarkdownComments"
"FsDocsCollectionNameLink"
"FsDocsLogoSource"
"FsDocsLogoAlt"
"FsDocsFaviconSource"
"FsDocsTheme"
"FsDocsLogoLink"
"FsDocsLicenseLink"
"FsDocsReleaseNotesLink"
"FsDocsSourceFolder"
"FsDocsSourceRepository"
"FsDocsWarnOnMissingDocs"
"FsDocsGenerateLlmsTxt"
"FsDocsAllowExecutableProject"
"FsDocsNoInheritedMembers"
"FsDocsTypeConstraints"
"RepositoryType"
"RepositoryBranch"
"PackageProjectUrl"
"Authors"
"GenerateDocumentationFile"
//Removed because this is typically a multi-line string and dotnet-proj-info can't handle this
//"Description"
"PackageLicenseExpression"
"PackageTags"
"Copyright"
"PackageVersion"
"PackageIconUrl"
//Removed because this is typically a multi-line string and dotnet-proj-info can't handle this
//"PackageReleaseNotes"
"RepositoryCommit"
"TargetFrameworks"
"RunArguments" ]
let customProperties = ("TargetPath" :: additionalInfo)
let loggedMessages = System.Collections.Concurrent.ConcurrentQueue<string>()
let result =
let cwd = System.Environment.CurrentDirectory |> System.IO.DirectoryInfo
let dotnetExe = getDotnetHostPath () |> Option.map System.IO.FileInfo
let toolsPath = Init.init cwd dotnetExe
let loader = WorkspaceLoader.Create(toolsPath, extraMsbuildProperties)
use _ =
loader.Notifications.Subscribe(fun msg ->
match msg with
| WorkspaceProjectState.Failed(_, err) -> loggedMessages.Enqueue(err.ToString())
| _ -> ())
let projects =
loader.LoadProjects([ projectFile ], customProperties, BinaryLogGeneration.Off)
|> Seq.toList
match projects with
| projOptions :: _ -> Ok(Some projOptions)
| [] ->
let msgs = loggedMessages.ToArray() |> Array.toList
let detail = msgs |> List.tryHead |> Option.defaultWith (fun () -> "not a standard project")
printfn $" skipping project '%s{Path.GetFileName projectFile}': %s{detail}"
Ok None
let msgs = (loggedMessages.ToArray() |> Array.toList)
match result with
| Ok None -> Ok None
| Ok(Some projOptions) ->
let props =
projOptions.CustomProperties
|> List.map (fun p -> p.Name, p.Value)
|> Map.ofList
//printfn "props = %A" (Map.toList props)
let msbuildPropString prop =
props
|> Map.tryFind prop
|> Option.bind (function
| s when String.IsNullOrWhiteSpace(s) -> None
| s -> Some s)
let splitTargetFrameworks =
function
| Some(s: string) ->
s.Split(";", StringSplitOptions.RemoveEmptyEntries)
|> Array.map (fun s' -> s'.Trim())
|> Some
| _ -> None
let targetFrameworks = msbuildPropString "TargetFrameworks" |> splitTargetFrameworks
let msbuildPropBool prop =
prop |> msbuildPropString |> Option.bind msbuildPropBool
let projOptions2 =
{ ProjectFileName = projectFile
ProjectOptions = Some projOptions
TargetPath = msbuildPropString "TargetPath"
IsTestProject = msbuildPropBool "IsTestProject" |> Option.defaultValue false
IsLibrary =
msbuildPropString "OutputType"
|> Option.map (fun s -> s.ToLowerInvariant())
|> ((=) (Some "library"))
IsPackable = msbuildPropBool "IsPackable" |> Option.defaultValue false
RepositoryUrl = msbuildPropString "RepositoryUrl"
RepositoryType = msbuildPropString "RepositoryType"
RepositoryBranch = msbuildPropString "RepositoryBranch"
FsDocsSourceFolder = msbuildPropString "FsDocsSourceFolder"
FsDocsSourceRepository = msbuildPropString "FsDocsSourceRepository"
FsDocsLicenseLink = msbuildPropString "FsDocsLicenseLink"
FsDocsReleaseNotesLink = msbuildPropString "FsDocsReleaseNotesLink"
FsDocsLogoLink = msbuildPropString "FsDocsLogoLink"
FsDocsLogoSource = msbuildPropString "FsDocsLogoSource"
FsDocsLogoAlt = msbuildPropString "FsDocsLogoAlt"
FsDocsFaviconSource = msbuildPropString "FsDocsFaviconSource"
FsDocsTheme = msbuildPropString "FsDocsTheme"
FsDocsWarnOnMissingDocs = msbuildPropBool "FsDocsWarnOnMissingDocs" |> Option.defaultValue false
FsDocsGenerateLlmsTxt = msbuildPropBool "FsDocsGenerateLlmsTxt" |> Option.defaultValue true
FsDocsAllowExecutableProject =
msbuildPropBool "FsDocsAllowExecutableProject" |> Option.defaultValue false
FsDocsNoInheritedMembers = msbuildPropBool "FsDocsNoInheritedMembers" |> Option.defaultValue false
FsDocsTypeConstraints =
msbuildPropString "FsDocsTypeConstraints"
|> Option.bind (fun s ->
match s.Trim() with
| "None" -> Some FSharp.Formatting.ApiDocs.TypeConstraintDisplayMode.None
| "Short" -> Some FSharp.Formatting.ApiDocs.TypeConstraintDisplayMode.Short
| "Full" -> Some FSharp.Formatting.ApiDocs.TypeConstraintDisplayMode.Full
| _ -> None)
|> Option.defaultValue FSharp.Formatting.ApiDocs.TypeConstraintDisplayMode.Short
UsesMarkdownComments = msbuildPropBool "UsesMarkdownComments" |> Option.defaultValue false
PackageProjectUrl = msbuildPropString "PackageProjectUrl"
Authors = msbuildPropString "Authors"
GenerateDocumentationFile = msbuildPropBool "GenerateDocumentationFile" |> Option.defaultValue false
PackageLicenseExpression = msbuildPropString "PackageLicenseExpression"
PackageTags = msbuildPropString "PackageTags"
Copyright = msbuildPropString "Copyright"
PackageVersion = msbuildPropString "PackageVersion"
PackageIconUrl = msbuildPropString "PackageIconUrl"
RepositoryCommit = msbuildPropString "RepositoryCommit" }
Ok(Some(targetFrameworks, projOptions2))
| Error err -> GetProjectOptionsErrors(err, msgs) |> Result.Error
/// Checks whether the project has been restored (i.e. the assets file exists) and
/// calls <c>dotnet restore</c> if not.
let private ensureProjectWasRestored (file: string) =
let projDir = Path.GetDirectoryName(file)
let projectAssetsJsonPath = Path.Combine(projDir, "obj", "project.assets.json")
if File.Exists projectAssetsJsonPath then
()
else
// In dotnet 8 <UseArtifactsOutput> was introduced, see https://learn.microsoft.com/en-us/dotnet/core/sdk/artifacts-output
// We will try and use CLI-based project evaluation to determine the location of project.assets.json file.
// See https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-8#cli-based-project-evaluation
// Some projects (e.g. those with nonstandard artifact output locations) may not put project.assets.json
// under <projDir>/obj/. If we can detect the actual path via MSBuild, we use that; otherwise we warn
// and proceed so that the cracking step itself can produce the definitive error.
let detectedPath =
try
let path = DotNetCli.msbuild projDir "--getProperty:ProjectAssetsFile"
Some path
with _ ->
None
match detectedPath with
| Some path when File.Exists path -> ()
| Some _ ->
// MSBuild reported a path but the file doesn't exist there — project is definitely not restored.
failwithf $"project '%s{file}' not restored"
| None ->
// Could not determine the assets file location (e.g. old SDK without --getProperty support,
// or nonstandard project layout). Warn and continue; if the project truly isn't restored the
// subsequent cracking step will fail with a more specific error.
printfn $"Warning: could not verify that project '%s{file}' was restored. Proceeding anyway."
/// Cracks a single F# project file, selecting the appropriate target framework when
/// the project multi-targets, and returns the full <see cref="CrackedProjectInfo"/> or
/// <c>None</c> when the project cannot be loaded.
let crackProjectFile slnDir extraMsbuildProperties (file: string) : CrackedProjectInfo option =
ensureProjectWasRestored file
let result = crackProjectFileAndIncludeTargetFrameworks slnDir extraMsbuildProperties file
//printfn "msgs = %A" msgs
match result with
| Ok None -> None
| Ok(Some(Some targetFrameworks, crackedProjectInfo)) when
crackedProjectInfo.TargetPath.IsNone && targetFrameworks.Length > 1
->
// no targetpath and there are multiple target frameworks
// let us retry with first target framework specified:
let extraMsbuildPropertiesAndFirstTargetFramework =
List.append extraMsbuildProperties [ ("TargetFramework", targetFrameworks.[0]) ]
let result2 =
crackProjectFileAndIncludeTargetFrameworks slnDir extraMsbuildPropertiesAndFirstTargetFramework file
match result2 with
| Ok None -> None
| Ok(Some(_, crackedProjectInfo)) -> Some crackedProjectInfo
| Error(GetProjectOptionsErrors(err, msgs)) ->
failwithf "error - %s\nlog - %s" (err.ToString()) (String.concat "\n" msgs)
| Ok(Some(_, crackedProjectInfo)) -> Some crackedProjectInfo
| Error(GetProjectOptionsErrors(err, msgs)) ->
failwithf "error - %s\nlog - %s" (err.ToString()) (String.concat "\n" msgs)
/// Parses a Visual Studio solution file and returns the ordered list of project file paths.
let getProjectsFromSlnFile (slnPath: string) =
match InspectSln.tryParseSln slnPath with
| Ok slnData -> InspectSln.loadingBuildOrder slnData
//this.LoadProjects(projs, crosstargetingStrategy, useBinaryLogger, numberOfThreads)
| Error e -> raise (exn ("cannot load the sln", e))
/// Discovers project files (from solutions, directories, or explicit lists),
/// cracks each one, and returns the collection name, collection URL, and per-project info.
let crackProjects
(onError, extraMsbuildProperties, userRoot, userCollectionName, userParameters, projects, ignoreProjects)
=
let slnDir = Path.GetFullPath "."
//printfn "x.projects = %A" x.projects
let collectionName, projectFiles =
match projects, ignoreProjects with
| [], false ->
match Directory.GetFiles(slnDir, "*.sln") with
| [| sln |] ->
printfn "getting projects from solution file %s" sln
let collectionName = defaultArg userCollectionName (Path.GetFileNameWithoutExtension(sln))
collectionName, getProjectsFromSlnFile sln
| _ ->
let projectFiles =
[ yield! Directory.EnumerateFiles(slnDir, "*.fsproj")
for d in Directory.EnumerateDirectories(slnDir) do
yield! Directory.EnumerateFiles(d, "*.fsproj")
for d2 in Directory.EnumerateDirectories(d) do
yield! Directory.EnumerateFiles(d2, "*.fsproj") ]
let collectionName =
match projectFiles with
| [ file1 ] -> Path.GetFileNameWithoutExtension file1
| _ -> Path.GetFileName slnDir
|> defaultArg userCollectionName
collectionName, projectFiles
| projectFiles, false ->
let collectionName = Path.GetFileName(slnDir)
collectionName, projectFiles |> List.map Path.GetFullPath
| _, true ->
let collectionName = defaultArg userCollectionName (Path.GetFileName slnDir)
collectionName, []
//printfn "projects = %A" projectFiles
let projectFiles =
projectFiles
|> List.filter (fun s ->
let isFSharpFormattingTestProject =
s.Contains $"FSharp.ApiDocs.Tests%c{Path.DirectorySeparatorChar}files"
|| s.EndsWith("FSharp.Formatting.TestHelpers.fsproj", StringComparison.Ordinal)
if isFSharpFormattingTestProject then
printfn
$" skipping project '%s{Path.GetFileName s}' because the project is part of the FSharp.Formatting test suite."
not isFSharpFormattingTestProject)
//printfn "filtered projects = %A" projectFiles
if projectFiles.Length = 0 && (ignoreProjects |> not) then
printfn "no project files found, no API docs will be generated"
if ignoreProjects then
printfn "project files are ignored, no API docs will be generated"
printfn "cracking projects..."
let projectInfos =
projectFiles
|> Array.ofList
|> Array.choose (fun p ->
try
crackProjectFile slnDir extraMsbuildProperties p
with e ->
printfn
" skipping project '%s' because an error occurred while cracking it: %O"
(Path.GetFileName p)
e
if not ignoreProjects then
onError "Project cracking failed and --strict is on, exiting"
None)
|> Array.toList
//printfn "projectInfos = %A" projectInfos
let projectInfos =
projectInfos
|> List.choose (fun info ->
let shortName = Path.GetFileName info.ProjectFileName
if info.TargetPath.IsNone then
printfn " skipping project '%s' because it doesn't have a target path" shortName
None
elif not info.IsLibrary && not info.FsDocsAllowExecutableProject then
printfn
" skipping project '%s' because it isn't a library (add <FsDocsAllowExecutableProject>true</FsDocsAllowExecutableProject> to include it)"
shortName
None
elif info.IsTestProject then
printfn " skipping project '%s' because it has <IsTestProject> true" shortName
None
elif not info.GenerateDocumentationFile then
printfn " skipping project '%s' because it doesn't have <GenerateDocumentationFile>" shortName
None
else
Some info)
//printfn "projectInfos = %A" projectInfos
if projectInfos.Length = 0 && projectFiles.Length > 0 then
printfn "Warning: While cracking project files, no project files succeeded."
let param setting key v =
match v with
| Some v -> Some(key, v)
| None ->
match setting with
| Some setting -> printfn "please set '%s' in 'Directory.Build.props'" setting
| None -> ()
None
/// Try and xpath query a fallback value from the current Directory.Build.props file.
/// This is useful to set some settings when there are no actual (c|f)sproj files.
let fallbackFromDirectoryProps =
if not (File.Exists "Directory.Build.props") then
fun _ optProp -> optProp
else
let xDoc = XDocument.Load("Directory.Build.props")
fun xpath optProp ->
optProp
|> Option.orElseWith (fun () ->
let xe = System.Xml.XPath.Extensions.XPathSelectElement(xDoc, xpath)
if isNull xe then None else Some xe.Value)
// For the 'docs' directory we use the best info we can find from across all projects
let projectInfoForDocs =
{ ProjectFileName = ""
ProjectOptions = None
TargetPath = None
IsTestProject = false
IsLibrary = true
IsPackable = true
RepositoryUrl =
projectInfos
|> List.tryPick (fun info -> info.RepositoryUrl)
|> fallbackFromDirectoryProps "//RepositoryUrl"
|> Option.map ensureTrailingSlash
RepositoryType = projectInfos |> List.tryPick (fun info -> info.RepositoryType)
RepositoryBranch = projectInfos |> List.tryPick (fun info -> info.RepositoryBranch)
FsDocsLicenseLink =
projectInfos
|> List.tryPick (fun info -> info.FsDocsLicenseLink)
|> fallbackFromDirectoryProps "//FsDocsLicenseLink"
FsDocsReleaseNotesLink =
projectInfos
|> List.tryPick (fun info -> info.FsDocsReleaseNotesLink)
|> fallbackFromDirectoryProps "//FsDocsReleaseNotesLink"
FsDocsLogoLink =
projectInfos
|> List.tryPick (fun info -> info.FsDocsLogoLink)
|> fallbackFromDirectoryProps "//FsDocsLogoLink"
FsDocsLogoSource =
projectInfos
|> List.tryPick (fun info -> info.FsDocsLogoSource)
|> fallbackFromDirectoryProps "//FsDocsLogoSource"
FsDocsLogoAlt =
projectInfos
|> List.tryPick (fun info -> info.FsDocsLogoAlt)
|> fallbackFromDirectoryProps "//FsDocsLogoAlt"
FsDocsFaviconSource =
projectInfos
|> List.tryPick (fun info -> info.FsDocsFaviconSource)
|> fallbackFromDirectoryProps "//FsDocsFaviconSource"
FsDocsSourceFolder = projectInfos |> List.tryPick (fun info -> info.FsDocsSourceFolder)
FsDocsSourceRepository =
projectInfos
|> List.tryPick (fun info -> info.FsDocsSourceRepository)
|> fallbackFromDirectoryProps "//RepositoryUrl"
FsDocsTheme = projectInfos |> List.tryPick (fun info -> info.FsDocsTheme)
FsDocsWarnOnMissingDocs = false
FsDocsGenerateLlmsTxt = projectInfos |> List.forall (fun i -> i.FsDocsGenerateLlmsTxt)
FsDocsAllowExecutableProject = false
FsDocsNoInheritedMembers = false
FsDocsTypeConstraints = FSharp.Formatting.ApiDocs.TypeConstraintDisplayMode.Short
PackageProjectUrl =
projectInfos
|> List.tryPick (fun info -> info.PackageProjectUrl)
|> Option.map ensureTrailingSlash
Authors =
projectInfos
|> List.tryPick (fun info -> info.Authors)
|> fallbackFromDirectoryProps "//Authors"
GenerateDocumentationFile = true
PackageLicenseExpression = projectInfos |> List.tryPick (fun info -> info.PackageLicenseExpression)
PackageTags = projectInfos |> List.tryPick (fun info -> info.PackageTags)
UsesMarkdownComments = false
Copyright = projectInfos |> List.tryPick (fun info -> info.Copyright)
PackageVersion =
projectInfos
|> List.tryPick (fun info -> info.PackageVersion)
|> fallbackFromDirectoryProps "//Version"
PackageIconUrl = projectInfos |> List.tryPick (fun info -> info.PackageIconUrl)
RepositoryCommit = projectInfos |> List.tryPick (fun info -> info.RepositoryCommit) }
let root =
let projectUrl = projectInfoForDocs.PackageProjectUrl |> Option.map ensureTrailingSlash
defaultArg userRoot (defaultArg projectUrl ("/" + collectionName) |> ensureTrailingSlash)
let parametersForProjectInfo (info: CrackedProjectInfo) =
let projectUrl =
info.PackageProjectUrl
|> Option.map ensureTrailingSlash
|> Option.defaultValue root
let repoUrl = info.RepositoryUrl |> Option.map ensureTrailingSlash
List.choose
id
[ param None ParamKeys.root (Some root)
param None ParamKeys.``fsdocs-authors`` (Some(info.Authors |> Option.defaultValue ""))
param None ParamKeys.``fsdocs-collection-name`` (Some collectionName)
param None ParamKeys.``fsdocs-copyright`` info.Copyright
param
(Some "<FsDocsLogoSource>")
ParamKeys.``fsdocs-logo-src``
(Some(defaultArg info.FsDocsLogoSource "img/logo.png"))
param
(Some "<FsDocsLogoAlt>")
ParamKeys.``fsdocs-logo-alt``
(Some(defaultArg info.FsDocsLogoAlt "Logo"))
param
(Some "<FsDocsFaviconSource>")
ParamKeys.``fsdocs-favicon-src``
(Some(defaultArg info.FsDocsFaviconSource "img/favicon.ico"))
param None ParamKeys.``fsdocs-theme`` (Some(defaultArg info.FsDocsTheme "default"))
param
(Some "<FsDocsLogoLink>")
ParamKeys.``fsdocs-logo-link``
(Some(info.FsDocsLogoLink |> Option.defaultValue projectUrl))
param
(Some "<FsDocsLicenseLink>")
ParamKeys.``fsdocs-license-link``
(info.FsDocsLicenseLink
|> Option.orElse (Option.map (sprintf "%sblob/master/LICENSE.md") repoUrl))
param
(Some "<FsDocsReleaseNotesLink>")
ParamKeys.``fsdocs-release-notes-link``
(info.FsDocsReleaseNotesLink
|> Option.orElse (Option.map (sprintf "%sblob/master/RELEASE_NOTES.md") repoUrl))
param None ParamKeys.``fsdocs-package-project-url`` (Some projectUrl)
param None ParamKeys.``fsdocs-package-license-expression`` info.PackageLicenseExpression
param None ParamKeys.``fsdocs-package-icon-url`` info.PackageIconUrl
param None ParamKeys.``fsdocs-package-tags`` (Some(info.PackageTags |> Option.defaultValue ""))
param (Some "<Version>") ParamKeys.``fsdocs-package-version`` info.PackageVersion
param (Some "<RepositoryUrl>") ParamKeys.``fsdocs-repository-link`` repoUrl
param None ParamKeys.``fsdocs-repository-branch`` info.RepositoryBranch
param None ParamKeys.``fsdocs-repository-commit`` info.RepositoryCommit ]
@ userParameters
let crackedProjects =
projectInfos
|> List.choose (fun info ->
match info.TargetPath, info.ProjectOptions with
| Some targetPath, Some projectOptions ->
let substitutions = parametersForProjectInfo info
Some(
targetPath,
projectOptions.OtherOptions,
info.RepositoryUrl,
info.RepositoryBranch,
info.RepositoryType,
info.UsesMarkdownComments,
info.FsDocsWarnOnMissingDocs,
info.FsDocsSourceFolder,
info.FsDocsSourceRepository,
info.FsDocsNoInheritedMembers,
info.FsDocsTypeConstraints,
substitutions
)
| _ -> None)
let paths =
projectInfos
|> List.choose (fun projectInfo -> projectInfo.TargetPath |> Option.map Path.GetDirectoryName)
let docsParameters = parametersForProjectInfo projectInfoForDocs
root, collectionName, crackedProjects, paths, docsParameters, projectInfoForDocs.FsDocsGenerateLlmsTxt