-
Notifications
You must be signed in to change notification settings - Fork 311
/
Copy pathProjectCracker.fs
1343 lines (1161 loc) · 46.9 KB
/
ProjectCracker.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
/// This module gets the F# compiler arguments from .fsproj as well as some
/// Fable-specific tasks like tracking the sources of Fable Nuget packages
module Fable.Compiler.ProjectCracker
open System
open System.Xml.Linq
open System.Text.RegularExpressions
open System.Collections.Generic
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.Text
open Fable
open Fable.AST
open Fable.Compiler.Util
open Globbing.Operators
open Buildalyzer
type FablePackage =
{
Id: string
Version: string
FsprojPath: string
DllPath: string
SourcePaths: string list
Dependencies: Set<string>
}
type CacheInfo =
{
Version: string
FableOptions: CompilerOptions
ProjectPath: string
SourcePaths: string array
FSharpOptions: string array
References: string list
OutDir: string option
FableLibDir: string
FableModulesDir: string
OutputType: OutputType
TargetFramework: string
Exclude: string list
SourceMaps: bool
SourceMapsRoot: string option
}
static member GetPath(fableModulesDir: string, isDebug: bool) =
let suffix =
if isDebug then
"_debug"
else
""
IO.Path.Combine(fableModulesDir, $"project_cracked%s{suffix}.json")
member this.GetTimestamp() =
CacheInfo.GetPath(this.FableModulesDir, this.FableOptions.DebugMode)
|> IO.File.GetLastWriteTime
static member TryRead(fableModulesDir: string, isDebug) : CacheInfo option =
try
CacheInfo.GetPath(fableModulesDir, isDebug)
|> Json.read<CacheInfo>
|> Some
with _ ->
None
member this.Write() =
let path =
CacheInfo.GetPath(this.FableModulesDir, this.FableOptions.DebugMode)
// Ensure the destination folder exists
if not (IO.File.Exists path) then
IO.Directory.CreateDirectory(IO.Path.GetDirectoryName path)
|> ignore
Json.write path this
/// Checks if there's also cache info for the alternate build mode (Debug/Release) and whether is more recent
member this.IsMostRecent =
match
CacheInfo.TryRead(
this.FableModulesDir,
not this.FableOptions.DebugMode
)
with
| None -> true
| Some other -> this.GetTimestamp() > other.GetTimestamp()
type CrackerOptions(cliArgs: CliArgs) =
let projDir = IO.Path.GetDirectoryName cliArgs.ProjectFile
let fableModulesDir =
CrackerOptions.GetFableModulesFromProject(
projDir,
cliArgs.OutDir,
cliArgs.NoCache
)
let builtDlls = HashSet()
let cacheInfo =
if cliArgs.NoCache then
None
else
CacheInfo.TryRead(
fableModulesDir,
cliArgs.CompilerOptions.DebugMode
)
member _.NoCache = cliArgs.NoCache
member _.CacheInfo = cacheInfo
member _.FableModulesDir = fableModulesDir
member _.FableOptions: CompilerOptions = cliArgs.CompilerOptions
member _.FableLib: string option = cliArgs.FableLibraryPath
member _.OutDir: string option = cliArgs.OutDir
member _.Configuration: string = cliArgs.Configuration
member _.Exclude: string list = cliArgs.Exclude
member _.Replace: Map<string, string> = cliArgs.Replace
member _.PrecompiledLib: string option = cliArgs.PrecompiledLib
member _.NoRestore: bool = cliArgs.NoRestore
member _.ProjFile: string = cliArgs.ProjectFile
member _.SourceMaps: bool = cliArgs.SourceMaps
member _.SourceMapsRoot: string option = cliArgs.SourceMapsRoot
member _.BuildDll(normalizedDllPath: string) =
if not (builtDlls.Contains(normalizedDllPath)) then
let projDir =
normalizedDllPath.Split('/')
|> Array.rev
|> Array.skipWhile (fun part -> part <> "bin")
|> Array.skip 1
|> Array.rev
|> String.concat "/"
Process.runSync
projDir
"dotnet"
[
"build"
"-c"
cliArgs.Configuration
]
|> ignore
builtDlls.Add(normalizedDllPath) |> ignore
static member GetFableModulesFromDir(baseDir: string) : string =
IO.Path.Combine(baseDir, Naming.fableModules) |> Path.normalizePath
static member GetFableModulesFromProject
(
projDir: string,
outDir: string option,
noCache: bool
)
: string
=
let fableModulesDir =
outDir
|> Option.defaultWith (fun () -> projDir)
|> CrackerOptions.GetFableModulesFromDir
if noCache then
if IO.Directory.Exists(fableModulesDir) then
IO.Directory.Delete(fableModulesDir, recursive = true)
if File.isDirectoryEmpty fableModulesDir then
IO.Directory.CreateDirectory(fableModulesDir) |> ignore
IO.File.WriteAllText(
IO.Path.Combine(fableModulesDir, ".gitignore"),
"**/*"
)
fableModulesDir
member _.ResetFableModulesDir() =
if IO.Directory.Exists(fableModulesDir) then
IO.Directory.Delete(fableModulesDir, recursive = true)
IO.Directory.CreateDirectory(fableModulesDir) |> ignore
IO.File.WriteAllText(
IO.Path.Combine(fableModulesDir, ".gitignore"),
"**/*"
)
type CrackerResponse =
{
FableLibDir: string
FableModulesDir: string
References: string list
ProjectOptions: FSharpProjectOptions
OutputType: OutputType
TargetFramework: string
PrecompiledInfo: PrecompiledInfoImpl option
CanReuseCompiledFiles: bool
}
let isSystemPackage (pkgName: string) =
pkgName.StartsWith("System.", StringComparison.Ordinal)
|| pkgName.StartsWith("Microsoft.", StringComparison.Ordinal)
|| pkgName.StartsWith("runtime.", StringComparison.Ordinal)
|| pkgName = "NETStandard.Library"
|| pkgName = "FSharp.Core"
|| pkgName = "Fable.Core"
type CrackedFsproj =
{
ProjectFile: string
SourceFiles: string list
ProjectReferences: string list
DllReferences: IDictionary<string, string>
PackageReferences: FablePackage list
OtherCompilerOptions: string list
OutputType: string option
TargetFramework: string
}
let makeProjectOptions
(opts: CrackerOptions)
otherOptions
sources
: FSharpProjectOptions
=
let otherOptions =
[|
yield! otherOptions
for constant in opts.FableOptions.Define do
yield "--define:" + constant
yield
"--optimize"
+ if opts.FableOptions.OptimizeFSharpAst then
"+"
else
"-"
|]
{
ProjectId = None
ProjectFileName = opts.ProjFile
OtherOptions = otherOptions
SourceFiles = Array.distinct sources
ReferencedProjects = [||]
IsIncompleteTypeCheckEnvironment = false
UseScriptResolutionRules = false
LoadTime = DateTime.UtcNow
UnresolvedReferences = None
OriginalLoadReferences = []
Stamp = None
}
let tryGetFablePackage (opts: CrackerOptions) (dllPath: string) =
let tryFileWithPattern dir pattern =
try
let files = IO.Directory.GetFiles(dir, pattern)
match files.Length with
| 0 -> None
| 1 -> Some files[0]
| _ ->
Log.always (
"More than one file found in "
+ dir
+ " with pattern "
+ pattern
)
None
with _ ->
None
let firstWithName localName (els: XElement seq) =
els |> Seq.find (fun x -> x.Name.LocalName = localName)
let tryFirstWithName localName (els: XElement seq) =
els |> Seq.tryFind (fun x -> x.Name.LocalName = localName)
let elements (el: XElement) = el.Elements()
let attr name (el: XElement) = el.Attribute(XName.Get name).Value
let child localName (el: XElement) =
let child = el.Elements() |> firstWithName localName
child.Value
let firstGroupOrAllDependencies (dependencies: XElement seq) =
match tryFirstWithName "group" dependencies with
| Some firstGroup -> elements firstGroup
| None -> dependencies
if Path.GetFileNameWithoutExtension(dllPath) |> isSystemPackage then
None
else
let rootDir =
IO.Path.Combine(IO.Path.GetDirectoryName(dllPath), "..", "..")
let fableDir = IO.Path.Combine(rootDir, "fable")
match
tryFileWithPattern rootDir "*.nuspec",
tryFileWithPattern fableDir "*.fsproj"
with
| Some nuspecPath, Some fsprojPath ->
let xmlDoc = XDocument.Load(nuspecPath)
let metadata = xmlDoc.Root.Elements() |> firstWithName "metadata"
let pkgId = metadata |> child "id"
let fsprojPath =
match Map.tryFind pkgId opts.Replace with
| Some replaced ->
if
replaced.EndsWith(".fsproj", StringComparison.Ordinal)
then
replaced
else
tryFileWithPattern replaced "*.fsproj"
|> Option.defaultValue fsprojPath
| None -> fsprojPath
{
Id = pkgId
Version = metadata |> child "version"
FsprojPath = fsprojPath
DllPath = dllPath
SourcePaths = []
Dependencies =
metadata.Elements()
|> firstWithName "dependencies"
|> elements
// We don't consider different frameworks
|> firstGroupOrAllDependencies
|> Seq.map (attr "id")
|> Seq.filter (isSystemPackage >> not)
|> Set
}
: FablePackage
|> Some
| _ -> None
let sortFablePackages (pkgs: FablePackage list) =
([], pkgs)
||> List.fold (fun acc pkg ->
match
List.tryFindIndexBack
(fun (x: FablePackage) -> pkg.Dependencies.Contains(x.Id))
acc
with
| None -> pkg :: acc
| Some targetIdx ->
let rec insertAfter x targetIdx i before after =
match after with
| justBefore :: after ->
if i = targetIdx then
if i > 0 then
let dependent, nonDependent =
List.rev before
|> List.partition (fun (x: FablePackage) ->
x.Dependencies.Contains(pkg.Id)
)
nonDependent @ justBefore :: x :: dependent @ after
else
(justBefore :: before |> List.rev) @ x :: after
else
insertAfter
x
targetIdx
(i + 1)
(justBefore :: before)
after
| [] -> failwith "Unexpected empty list in insertAfter"
insertAfter pkg targetIdx 0 [] acc
)
let private getDllName (dllFullPath: string) =
let i = dllFullPath.LastIndexOf('/')
dllFullPath[(i + 1) .. (dllFullPath.Length - 5)] // -5 removes the .dll extension
let getBasicCompilerArgs () =
[|
// "--debug"
// "--debug:portable"
"--noframework"
"--nologo"
"--simpleresolution"
"--nocopyfsharpcore"
"--nowin32manifest"
// "--nowarn:NU1603,NU1604,NU1605,NU1608"
// "--warnaserror:76"
"--warn:3"
"--fullpaths"
"--flaterrors"
// Since net5.0 there's no difference between app/library
// yield "--target:library"
|]
let MSBUILD_CONDITION =
Regex(
@"^\s*'\$\((\w+)\)'\s*([!=]=)\s*'(true|false)'\s*$",
RegexOptions.IgnoreCase
)
/// Simplistic XML-parsing of .fsproj to get source files, as we cannot
/// run `dotnet restore` on .fsproj files embedded in Nuget packages.
let getSourcesFromFablePkg (opts: CrackerOptions) (projFile: string) =
let withName s (xs: XElement seq) =
xs |> Seq.filter (fun x -> x.Name.LocalName = s)
let checkCondition (el: XElement) =
match el.Attribute(XName.Get "Condition") with
| null -> true
| attr ->
match attr.Value with
| Naming.Regex MSBUILD_CONDITION [ _; prop; op; bval ] ->
let bval = Boolean.Parse bval
let isTrue = (op = "==") = bval // (op = "==" && bval) || (op = "!=" && not bval)
let isDefined =
opts.FableOptions.Define
|> List.exists (fun d ->
String.Equals(
d,
prop,
StringComparison.InvariantCultureIgnoreCase
)
)
// printfn $"CONDITION: {prop} ({isDefined}) {op} {bval} ({isTrue})"
isTrue = isDefined
| _ -> false
let withNameAndCondition s (xs: XElement seq) =
xs |> Seq.filter (fun el -> el.Name.LocalName = s && checkCondition el)
let xmlDoc = XDocument.Load(projFile)
let projDir = Path.GetDirectoryName(projFile)
Log.showFemtoMsg (fun () ->
xmlDoc.Root.Elements()
|> withName "PropertyGroup"
|> Seq.exists (fun propGroup ->
propGroup.Elements()
|> withName "NpmDependencies"
|> Seq.isEmpty
|> not
)
)
xmlDoc.Root.Elements()
|> withNameAndCondition "ItemGroup"
|> Seq.map (fun item ->
(item.Elements(), [])
||> Seq.foldBack (fun el src ->
if el.Name.LocalName = "Compile" && checkCondition el then
el.Elements()
|> withName "Link"
|> Seq.tryHead
|> function
| Some link when Path.isRelativePath link.Value ->
link.Value :: src
| _ ->
match el.Attribute(XName.Get "Include") with
| null -> src
| att -> att.Value :: src
else
src
)
)
|> List.concat
|> List.collect (fun fileName ->
Path.Combine(projDir, fileName)
|> function
| path when (path.Contains("*") || path.Contains("?")) ->
match !!path |> List.ofSeq with
| [] -> [ path ]
| globResults -> globResults
| path -> [ path ]
|> List.map Path.normalizeFullPath
)
let private extractUsefulOptionsAndSources
isMainProj
(line: string)
(accSources: string list, accOptions: string list)
=
if line.StartsWith('-') then
// "--warnaserror" // Disable for now to prevent unexpected errors, see #2288
if
line.StartsWith("--langversion:", StringComparison.Ordinal)
&& isMainProj
then
let v = line.Substring("--langversion:".Length).ToLowerInvariant()
if v = "preview" then
accSources, line :: accOptions
else
accSources, accOptions
elif
line.StartsWith("--nowarn", StringComparison.Ordinal)
|| line.StartsWith("--warnon", StringComparison.Ordinal)
then
accSources, line :: accOptions
elif line.StartsWith("--define:", StringComparison.Ordinal) then
// When parsing the project as .csproj there will be multiple defines in the same line,
// but the F# compiler seems to accept only one per line
let defines =
line.Substring(9).Split(';')
|> Array.mapToList (fun d -> "--define:" + d)
accSources, defines @ accOptions
else
accSources, accOptions
else
(Path.normalizeFullPath line) :: accSources, accOptions
let excludeProjRef
(opts: CrackerOptions)
(dllRefs: IDictionary<string, string>)
(projRef: string)
=
let projName = Path.GetFileNameWithoutExtension(projRef)
let isExcluded =
opts.Exclude
|> List.exists (fun e ->
String.Equals(
e,
Path.GetFileNameWithoutExtension(projRef),
StringComparison.OrdinalIgnoreCase
)
)
if isExcluded then
try
opts.BuildDll(dllRefs[projName])
with e ->
Log.always ("Couldn't build " + projName + ": " + e.Message)
None
else
let _removed = dllRefs.Remove(projName)
// if not removed then
// Log.always("Couldn't remove project reference " + projName + " from dll references")
Path.normalizeFullPath projRef |> Some
let getCrackedMainFsproj
(opts: CrackerOptions)
(projOpts: string[], projRefs, msbuildProps, targetFramework)
=
// Use case insensitive keys, as package names in .paket.resolved
// may have a different case, see #1227
let dllRefs = Dictionary(StringComparer.OrdinalIgnoreCase)
let sourceFiles, otherOpts =
(projOpts, ([], []))
||> Array.foldBack (fun line (src, otherOpts) ->
if line.StartsWith("-r:", StringComparison.Ordinal) then
let line = Path.normalizePath (line[3..])
let dllName = getDllName line
dllRefs.Add(dllName, line)
src, otherOpts
else
extractUsefulOptionsAndSources true line (src, otherOpts)
)
let fablePkgs =
let dllRefs' =
dllRefs |> Seq.map (fun (KeyValue(k, v)) -> k, v) |> Seq.toArray
dllRefs'
|> Seq.choose (fun (dllName, dllPath) ->
match tryGetFablePackage opts dllPath with
| Some pkg ->
dllRefs.Remove(dllName) |> ignore
Some pkg
| None -> None
)
|> Seq.toList
|> sortFablePackages
{
ProjectFile = opts.ProjFile
SourceFiles = sourceFiles
ProjectReferences =
projRefs
|> Array.choose (excludeProjRef opts dllRefs)
|> Array.toList
DllReferences = dllRefs
PackageReferences = fablePkgs
OtherCompilerOptions = otherOpts
OutputType = ReadOnlyDictionary.tryFind "OutputType" msbuildProps
TargetFramework = targetFramework
}
let getProjectOptionsFromScript (opts: CrackerOptions) : CrackedFsproj =
let projectFilePath = opts.ProjFile
let projOpts, _diagnostics = // TODO: Check diagnostics
let checker = FSharpChecker.Create()
let text =
File.readAllTextNonBlocking (projectFilePath) |> SourceText.ofString
checker.GetProjectOptionsFromScript(
projectFilePath,
text,
useSdkRefs = true,
assumeDotNetFramework = false
)
|> Async.RunSynchronously
let projOpts = Array.append projOpts.OtherOptions projOpts.SourceFiles
getCrackedMainFsproj opts (projOpts, [||], Dictionary(), "")
let getProjectOptionsFromProjectFile =
let mutable manager = None
let tryGetResult
(isMain: bool)
(opts: CrackerOptions)
(manager: AnalyzerManager)
(maybeCsprojFile: string)
=
if isMain && not opts.NoRestore then
Process.runSync
(IO.Path.GetDirectoryName opts.ProjFile)
"dotnet"
[
"restore"
IO.Path.GetFileName maybeCsprojFile
// $"-p:TargetFramework={opts.TargetFramework}"
for constant in opts.FableOptions.Define do
$"-p:{constant}=true"
]
|> ignore
let analyzer = manager.GetProject(maybeCsprojFile)
let env =
analyzer.EnvironmentFactory.GetBuildEnvironment(
Environment.EnvironmentOptions(
DesignTime = true,
Restore = false
)
)
// If the project targets multiple frameworks, multiple results will be returned
// For now we just take the first one with non-empty command
let results = analyzer.Build(env)
results |> Seq.tryFind (fun r -> String.IsNullOrEmpty(r.Command) |> not)
fun (isMain: bool) (opts: CrackerOptions) (projFile: string) ->
let manager =
match manager with
| Some m -> m
| None ->
let log = new System.IO.StringWriter()
let options = AnalyzerManagerOptions(LogWriter = log)
let m = AnalyzerManager(options)
m.SetGlobalProperty("Configuration", opts.Configuration)
// m.SetGlobalProperty("TargetFramework", opts.TargetFramework)
for define in opts.FableOptions.Define do
m.SetGlobalProperty(define, "true")
manager <- Some m
m
// Because Buildalyzer works better with .csproj, we first "dress up" the project as if it were a C# one
// and try to adapt the results. If it doesn't work, we try again to analyze the .fsproj directly
let csprojResult =
let csprojFile = projFile.Replace(".fsproj", ".fable-temp.csproj")
if IO.File.Exists(csprojFile) then
None
else
try
IO.File.Copy(projFile, csprojFile)
let xmlDocument = XDocument.Load(csprojFile)
let xmlComment =
XComment(
"""This is a temporary file used by Fable to restore dependencies.
If you see this file in your project, you can delete it safely"""
)
// An fsproj/csproj should always have a root element
// so it should be safe to add the comment as first child
// of the root element
xmlDocument.Root.AddFirst(xmlComment)
xmlDocument.Save(csprojFile)
tryGetResult isMain opts manager csprojFile
|> Option.map (fun (r: IAnalyzerResult) ->
// Careful, options for .csproj start with / but so do root paths in unix
let reg = Regex(@"^\/[^\/]+?(:?:|$)")
let comArgs =
r.CompilerArguments
|> Array.map (fun line ->
if reg.IsMatch(line) then
if
line.StartsWith(
"/reference",
StringComparison.Ordinal
)
then
"-r" + line.Substring(10)
else
"--" + line.Substring(1)
else
line
)
let comArgs =
match r.Properties.TryGetValue("OtherFlags") with
| false, _ -> comArgs
| true, otherFlags ->
let otherFlags =
otherFlags.Split(
' ',
StringSplitOptions.RemoveEmptyEntries
)
Array.append otherFlags comArgs
comArgs, r
)
finally
File.safeDelete csprojFile
let compilerArgs, result =
csprojResult
|> Option.orElseWith (fun () ->
tryGetResult isMain opts manager projFile
|> Option.map (fun r ->
// result.CompilerArguments doesn't seem to work well in Linux
let comArgs = Regex.Split(r.Command, @"\r?\n")
comArgs, r
)
)
|> function
| Some result -> result
// TODO: Get Buildalyzer errors from the log
| None ->
$"Cannot parse {projFile}" |> Fable.FableError |> raise
let projDir = IO.Path.GetDirectoryName(projFile)
let projOpts =
compilerArgs
|> Array.skipWhile (fun line -> not (line.StartsWith('-')))
|> Array.map (fun f ->
if
f.EndsWith(".fs", StringComparison.Ordinal)
|| f.EndsWith(".fsi", StringComparison.Ordinal)
then
if Path.IsPathRooted f then
f
else
Path.Combine(projDir, f)
else
f
)
projOpts,
Seq.toArray result.ProjectReferences,
result.Properties,
result.TargetFramework
/// Use Buildalyzer to invoke MSBuild and get F# compiler args from an .fsproj file.
/// As we'll merge this later with other projects we'll only take the sources and
/// the references, checking if some .dlls correspond to Fable libraries
let crackMainProject (opts: CrackerOptions) : CrackedFsproj =
getProjectOptionsFromProjectFile true opts opts.ProjFile
|> getCrackedMainFsproj opts
/// For project references of main project, ignore dll and package references
let crackReferenceProject
(opts: CrackerOptions)
dllRefs
(projFile: string)
: CrackedFsproj
=
let projOpts, projRefs, msbuildProps, targetFramework =
getProjectOptionsFromProjectFile false opts projFile
let sourceFiles, otherOpts =
Array.foldBack (extractUsefulOptionsAndSources false) projOpts ([], [])
{
ProjectFile = projFile
SourceFiles = sourceFiles
ProjectReferences =
projRefs
|> Array.choose (excludeProjRef opts dllRefs)
|> Array.toList
DllReferences = Dictionary()
PackageReferences = []
OtherCompilerOptions = otherOpts
OutputType = ReadOnlyDictionary.tryFind "OutputType" msbuildProps
TargetFramework = targetFramework
}
let getCrackedProjectsFromMainFsproj (opts: CrackerOptions) =
let mainProj = crackMainProject opts
let rec crackProjects (acc: CrackedFsproj list) (projFile: string) =
let crackedFsproj =
match acc |> List.tryFind (fun x -> x.ProjectFile = projFile) with
| None -> crackReferenceProject opts mainProj.DllReferences projFile
| Some crackedFsproj -> crackedFsproj
// Add always a reference to the front to preserve compilation order
// Duplicated items will be removed later
List.fold
crackProjects
(crackedFsproj :: acc)
crackedFsproj.ProjectReferences
let refProjs =
List.fold crackProjects [] mainProj.ProjectReferences
|> List.distinctBy (fun x -> x.ProjectFile)
refProjs, mainProj
let getCrackedProjects (opts: CrackerOptions) =
match (Path.GetExtension opts.ProjFile).ToLower() with
| ".fsx" -> [], getProjectOptionsFromScript opts
| ".fsproj" -> getCrackedProjectsFromMainFsproj opts
| s -> failwith $"Unsupported project type: %s{s}"
// It is common for editors with rich editing or 'intellisense' to also be watching the project
// file for changes. In some cases that editor will lock the file which can cause fable to
// get a read error. If that happens the lock is usually brief so we can reasonably wait
// for it to be released.
let retryGetCrackedProjects opts =
let retryUntil = (DateTime.Now + TimeSpan.FromSeconds 2.)
let rec retry () =
try
getCrackedProjects opts
with
| :? IO.IOException as ioex ->
if retryUntil > DateTime.Now then
System.Threading.Thread.Sleep 500
retry ()
else
failwith
$"IO Error trying read project options: %s{ioex.Message} "
| _ -> reraise ()
retry ()
// Replace the .fsproj extension with .fableproj for files in fable_modules
// We do this to avoid conflicts with other F# tooling that scan for .fsproj files
let changeFsprojToFableproj (path: string) =
if path.EndsWith(".fsproj", StringComparison.Ordinal) then
IO.Path.ChangeExtension(path, Naming.fableProjExt)
else
path
let copyDir replaceFsprojExt (source: string) (target: string) =
IO.Directory.CreateDirectory(target) |> ignore
if IO.Directory.Exists source |> not then
failwith ("Source directory is missing: " + source)
let source = source.TrimEnd('/', '\\')
let target = target.TrimEnd('/', '\\')
for dirPath in
IO.Directory.GetDirectories(source, "*", IO.SearchOption.AllDirectories) do
IO.Directory.CreateDirectory(dirPath.Replace(source, target)) |> ignore
for fromPath in
IO.Directory.GetFiles(source, "*.*", IO.SearchOption.AllDirectories) do
let toPath = fromPath.Replace(source, target)
let toPath =
if replaceFsprojExt then
changeFsprojToFableproj toPath
else
toPath
IO.File.Copy(fromPath, toPath, true)
let copyDirIfDoesNotExist replaceFsprojExt (source: string) (target: string) =
if File.isDirectoryEmpty target then
copyDir replaceFsprojExt source target
let getFableLibraryPath (opts: CrackerOptions) =
let buildDir, libDir =
match opts.FableOptions.Language, opts.FableLib with
| Dart, None -> "fable-library-dart", "fable_library"
| Rust, None -> "fable-library-rust", "fable-library-rust"
| TypeScript, None -> "fable-library-ts", "fable-library-ts"
| Php, None -> "fable-library-php", "fable-library-php"
| JavaScript, None ->
"fable-library", "fable-library" + "." + Literals.VERSION
| Python, None -> "fable-library-py/fable_library", "fable_library"
| Python, Some Py.Naming.sitePackages ->
"fable-library-py", "fable-library"
| _, Some path ->
if path.StartsWith("./", StringComparison.Ordinal) then
"", Path.normalizeFullPath path
elif IO.Path.IsPathRooted(path) then
"", Path.normalizePath path
else
"", path
if String.IsNullOrEmpty(buildDir) then
libDir
else
let fableLibrarySource =
let baseDir = AppContext.BaseDirectory
baseDir
|> File.tryFindNonEmptyDirectoryUpwards
{|
matches =
[
buildDir
"temp/" + buildDir
]
exclude = [ "src" ]
|}
|> Option.defaultWith (fun () ->
Fable.FableError
$"Cannot find [temp/]{buildDir} from {baseDir}.\nPlease, make sure you build {buildDir}"
|> raise
)
let fableLibraryTarget = IO.Path.Combine(opts.FableModulesDir, libDir)
// Always overwrite fable-library in case it has been updated, see #3208
copyDir false fableLibrarySource fableLibraryTarget
Path.normalizeFullPath fableLibraryTarget
let copyFableLibraryAndPackageSources
(opts: CrackerOptions)
(pkgs: FablePackage list)
=
let pkgRefs =
pkgs
|> List.map (fun pkg ->
let sourceDir = IO.Path.GetDirectoryName(pkg.FsprojPath)
let targetDir =
IO.Path.Combine(
opts.FableModulesDir,
pkg.Id + "." + pkg.Version
)
copyDirIfDoesNotExist true sourceDir targetDir
let fsprojFile =
IO.Path.GetFileName(pkg.FsprojPath) |> changeFsprojToFableproj
{ pkg with FsprojPath = IO.Path.Combine(targetDir, fsprojFile) }
)
getFableLibraryPath opts, pkgRefs
// Separate handling for Python. Use plain lowercase package names without dots or version info.
let copyFableLibraryAndPackageSourcesPy
(opts: CrackerOptions)
(pkgs: FablePackage list)
=
let pkgRefs =
pkgs
|> List.map (fun pkg ->
let sourceDir = IO.Path.GetDirectoryName(pkg.FsprojPath)
let targetDir =
match opts.FableLib with
| Some Py.Naming.sitePackages ->
let name =
Naming.applyCaseRule Core.CaseRules.KebabCase pkg.Id
IO.Path.Combine(
opts.FableModulesDir,
name.Replace(".", "-")
)
| _ ->
let name =
Naming.applyCaseRule Core.CaseRules.SnakeCase pkg.Id
IO.Path.Combine(
opts.FableModulesDir,
name.Replace(".", "_")
)
copyDirIfDoesNotExist false sourceDir targetDir
{ pkg with
FsprojPath =
IO.Path.Combine(
targetDir,
IO.Path.GetFileName(pkg.FsprojPath)
)
}
)