forked from fsprojects/Paket
/
ProjectFile.fs
1408 lines (1163 loc) · 62.3 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 System
open System.IO
open System.Xml
open System.Collections.Generic
open Paket.Xml
open Paket.Requirements
[<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
GUID : Guid }
/// Compile items inside of project files.
type CompileItem =
{ SourceFile : string
DestinationPath : string
BaseDir : string }
/// Project output type.
[<RequireQualifiedAccess>]
type ProjectOutputType =
| Exe
| Library
type ProjectLanguage = Unknown | CSharp | FSharp | VisualBasic | WiX | Nemerle | CPP
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 getGuidLanguage (guid:Guid) =
let isCsharp = csharpGuids.Contains(guid)
let isVb = vbGuids.Contains(guid)
let isFsharp = fsharpGuids.Contains(guid)
let isNemerle = nemerleGuids.Contains(guid)
match (isCsharp, isVb, isFsharp, isNemerle) with
| (true, false, false, false) -> Some CSharp
| (false, true, false, false) -> Some VisualBasic
| (false, false, true, false) -> Some FSharp
| (false, false, false, true) -> Some Nemerle
| _ -> None
let private getLanguageFromExtension = function
| ".csproj" -> Some CSharp
| ".vbproj" -> Some VisualBasic
| ".fsproj" -> Some FSharp
| ".vcxproj" -> Some CPP
| ".wixproj" -> Some WiX
| ".nproj" -> Some Nemerle
| _ -> 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
| _ -> Unknown
/// Contains methods to read and manipulate project files.
type ProjectFile =
{ FileName: string
OriginalText : string
Document : XmlDocument
ProjectNode : XmlNode
Language : ProjectLanguage }
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module ProjectFile =
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)
}
let loadFromFile(fileName:string) =
let fileInfo = FileInfo (normalizePath fileName)
use stream = fileInfo.OpenRead()
loadFromStream fileInfo.FullName stream
let tryLoad(fileName:string) =
try
Some(loadFromFile fileName)
with
| exn ->
traceWarnfn "Unable to parse %s:%s %s" fileName Environment.NewLine exn.Message
None
let tryFindProject (projects: ProjectFile seq) projectName =
match projects |> Seq.tryFind (fun p -> nameWithoutExtension p = projectName || name p = projectName) with
| Some p -> Some p
| None ->
try
let fi = FileInfo (normalizePath (projectName.Trim().Trim([|'\"'|]))) // check if we can detect the path
let rec checkDir (dir:DirectoryInfo) =
match projects |> Seq.tryFind (fun p ->
String.equalsIgnoreCase ((FileInfo p.FileName).Directory.ToString()) (dir.ToString())) with
| Some p -> Some p
| None ->
if isNull dir.Parent then None else
checkDir dir.Parent
checkDir fi.Directory
with
| _ -> None
/// Finds all project files
let findAllProjects folder =
let packagesPath = Path.Combine(folder,Constants.PackagesFolderName) |> normalizePath
let paketPath = Path.Combine(folder,Constants.PaketFilesFolderName) |> normalizePath
let findAllFiles (folder, pattern) =
let rec search (di:DirectoryInfo) =
try
let files = di.GetFiles(pattern, SearchOption.TopDirectoryOnly)
di.GetDirectories()
|> Array.filter (fun di ->
try
let path = di.FullName |> normalizePath
if path = packagesPath then false else
if path = paketPath then false else
Path.Combine(path, Constants.DependenciesFileName)
|> File.Exists
|> not
with
| _ -> false)
|> Array.collect search
|> Array.append files
with
| _ -> Array.empty
search <| DirectoryInfo folder
findAllFiles(folder, "*.*proj")
|> Array.filter (fun f -> f.Extension = ".csproj" || f.Extension = ".fsproj" || f.Extension = ".vbproj" || f.Extension = ".wixproj" || f.Extension = ".nproj" || f.Extension = ".vcxproj")
|> Array.choose (fun fi -> tryLoad fi.FullName)
let createNode name (project:ProjectFile) =
project.Document.CreateElement (name, Constants.ProjectDefaultNameSpace)
let createNodeSet name text (project:ProjectFile) =
let node = createNode name project
node.InnerText <- text
node
open System.Text
let getPropertyWithDefaults propertyName defaultProperties (projectFile: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:System.Text.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:System.Text.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:System.Text.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
| "==" | "!=" -> doComp left right
| _ ->
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
// 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 text 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.tryFind propertyName map
let getProperty propertyName (projectFile:ProjectFile) =
getPropertyWithDefaults propertyName Map.empty<string, string> projectFile
let findCorrespondingFile (projectFile:FileInfo) (correspondingFile:string) =
let specificFile = FileInfo (Path.Combine(projectFile.Directory.FullName, projectFile.Name + "." + correspondingFile))
if specificFile.Exists then Some specificFile.FullName else
let rec findInDir (currentDir:DirectoryInfo) =
let generalFile = FileInfo(Path.Combine(currentDir.FullName, correspondingFile))
if generalFile.Exists then Some generalFile.FullName
elif (FileInfo (Path.Combine(currentDir.FullName, Constants.DependenciesFileName))).Exists then None
elif currentDir.Parent = null then None
else findInDir currentDir.Parent
findInDir projectFile.Directory
let findReferencesFile (projectFile:FileInfo) = findCorrespondingFile projectFile Constants.ReferencesFile
let findTemplatesFile (projectFile:FileInfo) = findCorrespondingFile projectFile Constants.TemplateFile
let findOrCreateReferencesFile (projectFile : FileInfo) =
match findReferencesFile projectFile with
| None ->
let newFileName =
let fi = FileInfo(Path.Combine(projectFile.Directory.FullName,Constants.ReferencesFile))
if fi.Exists then
Path.Combine(projectFile.Directory.FullName,projectFile.Name + "." + Constants.ReferencesFile)
else
fi.FullName
ReferencesFile.New newFileName
| Some fileName -> ReferencesFile.FromFile fileName
let hasPackageInstalled groupName (package:PackageName) (project:ProjectFile) =
let proj = FileInfo project.FileName
match findReferencesFile proj with
| None -> false
| Some fileName ->
let referencesFile = ReferencesFile.FromFile fileName
referencesFile.Groups.[groupName].NugetPackages
|> Seq.exists (fun p -> p.Name = package)
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 isPaketNode = ref 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
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
verbosefn " - Deleting Paket %s nodes" name
for node in nodesToDelete do
node.ParentNode.RemoveChild node |> ignore
let updateFileItems (fileItems:FileItem list) hard (project:ProjectFile) =
let newItemGroups =
let firstItemGroup = project.ProjectNode |> getNodes "ItemGroup" |> List.tryHead
match firstItemGroup with
| None ->
[BuildAction.Content, createNode "ItemGroup" project
BuildAction.Compile, createNode "ItemGroup" project
BuildAction.Reference, createNode "ItemGroup" project
BuildAction.Resource, createNode "ItemGroup" project
BuildAction.Page, createNode "ItemGroup" project ]
| 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 ->
let n = FileInfo(fileItem.Include).Name.TrimEnd('\\').Split('\\') |> Array.last
n.Replace(Path.GetExtension n,"")
| _ -> 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 -> 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 (Path.GetDirectoryName fileItem.Include) -> 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 ->
match existingNode.ChildNodes |> Seq.cast<XmlNode> |> Seq.tryFind (fun n -> n.Name = "Paket") with
| None when hard ->
let parent = existingNode.ParentNode
parent.InsertBefore(libReferenceNode, existingNode) |> ignore
parent.RemoveChild(existingNode) |> ignore
| Some _ ->
let parent = existingNode.ParentNode
parent.InsertBefore(libReferenceNode, existingNode) |> ignore
parent.RemoveChild(existingNode) |> ignore
| None -> verbosefn " - custom nodes for %s in %s ==> skipping" fileItem.Include project.FileName
| None ->
let firstNode = fileItemsInSameDir |> Seq.head
firstNode.ParentNode.InsertBefore(libReferenceNode, firstNode) |> ignore
let paketNodes =
BuildAction.PaketFileNodeNames
|> List.map (fun name -> findPaketNodes name project)
|> List.concat
// 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 =
model.GetLibReferencesLazy.Force()
|> Set.map (fun lib -> lib.ReferenceName)
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 isFrameworkNode = ref true
for child in node.ChildNodes do
if child.Name = "HintPath" then isFrameworkNode := false
if child.Name = "Private" then isFrameworkNode := false
not !isFrameworkNode)
if nodesToDelete <> [] 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
let generateXml (model:InstallModel) (copyLocal:bool) (importTargets:bool) (referenceCondition:string option) (project:ProjectFile) =
let references =
getCustomReferenceAndFrameworkNodes project
|> List.map (fun node -> node.Attributes.["Include"].InnerText.Split(',').[0])
|> Set.ofList
let model = model.FilterReferences references
let createItemGroup references =
let itemGroup = createNode "ItemGroup" project
for lib in references do
match lib with
| Reference.Library lib ->
let fi = FileInfo (normalizePath lib)
createNode "Reference" project
|> addAttribute "Include" (fi.Name.Replace(fi.Extension,""))
|> addChild (createNodeSet "HintPath" (createRelativePath project.FileName fi.FullName) project)
|> addChild (createNodeSet "Private" (if copyLocal then "True" else "False") project)
|> addChild (createNodeSet "Paket" "True" project)
|> itemGroup.AppendChild
|> ignore
| Reference.FrameworkAssemblyReference frameworkAssembly ->
createNode "Reference" project
|> addAttribute "Include" frameworkAssembly
|> addChild (createNodeSet "Paket" "True" project)
|> itemGroup.AppendChild
|> ignore
| Reference.TargetsFile _ -> ()
itemGroup
let createPropertyGroup references =
let propertyGroup = createNode "PropertyGroup" project
let propertyNames =
references
|> Seq.choose (fun lib ->
if not importTargets then None else
match lib with
| Reference.Library _ -> None
| Reference.FrameworkAssemblyReference _ -> None
| Reference.TargetsFile targetsFile ->
let fi = new 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
Some(propertyName,createRelativePath project.FileName fi.FullName,path.Substring(0,path.LastIndexOf("build\\") + 6)))
|> Set.ofSeq
propertyNames,propertyGroup
let conditions =
model.ReferenceFileFolders
|> List.map (fun lib -> PlatformMatching.getCondition referenceCondition lib.Targets,createItemGroup lib.Files.References)
|> List.sortBy fst
let targetsFileConditions =
model.TargetsFileFolders
|> List.map (fun lib -> PlatformMatching.getCondition referenceCondition lib.Targets,createPropertyGroup lib.Files.References)
|> List.sortBy fst
let chooseNode =
match conditions with
| ["$(TargetFrameworkIdentifier) == 'true'",itemGroup] -> itemGroup
| ["true",itemGroup] -> itemGroup
| _ ->
let chooseNode = createNode "Choose" project
let containsReferences = ref false
conditions
|> List.map (fun (condition,itemGroup) ->
let whenNode =
createNode "When" project
|> addAttribute "Condition" condition
if not itemGroup.IsEmpty then
whenNode.AppendChild itemGroup |> ignore
containsReferences := true
whenNode)
|> List.iter (fun node -> chooseNode.AppendChild node |> ignore)
if !containsReferences then chooseNode else createNode "Choose" project
let propertyNames,propertyChooseNode =
match targetsFileConditions 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
targetsFileConditions
|> List.map (fun (condition,(propertyNames,propertyGroup)) ->
let whenNode =
createNode "When" project
|> addAttribute "Condition" condition
if not <| Set.isEmpty propertyNames then
whenNode.AppendChild(propertyGroup) |> ignore
containsProperties := true
whenNode)
|> List.iter(fun node -> propertyChooseNode.AppendChild node |> ignore)
(targetsFileConditions |> List.map (fun (_,(propertyNames,_)) -> propertyNames)),
(if !containsProperties then propertyChooseNode else createNode "Choose" project)
let propsNodes =
propertyNames
|> 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 propertyChooseNode.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 targetsNodes =
propertyNames
|> 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 propertyChooseNode.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 analyzersNode = generateAnalyzersXml model project
propsNodes,targetsNodes,chooseNode,propertyChooseNode,analyzersNode
let removePaketNodes (project:ProjectFile) =
deletePaketNodes "Analyzer" project
deletePaketNodes "Reference" project
let rec getPaketNodes (node:XmlNode) =
[for node in node.ChildNodes do
if node.Name.Contains "__paket__" ||
(node.Name = "Import" && match node |> getAttribute "Project" with Some v -> v.Contains "__paket__" | None -> false) ||
(node |> withAttributeValue "Label" "Paket")
then
yield node
yield! getPaketNodes node]
for node in getPaketNodes project.Document do
let parent = node.ParentNode
try
node.ParentNode.RemoveChild node |> ignore
with
| _ -> ()
try
if parent.ChildNodes.Count = 0 then
parent.ParentNode.RemoveChild parent |> ignore
with
| _ -> ()
while List.exists (fun x -> deleteIfEmpty x project) ["ItemGroup";"When";"Otherwise";"Choose"] do
()
let getTargetFrameworkIdentifier (project:ProjectFile) = getProperty "TargetFrameworkIdentifier" project
let getTargetFrameworkProfile (project:ProjectFile) = getProperty "TargetFrameworkProfile" project
let getTargetFramework (project:ProjectFile) =
match getProperty "TargetFrameworkVersion" project with
| None -> None
| Some v -> FrameworkDetection.Extract(v.Replace("v","net"))
let updateReferences
(completeModel: Map<GroupName*PackageName,_*InstallModel>)
(usedPackages : Map<GroupName*PackageName,_*InstallSettings>) hard (project:ProjectFile) =
removePaketNodes project
completeModel
|> Seq.filter (fun kv -> usedPackages.ContainsKey kv.Key)
|> Seq.map (fun kv ->
if hard then
deleteCustomModelNodes (snd kv.Value) project
let installSettings = snd usedPackages.[kv.Key]
let projectModel =
(snd kv.Value)
.ApplyFrameworkRestrictions(installSettings.FrameworkRestrictions|> getRestrictionList)
.RemoveIfCompletelyEmpty()
match getTargetFramework project with
| Some targetFramework ->
if projectModel.GetLibReferences targetFramework |> Seq.isEmpty then
let libReferences =
projectModel.GetLibReferencesLazy |> force
|> Seq.filter (fun l -> match l with | Reference.Library _ -> true | _ -> false)
if not (Seq.isEmpty libReferences) then
traceWarnfn "Package %O contains libraries, but not for the selected TargetFramework %O in project %s."
(snd kv.Key) targetFramework project.FileName
| None -> ()
let copyLocal = defaultArg installSettings.CopyLocal true
let importTargets = defaultArg installSettings.ImportTargets true
generateXml projectModel copyLocal importTargets installSettings.ReferenceCondition project)
|> Seq.iter (fun (propsNodes,targetsNodes,chooseNode,propertyChooseNode, analyzersNode) ->
let i = ref (project.ProjectNode.ChildNodes.Count-1)
while
!i >= 0 &&
(String.startsWithIgnoreCase "<import" (project.ProjectNode.ChildNodes.[!i].OuterXml.ToString()) &&
String.containsIgnoreCase "label" (project.ProjectNode.ChildNodes.[!i].OuterXml.ToString()) &&
String.containsIgnoreCase "paket" (project.ProjectNode.ChildNodes.[!i].OuterXml.ToString()) ) do
decr i
if !i <= 0 then
if chooseNode.ChildNodes.Count > 0 then
project.ProjectNode.AppendChild chooseNode |> ignore
else
let node = project.ProjectNode.ChildNodes.[!i]
if chooseNode.ChildNodes.Count > 0 then
project.ProjectNode.InsertAfter(chooseNode,node) |> ignore
let j = ref 0
while !j < project.ProjectNode.ChildNodes.Count && String.startsWithIgnoreCase "<import" (project.ProjectNode.ChildNodes.[!j].OuterXml.ToString()) do
incr j
let k = ref !j
while !k < project.ProjectNode.ChildNodes.Count &&
(String.startsWithIgnoreCase "<PropertyGroup" (project.ProjectNode.ChildNodes.[!k].OuterXml.ToString()) ||
(String.startsWithIgnoreCase "<import" (project.ProjectNode.ChildNodes.[!k].OuterXml.ToString()) &&
not (String.containsIgnoreCase "label" (project.ProjectNode.ChildNodes.[!k].OuterXml.ToString()) &&
String.containsIgnoreCase "paket" (project.ProjectNode.ChildNodes.[!k].OuterXml.ToString())))) do
incr k
let addProps() =
if !j = 0 then
propsNodes
|> Seq.iter (project.ProjectNode.PrependChild >> ignore)
else
propsNodes
|> Seq.iter (fun n -> project.ProjectNode.InsertAfter(n,project.ProjectNode.ChildNodes.[!j-1]) |> ignore)
if propertyChooseNode.ChildNodes.Count > 0 then
if !k = 0 then
project.ProjectNode.AppendChild propertyChooseNode |> ignore
propsNodes
|> Seq.iter (project.ProjectNode.AppendChild >> ignore)
else
let node = project.ProjectNode.ChildNodes.[!k-1]
propsNodes
|> Seq.iter (fun n -> project.ProjectNode.InsertAfter(n,node) |> ignore)
project.ProjectNode.InsertAfter(propertyChooseNode,node) |> ignore
else
addProps()
targetsNodes
|> Seq.iter (project.ProjectNode.AppendChild >> ignore)
if analyzersNode.ChildNodes.Count > 0 then
project.ProjectNode.AppendChild analyzersNode |> ignore
)
let save forceTouch project =
if Utils.normalizeXml project.Document <> project.OriginalText || not (File.Exists(project.FileName)) then
verbosefn "Project %s changed" project.FileName
project.Document.Save(project.FileName)
elif forceTouch then
File.SetLastWriteTimeUtc(project.FileName, DateTime.UtcNow)
let getPaketFileItems project =
BuildAction.PaketFileNodeNames
|> List.map (fun name -> findPaketNodes name project)
|> List.concat
|> List.map (fun n -> FileInfo(Path.Combine(Path.GetDirectoryName project.FileName, n.Attributes.["Include"].Value)))