-
Notifications
You must be signed in to change notification settings - Fork 520
/
ProjectFile.fs
2112 lines (1772 loc) · 97.8 KB
/
ProjectFile.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 Paket
open Paket
open Paket.Domain
open Paket.Logging
open Paket.InterprojectReferencesConstraint
open System
open System.Collections.Concurrent
open System.Collections.Generic
open System.IO
open System.Text
open System.Text.RegularExpressions
open System.Xml
open Paket.Xml
open Paket.Requirements
open Paket.PackageSources
open System.Globalization
[<RequireQualifiedAccess>]
type BuildAction =
| Compile | Content | Reference
| Resource | Page // These two are WPF only - https://msdn.microsoft.com/library/aa970494%28v=vs.100%29.aspx?f=255&MSPPError=-2147217396
// There are some other build actions - http://stackoverflow.com/questions/145752/what-are-the-various-build-action-settings-in-visual-studio-project-properties/145769#145769
override this.ToString() =
match this with
| Compile -> "Compile"
| Content -> "Content"
| Reference -> "Reference"
| Resource -> "Resource"
| Page -> "Page"
static member PaketFileNodeNames =
[Compile; Content; Resource; Page] |> List.map (fun x->x.ToString())
/// File item inside of project files.
type FileItem =
{ BuildAction : BuildAction
Include : string
WithPaketSubNode: bool
CopyToOutputDirectory: CopyToOutputDirectorySettings option
Link : string option }
/// Project references inside of project files.
type ProjectReference =
{ Path : string
RelativePath : string
Name : string option
ReferenceOutputAssembly : bool
GUID : Guid option }
/// Compile items inside of project files.
type CompileItem =
{ SourceFile : string
DestinationPath : string
BaseDir : string }
/// Project output type.
[<RequireQualifiedAccess>]
type ProjectOutputType =
| Exe
| Library
[<RequireQualifiedAccess>]
type ProjectLanguage = Unknown | CSharp | FSharp | VisualBasic | WiX | Nemerle | CPP | IronPython | ServiceFabric | Sql
module LanguageEvaluation =
let private extractProjectTypeGuids (projectDocument:XmlDocument) =
projectDocument
|> getDescendants "PropertyGroup"
|> List.filter(fun g -> g.Attributes.Count = 0)
|> List.collect(fun g -> g |> getDescendants "ProjectTypeGuids")
|> List.filter(fun pt -> pt.Attributes.Count = 0)
|> List.collect(fun pt -> pt.InnerText.Split ';' |> List.ofArray)
|> List.distinct
|> List.choose(fun guid -> match Guid.TryParse guid with | true, g -> Some g | _ -> None)
let private csharpGuids =
[
"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" // C#
"{BF6F8E12-879D-49E7-ADF0-5503146B24B8}" // Dynamics 2012 AX C# in AOT
"{20D4826A-C6FA-45DB-90F4-C717570B9F32}" // Legacy (2003) Smart Device (C#)
"{593B0543-81F6-4436-BA1E-4747859CAAE2}" // SharePoint (C#)
"{4D628B5B-2FBC-4AA6-8C16-197242AEB884}" // Smart Device (C#)
"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" // Windows (C#)
"{C089C8C0-30E0-4E22-80C0-CE093F111A43}" // Windows Phone 8/8.1 App (C#)
"{14822709-B5A1-4724-98CA-57A101D1B079}" // Workflow (C#)
] |> List.map Guid.Parse |> Set.ofList
let private vbGuids =
[
"{CB4CE8C6-1BDB-4DC7-A4D3-65A1999772F8}" // Legacy (2003) Smart Device (VB.NET)
"{EC05E597-79D4-47f3-ADA0-324C4F7C7484}" // SharePoint (VB.NET)
"{68B1623D-7FB9-47D8-8664-7ECEA3297D4F}" // Smart Device (VB.NET)
"{F184B08F-C81C-45F6-A57F-5ABD9991F28F}" // VB.NET
"{F184B08F-C81C-45F6-A57F-5ABD9991F28F}" // Windows (VB.NET)
"{DB03555F-0C8B-43BE-9FF9-57896B3C5E56}" // Windows Phone 8/8.1 App (VB.NET)
"{D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8}" // Workflow (VB.NET)
] |> List.map Guid.Parse |> Set.ofList
let private fsharpGuids =
[
"{F2A71F9B-5D33-465A-A702-920D77279786}" // F#
] |> List.map Guid.Parse |> Set.ofList
let private nemerleGuids =
[
"{EDCC3B85-0BAD-11DB-BC1A-00112FDE8B61}" // Nemerle
] |> List.map Guid.Parse |> Set.ofList
let private ironPythonGuids =
[
"{D499C55F-46C0-4FE1-8D05-02605C1891EA}" // IronPython
] |> List.map Guid.Parse |> Set.ofList
let private serviceFabric =
[
"{e1296024-58b6-4e25-843e-b9faa9b07be6}" // ServiceFabric
] |> List.map Guid.Parse |> Set.ofList
let private getGuidLanguage (guid:Guid) =
let isCsharp = csharpGuids.Contains(guid)
let isVb = vbGuids.Contains(guid)
let isFsharp = fsharpGuids.Contains(guid)
let isNemerle = nemerleGuids.Contains(guid)
let isIronPython = ironPythonGuids.Contains(guid)
let isServiceFabric = serviceFabric.Contains(guid)
match (isCsharp, isVb, isFsharp, isNemerle, isIronPython) with
| true, false, false, false, false -> Some ProjectLanguage.CSharp
| false, true, false, false, false -> Some ProjectLanguage.VisualBasic
| false, false, true, false, false -> Some ProjectLanguage.FSharp
| false, false, false, true, false -> Some ProjectLanguage.Nemerle
| false, false, false, false, true -> Some ProjectLanguage.IronPython
| _ -> None
let private getLanguageFromExtension = function
| ".csproj" -> Some ProjectLanguage.CSharp
| ".vbproj" -> Some ProjectLanguage.VisualBasic
| ".fsproj" -> Some ProjectLanguage.FSharp
| ".vcxproj" -> Some ProjectLanguage.CPP
| ".wixproj" -> Some ProjectLanguage.WiX
| ".nproj" -> Some ProjectLanguage.Nemerle
| ".pyproj" -> Some ProjectLanguage.IronPython
| ".sfproj" -> Some ProjectLanguage.ServiceFabric
| ".sqlproj" -> Some ProjectLanguage.Sql
| _ -> None
let private getLanguageFromFileName (fileName : string) =
let ext = fileName |> Path.GetExtension
getLanguageFromExtension (ext.ToLowerInvariant())
/// Get the programming language for a project file using the "ProjectTypeGuids"
let getProjectLanguage (projectDocument:XmlDocument) (fileName: string) =
let cons x y = x :: y
let languageGroups =
projectDocument
|> extractProjectTypeGuids
|> List.map getGuidLanguage
|> cons (getLanguageFromFileName fileName)
|> List.choose id
|> List.groupBy id
|> List.map fst
match languageGroups with
| [language] -> language
| _ -> ProjectLanguage.Unknown
/// Contains methods to read and manipulate project files.
type ProjectFile =
{ FileName: string
OriginalText : string
Document : XmlDocument
ProjectNode : XmlNode
Language : ProjectLanguage
// Caches for optimizations
mutable DefaultProperties : Map<string,string> option
// CalculatedMaps for optimizations
mutable CalculatedProperties : System.Collections.Concurrent.ConcurrentDictionary<Map<string,string>, Map<string,string>> }
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module ProjectFile =
let supportedEndings = [ ".csproj"; ".fsproj"; ".vbproj"; ".wixproj"; ".nproj"; ".vcxproj"; ".pyproj"; ".sfproj"; ".proj"; ".sqlproj" ]
let isSupportedFile (fi:FileInfo) =
supportedEndings
|> List.exists fi.Extension.Contains
let name (projectFile:ProjectFile) = FileInfo(projectFile.FileName).Name
let nameWithoutExtension (projectFile:ProjectFile) = Path.GetFileNameWithoutExtension (name projectFile)
let loadFromStream (fullName:string) (stream:Stream) =
let doc = XmlDocument()
doc.Load stream
let manager = XmlNamespaceManager doc.NameTable
manager.AddNamespace ("ns", Constants.ProjectDefaultNameSpace)
let projectNode =
match doc |> getNode "Project" with
| Some node -> node
| _ -> failwithf "unable to find Project node in file %s" fullName
{ FileName = fullName
Document = doc
ProjectNode = projectNode
OriginalText = Utils.normalizeXml doc
Language = LanguageEvaluation.getProjectLanguage doc (Path.GetFileName fullName)
DefaultProperties = None
CalculatedProperties = new System.Collections.Concurrent.ConcurrentDictionary<Map<string,string>, Map<string,string>>()
}
let loadFromFile(fileName:string) =
let fileInfo = FileInfo (normalizePath fileName)
use stream = fileInfo.OpenRead()
loadFromStream fileInfo.FullName stream
let loadFromString (fullName:string) (text:string) =
use stream =
let bytes = text |> Encoding.UTF8.GetBytes
new MemoryStream (bytes)
loadFromStream fullName stream
let tryLoad(fileName:string) =
try
if String.IsNullOrWhiteSpace fileName then None else
let fi = FileInfo fileName
if isSupportedFile fi then
if verbose then
verbosefn "Loading %s" fileName
Some(loadFromFile fileName)
else
None
with
| exn ->
traceWarnfn "Unable to parse project %s:%s %s" fileName Environment.NewLine exn.Message
None
let createNode name (project:ProjectFile) =
try
project.Document.CreateElement (name, project.Document.DocumentElement.NamespaceURI)
with
| _ ->
project.Document.CreateElement (name, Constants.ProjectDefaultNameSpace)
let createNodeSet name text (project:ProjectFile) =
let node = createNode name project
node.InnerText <- text
node
let private getReservedProperties (projectFile:ProjectFile) =
let calculateNew () =
let projectFileInfo = FileInfo projectFile.FileName
let directoryNoRoot = Regex.Replace(projectFileInfo.FullName, "^.:\\\\?", "")
[
// Project file properties
"MSBuildProjectDirectory", projectFileInfo.DirectoryName
"MSBuildProjectDirectoryNoRoot", directoryNoRoot
"MSBuildProjectExtension", projectFileInfo.Extension
"MSBuildProjectFile", projectFileInfo.Name
"MSBuildProjectFullPath", projectFileInfo.FullName
"MSBuildProjectName", Path.GetFileNameWithoutExtension(projectFileInfo.FullName)
// This file properties (Potentially an Imported file)
"MSBuildThisFileDirectory", projectFileInfo.DirectoryName + (string Path.DirectorySeparatorChar)
"MSBuildThisFileDirectoryNoRoot", directoryNoRoot + (string Path.DirectorySeparatorChar)
"MSBuildThisFileExtension", projectFileInfo.Extension
"MSBuildThisFile", projectFileInfo.Name
"MSBuildThisFileFullPath", projectFileInfo.FullName
"MSBuildThisFileName", Path.GetFileNameWithoutExtension(projectFileInfo.FullName)
] |> Map.ofList
match projectFile.DefaultProperties with
| Some p -> p
| None ->
let res = calculateNew()
projectFile.DefaultProperties <- Some res
res
/// Append two maps with the properties of the second replacing properties of the first
let private appendMap first second =
Map.fold (fun state key value -> Map.add key value state) first second
let inline getPackageIdAttribute (pf:ProjectFile) (node:XmlNode) =
let maybePackageId =
node
|> getAttribute "Include"
|> Option.orElseWith (fun _ -> node |> getAttribute "Update")
match maybePackageId with
| Some id -> id
| None -> failwithf "project file '%s' contains a reference without 'Include' or 'Update' attribute" pf.FileName
let private calculatePropertyMap (projectFile:ProjectFile) defaultProperties =
let defaultProperties = appendMap defaultProperties (getReservedProperties projectFile)
let processPlaceholders (data : Map<string, string>) text =
let getPlaceholderValue (name:string) =
// Change "$(Configuration)" to "Configuration",
// then find in the data map
let name = name.Substring(2, name.Length - 3)
match data.TryFind(name) with
| None -> ""
| Some s -> s
let replacePlaceholder (s:string) (m:RegularExpressions.Match) =
let front = s.Substring(0, m.Index)
let value = getPlaceholderValue m.Value
let back = s.Substring(m.Index + m.Length)
front + value + back
// The placeholder name must be a valid XML node name,
// else where would its value be defined?
let regex = @"\$\([a-zA-Z_\-\:][a-zA-Z0-9_\.\-\:]*\)"
RegularExpressions.Regex.Matches(text, regex)
|> fun x -> Seq.cast<RegularExpressions.Match>(x)
|> Seq.toArray
|> Array.rev
|> Array.fold replacePlaceholder text
let rec parseWord (data:StringBuilder) (input:string) index inQuotes =
if input.Length <= index then
if data.Length > 0 && not inQuotes then Some(data.ToString(), index)
else None
else
let c = input.[index]
let gtz = data.Length > 0
match gtz, inQuotes, c with
| false, false, ' ' -> parseWord data input (index + 1) false
| false, false, '\'' -> parseWord data input (index + 1) true
| _, true, '\'' -> Some (string data, index + 1)
| true, false, ' ' -> Some (string data, index + 1)
| _, true, c -> parseWord (data.Append c) input (index + 1) true
| _, false, c -> parseWord (data.Append c) input (index + 1) false
let rec parseComparison (data:StringBuilder) (input:string) index =
let isCompChar c = c = '<' || c = '>' || c = '!' || c = '='
if input.Length <= index then None else
let c = input.[index]
if data.Length = 0 && c = ' 'then
parseComparison data input (index + 1)
elif data.Length = 2 && isCompChar c then
None
elif isCompChar c then
parseComparison (data.Append c) input (index + 1)
else
let s = string data
let valid = [ "=="; "!="; "<"; ">"; "<="; ">=" ]
match (valid |> List.tryFind ((=) s)) with
| None -> None
| Some _ -> Some(s, index)
let parseCondition (data:StringBuilder) (input:string) index =
if input.Length <= index
then None
else
data.Clear() |> ignore
match parseWord data input index false with
| None -> None
| Some(left, index) ->
data.Clear() |> ignore
let comp = parseComparison data input index
match comp with
| None -> None
| Some(comp, index) ->
data.Clear() |> ignore
match parseWord data input index false with
| None -> None
| Some(right, index) ->
Some(left, comp, right, index)
let rec parseAndOr (data:StringBuilder) (input:string) index =
if input.Length <= index then None else
let c = input.[index]
if data.Length = 0 && c = ' '
then parseAndOr data input (index + 1)
elif c <> ' ' then parseAndOr (data.Append c) input (index + 1) else
let s = string data
if s.Equals ("and", StringComparison.OrdinalIgnoreCase) then Some("and", index)
elif s.Equals ("or", StringComparison.OrdinalIgnoreCase) then Some("or", index)
else None
let rec containsMoreText (input:string) index =
if input.Length <= index then false else
match input.[index] with
| ' ' -> containsMoreText input (index + 1)
| _ -> true
let rec parseFullCondition data (sb:StringBuilder) (input:string) index =
if input.Length <= index
then data
else
match data with
| None -> None
| Some data ->
sb.Clear() |> ignore
let andOr, index =
match data with
| [] -> None, index
| _ ->
let moreText = containsMoreText input index
match (parseAndOr sb input index), moreText with
| None, false -> None, index
| Some(andOr, index), _ -> Some andOr, index
| None, true -> failwith "Could not parse condition; multiple conditions found with no \"AND\" or \"OR\" between them."
sb.Clear() |> ignore
let nextCondition = parseCondition sb input index
let moreText = containsMoreText input index
match nextCondition, moreText with
| None, true -> None
| None, false -> Some(data)
| Some(left, comp, right, index), _ ->
let data = Some (data @[(andOr, left, comp, right)])
parseFullCondition data sb input index
let rec handleConditions data xs lastCondition =
match xs with
| [] -> lastCondition
| (cond, left, comp, right)::xs ->
let left = processPlaceholders data left
let right = processPlaceholders data right
let inline doComp l r =
match comp with
| "==" -> l = r
| "!=" -> l <> r
| ">" -> l > r
| "<" -> l < r
| "<=" -> l <= r
| ">=" -> l >= r
| _ -> failwithf "%s is not a valid comparison operator" comp
let result =
match comp with
| "==" | "!=" ->
let eq = left.Equals(right, StringComparison.OrdinalIgnoreCase)
if comp = "=="
then eq
else not eq
| _ ->
match System.Int64.TryParse left, System.Int64.TryParse right with
| (true, l), (true, r) -> doComp l r
| _ -> false
match lastCondition, cond with
| _, None -> handleConditions data xs result
| true, Some "and" -> handleConditions data xs result
| _, Some "or" -> handleConditions data xs (lastCondition || result)
| _ -> false
let conditionMatches data condition =
let allConditions = parseFullCondition (Some []) (StringBuilder()) condition 0
match allConditions with
| None -> false
| Some conditions -> handleConditions data conditions true
let addData data (node:XmlNode) =
let text = processPlaceholders data node.InnerText
let unescapedString = Uri.UnescapeDataString text
// Note that using Map.add overrides the value assigned
// to this key if it already exists in the map; so long
// as we process nodes top-to-bottom, this matches the
// behavior of MSBuild.
Map.add node.Name unescapedString data
let rec handleElement (data : Map<string, string>) (node : XmlNode) =
let handleConditionalElement data node =
match getAttribute "Condition" node with
| None ->
node |> getChildNodes
|> Seq.fold handleElement data
| Some s ->
if not (conditionMatches data s)
then data
elif node.ChildNodes.Count > 0 then
node |> getChildNodes
|> Seq.fold handleElement data
else data
match node.Name with
| "PropertyGroup" -> handleConditionalElement data node
// Don't handle these yet
| "Choose" | "Import" | "ItemGroup" | "ProjectExtensions" | "Target" | "UsingTask" -> data
// Any other node types are intended to be values being defined
| _ ->
match getAttribute "Condition" node with
| None -> addData data node
| Some s ->
if not (conditionMatches data s)
then data
else addData data node
let map =
projectFile.Document
|> getDescendants "PropertyGroup"
|> Seq.fold handleElement defaultProperties
map
let getPropertyWithDefaults propertyName defaultProperties (projectFile:ProjectFile) =
let map = projectFile.CalculatedProperties.GetOrAdd(defaultProperties, calculatePropertyMap projectFile)
Map.tryFind propertyName map
let getProperty propertyName (projectFile:ProjectFile) =
getPropertyWithDefaults propertyName Map.empty<string, string> projectFile
let deleteIfEmpty name (project:ProjectFile) =
let nodesToDelete = List<_>()
for node in project.Document |> getDescendants name do
if node.ChildNodes.Count = 0 then
nodesToDelete.Add node
for node in nodesToDelete do
node.ParentNode.RemoveChild node |> ignore
Seq.isEmpty nodesToDelete |> not
let internal findNodes paketOnes name (project:ProjectFile) = [
for node in project.Document |> getDescendants name do
let mutable isPaketNode = false
for child in node.ChildNodes do
if child.Name = "Paket" && String.equalsIgnoreCase child.InnerText "true" then
isPaketNode <- true
if isPaketNode = paketOnes then yield node
]
let getCustomReferenceAndFrameworkNodes project = (findNodes false "Reference" project) @ (findNodes false "NativeReference" project)
let findPaketNodes name (project:ProjectFile) = findNodes true name project
let getFrameworkAssemblies (project:ProjectFile) = [
for node in project.Document |> getDescendants "Reference" do
let hasHintPath = ref false
for child in node.ChildNodes do
if child.Name = "HintPath" then
hasHintPath := true
if not !hasHintPath then
yield node.Attributes.["Include"].InnerText.Split(',').[0]
]
let deletePaketNodes name (project:ProjectFile) =
let nodesToDelete = findPaketNodes name project
if nodesToDelete |> Seq.isEmpty |> not then
if verbose then
verbosefn " - Deleting Paket %s nodes" name
for node in nodesToDelete do
node.ParentNode.RemoveChild node |> ignore
let updateFileItems (fileItems:FileItem list) (project:ProjectFile) =
let newItemGroups =
let firstItemGroup =
project.ProjectNode
|> getNodes "ItemGroup"
|> List.filter (fun n -> List.isEmpty (getNodes "Reference" n))
|> List.tryHead
match firstItemGroup with
| None ->
let node = createNode "ItemGroup" project
if List.isEmpty fileItems |> not then
project.ProjectNode.AppendChild node |> ignore
[ BuildAction.Content, node
BuildAction.Compile, node
BuildAction.Reference, node
BuildAction.Resource, node
BuildAction.Page, node
]
| Some node ->
[ BuildAction.Content, node :?> XmlElement
BuildAction.Compile, node :?> XmlElement
BuildAction.Reference, node :?> XmlElement
BuildAction.Resource, node :?> XmlElement
BuildAction.Page, node :?> XmlElement
]
|> dict
for fileItem in fileItems |> List.rev do
let libReferenceNode =
let name =
match fileItem.BuildAction with
| BuildAction.Reference ->
fileItem.Include |> normalizePath |> Path.GetFileNameWithoutExtension
| _ -> fileItem.Include
createNode (string fileItem.BuildAction) project
|> addAttribute "Include" name
|> fun node ->
match fileItem.BuildAction with
| BuildAction.Reference ->
node
|> addChild (createNodeSet "HintPath" fileItem.Include project)
|> addChild (createNodeSet "Private" "True" project)
| BuildAction.Page ->
node
|> addChild (createNodeSet "Generator" "MSBuild:Compile" project)
|> addChild (createNodeSet "SubType" "Designer" project)
| _ -> node
|> fun n -> if fileItem.WithPaketSubNode then addChild (createNodeSet "Paket" "True" project) n else n
|> fun n ->
if fileItem.BuildAction <> BuildAction.Content then n else
match fileItem.CopyToOutputDirectory with
| Some CopyToOutputDirectorySettings.Always -> addChild (createNodeSet "CopyToOutputDirectory" "Always" project) n
| Some CopyToOutputDirectorySettings.Never -> addChild (createNodeSet "CopyToOutputDirectory" "Never" project) n
| Some CopyToOutputDirectorySettings.PreserveNewest -> addChild (createNodeSet "CopyToOutputDirectory" "PreserveNewest" project) n
| None -> n
|> fun n ->
match fileItem.Link with
| Some link -> addChild (createNodeSet "Link" (link.Replace("\\","/")) project) n
| _ -> n
let fileItemsInSameDir =
project.Document
|> getDescendants (string fileItem.BuildAction)
|> List.filter (fun node ->
match node |> getAttribute "Include" with
| Some path when path.StartsWith (fileItem.Include |> normalizePath |> Path.GetDirectoryName |> windowsPath) -> true
| _ -> false)
if Seq.isEmpty fileItemsInSameDir then
newItemGroups.[fileItem.BuildAction].PrependChild libReferenceNode |> ignore
else
let existingNode =
fileItemsInSameDir
|> Seq.tryFind (withAttributeValue "Include" fileItem.Include)
match existingNode with
| Some existingNode ->
let parent = existingNode.ParentNode
parent.InsertBefore(libReferenceNode, existingNode) |> ignore
parent.RemoveChild(existingNode) |> ignore
| None ->
let firstNode = fileItemsInSameDir |> Seq.head
firstNode.ParentNode.InsertBefore(libReferenceNode, firstNode) |> ignore
let paketNodes =
BuildAction.PaketFileNodeNames
|> List.collect (fun name -> findPaketNodes name project)
// remove unneeded files
for paketNode in paketNodes do
match getAttribute "Include" paketNode with
| Some path ->
if not (fileItems |> List.exists (fun fi -> fi.Include = path)) then
paketNode.ParentNode.RemoveChild paketNode |> ignore
| _ -> ()
deleteIfEmpty "PropertyGroup" project |> ignore
deleteIfEmpty "ItemGroup" project |> ignore
deleteIfEmpty "When" project |> ignore
deleteIfEmpty "Choose" project |> ignore
let getCustomModelNodes(model:InstallModel) (project:ProjectFile) =
let libs : string Set =
(model.GetAllLegacyReferenceAndFrameworkReferenceNames())
getCustomReferenceAndFrameworkNodes project
|> List.filter (fun node ->
let libName = node.Attributes.["Include"].InnerText.Split(',').[0]
Set.contains libName libs)
let deleteCustomModelNodes (model:InstallModel) (project:ProjectFile) =
let nodesToDelete =
getCustomModelNodes model project
|> List.filter (fun node ->
let mutable isFrameworkNode = true
let mutable isManualNode = false
for child in node.ChildNodes do
if child.Name = "HintPath" then isFrameworkNode <- false
if child.Name = "Private" then isFrameworkNode <- false
if child.Name = "Paket" && String.equalsIgnoreCase child.InnerText "false" then
isManualNode <- true
not isFrameworkNode && not isManualNode)
if nodesToDelete <> [] then
if verbose then
verbosefn " - Deleting custom projects nodes for %O" model.PackageName
for node in nodesToDelete do
node.ParentNode.RemoveChild node |> ignore
let generateAnalyzersXml (model:InstallModel) (project:ProjectFile) =
let createAnalyzersNode (analyzers: AnalyzerLib list) =
let itemGroup = createNode "ItemGroup" project
for lib in analyzers do
let fi = FileInfo (normalizePath lib.Path)
createNode "Analyzer" project
|> addAttribute "Include" (createRelativePath project.FileName fi.FullName)
|> addChild (createNodeSet "Paket" "True" project)
|> itemGroup.AppendChild
|> ignore
itemGroup
let shouldBeInstalled (analyzer : AnalyzerLib) =
match analyzer.Language, project.Language with
| AnalyzerLanguage.Any, projectLanguage -> projectLanguage <> ProjectLanguage.Unknown
| AnalyzerLanguage.CSharp, ProjectLanguage.CSharp -> true
| AnalyzerLanguage.VisualBasic, ProjectLanguage.VisualBasic -> true
| AnalyzerLanguage.FSharp, ProjectLanguage.FSharp -> true
| _ -> false
model.Analyzers
|> List.filter shouldBeInstalled
|> List.sortBy (fun lib -> lib.Path)
|> createAnalyzersNode
type XmlContext = {
GlobalPropsNodes : XmlElement list
GlobalTargetsNodes : XmlElement list
FrameworkSpecificPropsNodes : XmlElement list
FrameworkSpecificTargetsNodes : XmlElement list
ChooseNodes : XmlElement list
FrameworkSpecificPropertyChooseNode : XmlElement
AnalyzersNode : XmlElement
}
let generateXml (model:InstallModel) (usedFrameworkLibs:HashSet<TargetProfile*string>) (aliases:Map<string,string>) (embedInteropTypes:bool option) (copyLocal:bool option) (specificVersion:bool option) (importTargets:bool) (referenceCondition:string option) (allTargetProfiles:Set<TargetProfile>) (project:ProjectFile) : XmlContext =
let references =
getCustomReferenceAndFrameworkNodes project
|> List.map (fun node -> node.Attributes.["Include"].InnerText.Split(',').[0])
|> Set.ofList
let model = model.FilterReferences references
let createItemGroup (targets:TargetProfile Set) (frameworkReferences:FrameworkReference list) (libraries:Library list) =
let itemGroup = createNode "ItemGroup" project
for ref in frameworkReferences |> List.sortBy (fun f -> f.Name) do
createNode "Reference" project
|> addAttribute "Include" ref.Name
|> addChild (createNodeSet "Paket" "True" project)
|> itemGroup.AppendChild
|> ignore
for lib in libraries |> List.sortBy (fun f -> f.Name) do
let fi = FileInfo (normalizePath lib.Path)
let aliases =
aliases
|> Map.tryPick (fun dll alias -> if fi.Name.Equals(dll, StringComparison.OrdinalIgnoreCase) then Some(alias) else None)
let relativePath = createRelativePath project.FileName fi.FullName
let privateSettings =
match copyLocal with
| Some true -> "True"
| Some false -> "False"
| None -> if relativePath.Contains @"\ref\" then "False" else "True"
let specificVersionSettings =
match specificVersion with
| Some true -> "True"
| Some false -> "False"
| None -> "True"
if relativePath.Contains @"\native\" then createNode "NativeReference" project else createNode "Reference" project
|> addAttribute "Include" (fi.Name.Replace(fi.Extension,""))
|> addChild (createNodeSet "HintPath" relativePath project)
|> addChild (createNodeSet "Private" privateSettings project)
|> fun n ->
match specificVersion with
| None -> n
| Some(bool) -> addChild (createNodeSet "SpecificVersion" specificVersionSettings project) n
|> addChild (createNodeSet "Paket" "True" project)
|> fun n ->
match embedInteropTypes with
| None -> n
| _ -> addChild (createNodeSet "EmbedInteropTypes" "True" project) n
|> fun n ->
match aliases with
| None -> n
| Some alias -> addChild (createNodeSet "Aliases" alias project) n
|> itemGroup.AppendChild
|> ignore
itemGroup
let createPropertyGroup (references:MsBuildFile list) =
let propertyGroup = createNode "PropertyGroup" project
let propertyNames =
references
|> Seq.map (fun lib ->
let targetsFile = lib.Path
let fi = FileInfo (normalizePath targetsFile)
let propertyName = "__paket__" + fi.Name.ToString().Replace(" ","_").Replace(".","_")
let path = createRelativePath project.FileName (fi.FullName.Replace (fi.Extension,""))
let s = path.Substring(path.LastIndexOf("build\\") + 6)
let node = createNode propertyName project
node.InnerText <- s
node
|> propertyGroup.AppendChild
|> ignore
propertyName,createRelativePath project.FileName fi.FullName,path.Substring(0,path.LastIndexOf("build\\") + 6))
|> Set.ofSeq
propertyNames,propertyGroup
let allTargets =
model.CompileLibFolders
|> List.map (fun lib -> lib.Targets)
// Just in case anyone wants to compile FOR netcore in the old format...
// I don't think there is anyone actually using this part, but it's there for backwards compat.
let netCoreRestricted =
model.ApplyFrameworkRestrictions
((List.map DotNetCoreApp KnownTargetProfiles.DotNetCoreAppVersions @ List.map DotNetStandard KnownTargetProfiles.DotNetStandardVersions)
|> List.map FrameworkRestriction.Exactly
|> List.fold FrameworkRestriction.combineRestrictionsWithOr FrameworkRestriction.EmptySet)
// handle legacy conditions
let conditions =
(model.CompileLibFolders @ (List.map (FrameworkFolder.map (fun refs -> { ReferenceOrLibraryFolder.empty with Libraries = refs })) netCoreRestricted.CompileRefFolders))
|> List.sortBy (fun libFolder -> libFolder.Path)
|> List.collect (fun libFolder ->
match libFolder with
| _ ->
match PlatformMatching.getCondition referenceCondition libFolder.Targets with
| "" -> []
| condition ->
let condition =
match condition with
| "$(TargetFrameworkIdentifier) == 'true'" -> "true"
| _ -> condition
let frameworkReferences =
libFolder.FolderContents.FrameworkReferences
|> Seq.sortBy (fun r -> r.Name)
|> Seq.toList
let libraries =
libFolder.FolderContents.Libraries
|> Seq.sortBy (fun r -> r.Path)
|> Seq.toList
let assemblyTargets = ref libFolder.Targets
let duplicates = HashSet<_>()
for frameworkAssembly in frameworkReferences do
for t in libFolder.Targets do
if not (usedFrameworkLibs.Add(t,frameworkAssembly.Name)) then
assemblyTargets := Set.remove t !assemblyTargets // List.filter ((<>) t) !assemblyTargets
duplicates.Add frameworkAssembly.Name |> ignore
if !assemblyTargets = libFolder.Targets then
[condition,createItemGroup libFolder.Targets frameworkReferences libraries,false]
else
let specialFrameworkAssemblies, rest =
frameworkReferences
|> List.partition (fun fr -> duplicates.Contains fr.Name)
match PlatformMatching.getCondition referenceCondition !assemblyTargets with
| "" -> [condition,createItemGroup libFolder.Targets rest libraries,false]
| lowerCondition ->
[lowerCondition,createItemGroup !assemblyTargets specialFrameworkAssemblies [],true
condition,createItemGroup libFolder.Targets rest libraries,false]
)
// global targets are targets, that are either directly in the /build folder.
// (ref https://docs.microsoft.com/en-us/nuget/create-packages/creating-a-package#including-msbuild-props-and-targets-in-a-package).
let globalTargets, frameworkSpecificTargets =
if not importTargets then Seq.empty, List.empty else
let globalTargets = model.TargetsFileFolders |> Seq.collect (fun f -> f.RootContents)
let frameworkSpecificTargets = model.TargetsFileFolders |> List.collect (fun f -> f.FrameworkFolders)
globalTargets,frameworkSpecificTargets
let frameworkSpecificTargetsFileConditions =
frameworkSpecificTargets
|> List.map (fun lib -> PlatformMatching.getCondition referenceCondition lib.Targets,createPropertyGroup (lib.FolderContents |> List.ofSeq))
let chooseNodes =
match conditions with
| ["$(TargetFrameworkIdentifier) == 'true'",itemGroup,_] -> [itemGroup]
| ["true",itemGroup,_] -> [itemGroup]
| _ ->
let chooseNode = createNode "Choose" project
let chooseNode2 = createNode "Choose" project
let containsReferences = ref false
let containsReferences2 = ref false
let nodes =
conditions
|> List.map (fun (condition,itemGroup,ownNode) ->
let condition =
match condition with
| "$(TargetFrameworkIdentifier) == 'true'" -> "true"
| _ -> condition
let whenNode =
createNode "When" project
|> addAttribute "Condition" condition
if not itemGroup.IsEmpty then
whenNode.AppendChild itemGroup |> ignore
if ownNode then
containsReferences2 := true
else
containsReferences := true
whenNode,ownNode)
for node,ownNode in nodes do
if ownNode then
chooseNode2.AppendChild node |> ignore
else
chooseNode.AppendChild node |> ignore
match !containsReferences,!containsReferences2 with
| true,true -> [chooseNode2; chooseNode]
| true,false -> [chooseNode]
| false,true -> [chooseNode2]
| false,false -> [createNode "Choose" project]
let frameworkSpecificPropertyNames,frameworkSpecificPropertyChooseNode =
match frameworkSpecificTargetsFileConditions with
| ["$(TargetFrameworkIdentifier) == 'true'",(propertyNames,propertyGroup)] ->
[propertyNames], createNode "Choose" project
| ["true",(propertyNames,propertyGroup)] ->
[propertyNames], createNode "Choose" project
| _ ->
let propertyChooseNode = createNode "Choose" project
let containsProperties = ref false
let nodes =
frameworkSpecificTargetsFileConditions
|> List.map (fun (condition,(propertyNames,propertyGroup)) ->
let finalCondition = if condition = "" || condition.Length > 3000 || condition = "$(TargetFrameworkIdentifier) == 'true'" then "1 == 1" else condition
let whenNode =
createNode "When" project
|> addAttribute "Condition" finalCondition
if not (Set.isEmpty propertyNames) then
whenNode.AppendChild(propertyGroup) |> ignore
containsProperties := true
whenNode)
for node in nodes do
propertyChooseNode.AppendChild node |> ignore
(frameworkSpecificTargetsFileConditions |> List.map (fun (_,(propertyNames,_)) -> propertyNames)),
(if !containsProperties then propertyChooseNode else createNode "Choose" project)
let frameworkSpecificPropsNodes =
frameworkSpecificPropertyNames
|> Seq.concat
|> Seq.distinctBy (fun (x,_,_) -> x)
|> Seq.filter (fun (propertyName,path,buildPath) -> String.endsWithIgnoreCase "props" propertyName)
|> Seq.map (fun (propertyName,path,buildPath) ->
let fileName =
match propertyName with
| _ when frameworkSpecificPropertyChooseNode.ChildNodes.Count = 0 -> path
| name when String.endsWithIgnoreCase "props" name -> sprintf "%s$(%s).props" buildPath propertyName
| _ -> failwithf "Unknown .props filename %s" propertyName
createNode "Import" project
|> addAttribute "Project" fileName
|> addAttribute "Condition" (sprintf "Exists('%s')" fileName)
|> addAttribute "Label" "Paket")
|> Seq.toList
let frameworkSpecificTargetsNodes =
frameworkSpecificPropertyNames
|> Seq.concat
|> Seq.distinctBy (fun (x,_,_) -> x)
|> Seq.filter (fun (propertyName,path,buildPath) -> String.endsWithIgnoreCase "props" propertyName |> not)
|> Seq.map (fun (propertyName,path,buildPath) ->
let fileName =
match propertyName with
| _ when frameworkSpecificPropertyChooseNode.ChildNodes.Count = 0 -> path
| name when String.endsWithIgnoreCase "targets" name ->
sprintf "%s$(%s).targets" buildPath propertyName
| _ -> failwithf "Unknown .targets filename %s" propertyName
createNode "Import" project
|> addAttribute "Project" fileName
|> addAttribute "Condition" (sprintf "Exists('%s')" fileName)
|> addAttribute "Label" "Paket")
|> Seq.toList
let globalPropsNodes =
globalTargets
|> Seq.map (fun t -> t.Path)
|> Seq.distinct
|> Seq.filter (fun t -> String.endsWithIgnoreCase ".props" t)
|> Seq.map (fun t ->
let fileName = createRelativePath project.FileName t
createNode "Import" project
|> addAttribute "Project" fileName
|> addAttribute "Condition" (sprintf "Exists('%s')" fileName)
|> addAttribute "Label" "Paket")
|> Seq.toList
let globalTargetsNodes =