-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ProjectRootElement.cs
2128 lines (1812 loc) · 91.2 KB
/
ProjectRootElement.cs
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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using Microsoft.Build.Collections;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Eventing;
using Microsoft.Build.Framework;
using Microsoft.Build.Internal;
using Microsoft.Build.ObjectModelRemoting;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.Construction
{
/// <summary>
/// Event handler for the event fired after this project file is named or renamed.
/// If the project file has not previously had a name, oldFullPath is null.
/// </summary>
internal delegate void RenameHandlerDelegate(string oldFullPath);
/// <summary>
/// ProjectRootElement class represents an MSBuild project, an MSBuild targets file or any other file that conforms to MSBuild
/// project file schema.
/// This class and its related classes allow a complete MSBuild project or targets file to be read and written.
/// Comments and whitespace cannot be edited through this model at present.
///
/// Each project root element is associated with exactly one ProjectCollection. This allows the owner of that project collection
/// to control its lifetime and not be surprised by edits via another project collection.
/// </summary>
[DebuggerDisplay("{FullPath} #Children={Count} DefaultTargets={DefaultTargets} ToolsVersion={ToolsVersion} InitialTargets={InitialTargets} ExplicitlyLoaded={IsExplicitlyLoaded}")]
public class ProjectRootElement : ProjectElementContainer
{
/// Constants for default (empty) project file.
private const string EmptyProjectFileContent = "{0}<Project{1}{2}>\r\n</Project>";
private const string EmptyProjectFileXmlDeclaration = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
private const string EmptyProjectFileToolsVersion = " ToolsVersion=\"" + MSBuildConstants.CurrentToolsVersion + "\"";
internal const string EmptyProjectFileXmlNamespace = " xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"";
/// <summary>
/// The singleton delegate that loads projects into the ProjectRootElement
/// </summary>
private static readonly ProjectRootElementCacheBase.OpenProjectRootElement s_openLoaderDelegate = OpenLoader;
private static readonly ProjectRootElementCacheBase.OpenProjectRootElement s_openLoaderPreserveFormattingDelegate = OpenLoaderPreserveFormatting;
/// <summary>
/// Used to determine if a file is an empty XML file if it ONLY contains an XML declaration like <?xml version="1.0" encoding="utf-8"?>.
/// </summary>
private static readonly Lazy<Regex> XmlDeclarationRegEx = new Lazy<Regex>(() => new Regex(@"\A\s*\<\?\s*xml.*\?\>\s*\Z"), isThreadSafe: true);
/// <summary>
/// The default encoding to use / assume for a new project.
/// </summary>
private static readonly Encoding s_defaultEncoding = Encoding.UTF8;
/// <summary>
/// A global counter used to ensure each project version is distinct from every other.
/// </summary>
/// <remarks>
/// This number is static so that it is unique across the appdomain. That is so that a host
/// can know when a ProjectRootElement has been unloaded (perhaps after modification) and
/// reloaded -- the version won't reset to '0'.
/// </remarks>
private static int s_globalVersionCounter;
private int _version;
/// <summary>
/// Version number of this object that was last saved to disk, or last loaded from disk.
/// Used to figure whether this object is dirty for saving.
/// Saving to or loading from a provided stream reader does not modify this value, only saving to or loading from disk.
/// The actual value is meaningless (since the counter is shared with all projects) --
/// it should only be compared to a stored value.
/// Immediately after loading from disk, this has the same value as <see cref="Version">version</see>.
/// </summary>
private int _versionOnDisk;
/// <summary>
/// The encoding of the project that was (if applicable) loaded off disk, and that will be used to save the project.
/// </summary>
/// <value>Defaults to UTF8 for new projects.</value>
private Encoding _encoding;
/// <summary>
/// XML namespace specified and used by this project file. If a namespace was not specified in the project file, this
/// value will be string.Empty.
/// </summary>
internal string XmlNamespace { get; set; }
/// <summary>
/// The project file's location. It can be null if the project is not directly loaded from a file.
/// </summary>
private ElementLocation _projectFileLocation;
/// <summary>
/// The project file's full path, escaped.
/// </summary>
private string _escapedFullPath;
/// <summary>
/// The directory that the project is in.
/// Essential for evaluating relative paths.
/// If the project is not loaded from disk, returns the current-directory from
/// the time the project was loaded - this is the same behavior as Whidbey/Orcas.
/// </summary>
private string _directory;
/// <summary>
/// The time that this object was last changed. If it hasn't
/// been changed since being loaded or created, its value is <see cref="DateTime.MinValue"/>.
/// Stored as UTC as this is faster when there are a large number of rapid edits.
/// </summary>
private DateTime _timeLastChangedUtc;
/// <summary>
/// The last-write-time of the file that was read, when it was read.
/// This can be used to see whether the file has been changed on disk
/// by an external means.
/// </summary>
private DateTime _lastWriteTimeWhenReadUtc;
/// <summary>
/// Reason it was last marked dirty; unlocalized, for debugging
/// </summary>
private string _dirtyReason = "first created project {0}";
/// <summary>
/// Parameter to be formatted into the dirty reason
/// </summary>
private string _dirtyParameter = String.Empty;
internal ProjectRootElementLink RootLink => (ProjectRootElementLink)Link;
/// <summary>
/// External projects support
/// </summary>
internal ProjectRootElement(ProjectRootElementLink link)
: base(link)
{
}
/// <summary>
/// Initialize a ProjectRootElement instance from a XmlReader.
/// May throw InvalidProjectFileException.
/// Leaves the project dirty, indicating there are unsaved changes.
/// Used to create a root element for solutions loaded by the 3.5 version of the solution wrapper.
/// </summary>
internal ProjectRootElement(XmlReader xmlReader, ProjectRootElementCacheBase projectRootElementCache, bool isExplicitlyLoaded,
bool preserveFormatting)
{
ErrorUtilities.VerifyThrowArgumentNull(xmlReader, nameof(xmlReader));
ErrorUtilities.VerifyThrowArgumentNull(projectRootElementCache, nameof(projectRootElementCache));
IsExplicitlyLoaded = isExplicitlyLoaded;
ProjectRootElementCache = projectRootElementCache;
_directory = NativeMethodsShared.GetCurrentDirectory();
IncrementVersion();
XmlDocumentWithLocation document = LoadDocument(xmlReader, preserveFormatting);
ProjectParser.Parse(document, this);
}
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later.
/// Leaves the project dirty, indicating there are unsaved changes.
/// </summary>
private ProjectRootElement(ProjectRootElementCacheBase projectRootElementCache, NewProjectFileOptions projectFileOptions)
{
ErrorUtilities.VerifyThrowArgumentNull(projectRootElementCache, nameof(projectRootElementCache));
ProjectRootElementCache = projectRootElementCache;
_directory = NativeMethodsShared.GetCurrentDirectory();
IncrementVersion();
var document = new XmlDocumentWithLocation();
var xrs = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore };
var emptyProjectFile = string.Format(EmptyProjectFileContent,
(projectFileOptions & NewProjectFileOptions.IncludeXmlDeclaration) != 0 ? EmptyProjectFileXmlDeclaration : string.Empty,
(projectFileOptions & NewProjectFileOptions.IncludeToolsVersion) != 0 ? EmptyProjectFileToolsVersion : string.Empty,
(projectFileOptions & NewProjectFileOptions.IncludeXmlNamespace) != 0 ? EmptyProjectFileXmlNamespace : string.Empty);
using (XmlReader xr = XmlReader.Create(new StringReader(emptyProjectFile), xrs))
{
document.Load(xr);
}
ProjectParser.Parse(document, this);
}
/// <summary>
/// Initialize a ProjectRootElement instance over a project with the specified file path.
/// Assumes path is already normalized.
/// May throw InvalidProjectFileException.
/// </summary>
private ProjectRootElement(string path, ProjectRootElementCacheBase projectRootElementCache,
bool preserveFormatting)
{
ErrorUtilities.VerifyThrowArgumentLength(path, nameof(path));
ErrorUtilities.VerifyThrowInternalRooted(path);
ErrorUtilities.VerifyThrowArgumentNull(projectRootElementCache, nameof(projectRootElementCache));
ProjectRootElementCache = projectRootElementCache;
IncrementVersion();
_versionOnDisk = Version;
_timeLastChangedUtc = DateTime.UtcNow;
XmlDocumentWithLocation document = LoadDocument(path, preserveFormatting, projectRootElementCache.LoadProjectsReadOnly);
ProjectParser.Parse(document, this);
projectRootElementCache.AddEntry(this);
}
/// <summary>
/// Initialize a ProjectRootElement instance from an existing document.
/// May throw InvalidProjectFileException.
/// Leaves the project dirty, indicating there are unsaved changes.
/// </summary>
/// <remarks>
/// Do not make public: we do not wish to expose particular XML API's.
/// </remarks>
private ProjectRootElement(XmlDocumentWithLocation document, ProjectRootElementCacheBase projectRootElementCache)
{
ErrorUtilities.VerifyThrowArgumentNull(document, nameof(document));
ErrorUtilities.VerifyThrowArgumentNull(projectRootElementCache, nameof(projectRootElementCache));
ProjectRootElementCache = projectRootElementCache;
_directory = NativeMethodsShared.GetCurrentDirectory();
IncrementVersion();
ProjectParser.Parse(document, this);
}
/// <summary>
/// Initialize a ProjectRootElement instance from an existing document.
/// Helper constructor for the <see cref="ReloadFrom(string,bool,System.Nullable{bool})"/>> mehtod which needs to check if the document parses
/// </summary>
/// <remarks>
/// Do not make public: we do not wish to expose particular XML API's.
/// </remarks>
private ProjectRootElement(XmlDocumentWithLocation document)
{
ProjectParser.Parse(document, this);
}
/// <summary>
/// Event raised after this project is renamed
/// </summary>
internal event RenameHandlerDelegate OnAfterProjectRename;
/// <summary>
/// Event raised after the project XML is changed.
/// </summary>
internal event EventHandler<ProjectXmlChangedEventArgs> OnProjectXmlChanged;
/// <summary>
/// Condition should never be set, but the getter returns null instead of throwing
/// because a nonexistent condition is implicitly true
/// </summary>
public override string Condition
{
get => null;
set => ErrorUtilities.ThrowInvalidOperation("OM_CannotGetSetCondition");
}
#region ChildEnumerators
/// <summary>
/// Get a read-only collection of the child chooses, if any
/// </summary>
/// <remarks>
/// The name is inconsistent to make it more understandable, per API review.
/// </remarks>
public ICollection<ProjectChooseElement> ChooseElements => new ReadOnlyCollection<ProjectChooseElement>(Children.OfType<ProjectChooseElement>());
/// <summary>
/// Get a read-only collection of the child item definition groups, if any
/// </summary>
public ICollection<ProjectItemDefinitionGroupElement> ItemDefinitionGroups => new ReadOnlyCollection<ProjectItemDefinitionGroupElement>(Children.OfType<ProjectItemDefinitionGroupElement>());
/// <summary>
/// Get a read-only collection of the child item definitions, if any, in all item definition groups anywhere in the project file.
/// </summary>
public ICollection<ProjectItemDefinitionElement> ItemDefinitions => new ReadOnlyCollection<ProjectItemDefinitionElement>(AllChildren.OfType<ProjectItemDefinitionElement>());
/// <summary>
/// Get a read-only collection over the child item groups, if any.
/// Does not include any that may not be at the root, i.e. inside Choose elements.
/// </summary>
public ICollection<ProjectItemGroupElement> ItemGroups => new ReadOnlyCollection<ProjectItemGroupElement>(Children.OfType<ProjectItemGroupElement>());
/// <summary>
/// Get a read-only collection of the child items, if any, in all item groups anywhere in the project file.
/// Not restricted to root item groups: traverses through Choose elements.
/// </summary>
public ICollection<ProjectItemElement> Items => new ReadOnlyCollection<ProjectItemElement>(AllChildren.OfType<ProjectItemElement>());
/// <summary>
/// Get a read-only collection of the child import groups, if any.
/// </summary>
public ICollection<ProjectImportGroupElement> ImportGroups => new ReadOnlyCollection<ProjectImportGroupElement>(Children.OfType<ProjectImportGroupElement>());
/// <summary>
/// Get a read-only collection of the child imports
/// </summary>
public ICollection<ProjectImportElement> Imports => new ReadOnlyCollection<ProjectImportElement>(AllChildren.OfType<ProjectImportElement>());
/// <summary>
/// Get a read-only collection of the child property groups, if any.
/// Does not include any that may not be at the root, i.e. inside Choose elements.
/// </summary>
public ICollection<ProjectPropertyGroupElement> PropertyGroups => new ReadOnlyCollection<ProjectPropertyGroupElement>(Children.OfType<ProjectPropertyGroupElement>());
/// <summary>
/// Geta read-only collection of the child properties, if any, in all property groups anywhere in the project file.
/// Not restricted to root property groups: traverses through Choose elements.
/// </summary>
public ICollection<ProjectPropertyElement> Properties => new ReadOnlyCollection<ProjectPropertyElement>(AllChildren.OfType<ProjectPropertyElement>());
/// <summary>
/// Get a read-only collection of the child targets
/// </summary>
public ICollection<ProjectTargetElement> Targets => new ReadOnlyCollection<ProjectTargetElement>(Children.OfType<ProjectTargetElement>());
/// <summary>
/// Get a read-only collection of the child usingtasks, if any
/// </summary>
public ICollection<ProjectUsingTaskElement> UsingTasks => new ReadOnlyCollection<ProjectUsingTaskElement>(Children.OfType<ProjectUsingTaskElement>());
/// <summary>
/// Get a read-only collection of the child item groups, if any, in reverse order
/// </summary>
public ICollection<ProjectItemGroupElement> ItemGroupsReversed => new ReadOnlyCollection<ProjectItemGroupElement>(ChildrenReversed.OfType<ProjectItemGroupElement>());
/// <summary>
/// Get a read-only collection of the child item definition groups, if any, in reverse order
/// </summary>
public ICollection<ProjectItemDefinitionGroupElement> ItemDefinitionGroupsReversed => new ReadOnlyCollection<ProjectItemDefinitionGroupElement>(ChildrenReversed.OfType<ProjectItemDefinitionGroupElement>());
/// <summary>
/// Get a read-only collection of the child import groups, if any, in reverse order
/// </summary>
public ICollection<ProjectImportGroupElement> ImportGroupsReversed => new ReadOnlyCollection<ProjectImportGroupElement>(ChildrenReversed.OfType<ProjectImportGroupElement>());
/// <summary>
/// Get a read-only collection of the child property groups, if any, in reverse order
/// </summary>
public ICollection<ProjectPropertyGroupElement> PropertyGroupsReversed => new ReadOnlyCollection<ProjectPropertyGroupElement>(ChildrenReversed.OfType<ProjectPropertyGroupElement>());
#endregion
/// <summary>
/// The directory that the project is in.
/// Essential for evaluating relative paths.
/// Is never null, even if the FullPath does not contain directory information.
/// If the project has not been loaded from disk and has not been given a path, returns the current-directory from
/// the time the project was loaded - this is the same behavior as Whidbey/Orcas.
/// If the project has not been loaded from disk but has been given a path, this path may not exist.
/// </summary>
public string DirectoryPath
{
get => Link != null ? RootLink.DirectoryPath : _directory ?? String.Empty;
internal set => _directory = value;
// Used during solution load to ensure solutions which were created from a file have a location.
}
public string EscapedFullPath => _escapedFullPath ?? (_escapedFullPath = ProjectCollection.Escape(FullPath));
/// <summary>
/// Full path to the project file.
/// If the project has not been loaded from disk and has not been given a path, returns null.
/// If the project has not been loaded from disk but has been given a path, this path may not exist.
/// Setter renames the project, if it already had a name.
/// </summary>
/// <remarks>
/// Updates the ProjectRootElement cache.
/// </remarks>
public string FullPath
{
get => Link != null ? RootLink.FullPath : _projectFileLocation?.File;
set
{
ErrorUtilities.VerifyThrowArgumentLength(value, nameof(value));
if (Link != null)
{
RootLink.FullPath = value;
return;
}
string oldFullPath = _projectFileLocation?.File;
// We do not control the current directory at this point, but assume that if we were
// passed a relative path, the caller assumes we will prepend the current directory.
string newFullPath = FileUtilities.NormalizePath(value);
if (String.Equals(oldFullPath, newFullPath, StringComparison.OrdinalIgnoreCase))
{
return;
}
_projectFileLocation = ElementLocation.Create(newFullPath);
_escapedFullPath = null;
_directory = Path.GetDirectoryName(newFullPath);
if (XmlDocument != null)
{
XmlDocument.FullPath = newFullPath;
}
if (oldFullPath == null)
{
ProjectRootElementCache.AddEntry(this);
}
else
{
ProjectRootElementCache.RenameEntry(oldFullPath, this);
}
OnAfterProjectRename?.Invoke(oldFullPath);
MarkDirty("Set project FullPath to '{0}'", FullPath);
}
}
/// <summary>
/// Encoding that the project file is saved in, or will be saved in, unless
/// otherwise specified.
/// </summary>
/// <remarks>
/// Returns the encoding from the Xml declaration if any, otherwise UTF8.
/// </remarks>
public Encoding Encoding
{
get
{
if (Link != null)
{
return RootLink.Encoding;
}
// No thread-safety lock required here because many reader threads would set the same value to the field.
if (_encoding == null)
{
var declaration = XmlDocument.FirstChild as XmlDeclaration;
if (declaration?.Encoding.Length > 0)
{
_encoding = Encoding.GetEncoding(declaration.Encoding);
}
}
// Ensure we never return null, in case there was no xml declaration that we could find above.
return _encoding ?? s_defaultEncoding;
}
}
/// <summary>
/// Gets or sets the value of DefaultTargets. If there is no DefaultTargets, returns empty string.
/// If the value is null or empty, removes the attribute.
/// </summary>
public string DefaultTargets
{
[DebuggerStepThrough]
get => GetAttributeValue(XMakeAttributes.defaultTargets);
[DebuggerStepThrough]
set => SetOrRemoveAttribute(XMakeAttributes.defaultTargets, value, "Set Project DefaultTargets to '{0}'", value);
}
/// <summary>
/// Gets or sets the value of InitialTargets. If there is no InitialTargets, returns empty string.
/// If the value is null or empty, removes the attribute.
/// </summary>
public string InitialTargets
{
[DebuggerStepThrough]
get => GetAttributeValue(XMakeAttributes.initialTargets);
[DebuggerStepThrough]
set => SetOrRemoveAttribute(XMakeAttributes.initialTargets, value, "Set project InitialTargets to '{0}'", value);
}
/// <summary>
/// Gets or sets a semicolon delimited list of software development kits (SDK) that the project uses.
/// If a value is specified, an Sdk.props is simplicity imported at the top of the project and an
/// Sdk.targets is simplicity imported at the bottom from the specified SDK.
/// If the value is null or empty, removes the attribute.
/// </summary>
public string Sdk
{
[DebuggerStepThrough]
get => GetAttributeValue(XMakeAttributes.sdk);
[DebuggerStepThrough]
set => SetOrRemoveAttribute(XMakeAttributes.sdk, value, "Set project Sdk to '{0}'", value);
}
/// <summary>
/// Gets or sets the value of TreatAsLocalProperty. If there is no tag, returns empty string.
/// If the value being set is null or empty, removes the attribute.
/// </summary>
public string TreatAsLocalProperty
{
[DebuggerStepThrough]
get => GetAttributeValue(XMakeAttributes.treatAsLocalProperty);
[DebuggerStepThrough]
set => SetOrRemoveAttribute(XMakeAttributes.treatAsLocalProperty, value, "Set project TreatAsLocalProperty to '{0}'", value);
}
/// <summary>
/// Gets or sets the value of ToolsVersion. If there is no ToolsVersion, returns empty string.
/// If the value is null or empty, removes the attribute.
/// </summary>
public string ToolsVersion
{
[DebuggerStepThrough]
get => GetAttributeValue(XMakeAttributes.toolsVersion);
[DebuggerStepThrough]
set => SetOrRemoveAttribute(XMakeAttributes.toolsVersion, value, "Set project ToolsVersion {0}", value);
}
/// <summary>
/// Gets the XML representing this project as a string.
/// Does not remove any dirty flag.
/// </summary>
/// <remarks>
/// Useful for debugging.
/// Note that we do not expose an XmlDocument or any other specific XML API.
/// </remarks>
public string RawXml
{
get
{
if (Link != null)
{
return RootLink.RawXml;
}
using (var stringWriter = new EncodingStringWriter(Encoding))
{
using (var projectWriter = new ProjectWriter(stringWriter))
{
projectWriter.Initialize(XmlDocument);
XmlDocument.Save(projectWriter);
}
return stringWriter.ToString();
}
}
}
/// <summary>
/// Whether the XML has been modified since it was last loaded or saved.
/// </summary>
public bool HasUnsavedChanges => Link != null ? RootLink.HasUnsavedChanges : Version != _versionOnDisk;
/// <summary>
/// Whether the XML is preserving formatting or not.
/// </summary>
public bool PreserveFormatting => Link != null ? RootLink.PreserveFormatting : XmlDocument?.PreserveWhitespace ?? false;
/// <summary>
/// Version number of this object.
/// A host can compare this to a stored version number to determine whether
/// a project's XML has changed, even if it has also been saved since.
///
/// The actual value is meaningless: an edit may increment it more than once,
/// so it should only be compared to a stored value.
/// </summary>
/// <remarks>
/// Used by the Project class to figure whether changes have occurred that
/// it might want to pick up by reevaluation.
///
/// Used by the ProjectRootElement class to determine whether it needs to save.
///
/// This number is unique to the appdomain. That means that it is possible
/// to know when a ProjectRootElement has been unloaded (perhaps after modification) and
/// reloaded -- the version won't reset to '0'.
///
/// We're assuming we don't have over 2 billion edits.
/// </remarks>
public int Version
{
get => Link != null ? RootLink.Version : _version;
private set => _version = value;
}
/// <summary>
/// The time that this object was last changed. If it hasn't
/// been changed since being loaded or created, its value is <see cref="DateTime.MinValue"/>.
/// </summary>
/// <remarks>
/// This is used by the VB/C# project system.
/// </remarks>
public DateTime TimeLastChanged => Link != null ? RootLink.TimeLastChanged : _timeLastChangedUtc.ToLocalTime();
/// <summary>
/// The last-write-time of the file that was read, when it was read.
/// This can be used to see whether the file has been changed on disk
/// by an external means.
/// </summary>
public DateTime LastWriteTimeWhenRead => Link != null ? RootLink.LastWriteTimeWhenRead : _lastWriteTimeWhenReadUtc.ToLocalTime();
internal DateTime? StreamTimeUtc = null;
/// <summary>
/// This does not allow conditions, so it should not be called.
/// </summary>
public override ElementLocation ConditionLocation
{
get
{
ErrorUtilities.ThrowInternalError("Should not evaluate this");
return null;
}
}
/// <summary>
/// Location of the originating file itself, not any specific content within it.
/// If the file has not been given a name, returns an empty location.
/// This is a case where it is legitimate to "not have a location".
/// </summary>
public ElementLocation ProjectFileLocation => Link != null ? RootLink.ProjectFileLocation : _projectFileLocation ?? ElementLocation.EmptyLocation;
/// <summary>
/// Location of the toolsversion attribute, if any
/// </summary>
public ElementLocation ToolsVersionLocation => GetAttributeLocation(XMakeAttributes.toolsVersion);
/// <summary>
/// Location of the defaulttargets attribute, if any
/// </summary>
public ElementLocation DefaultTargetsLocation => GetAttributeLocation(XMakeAttributes.defaultTargets);
/// <summary>
/// Location of the initialtargets attribute, if any
/// </summary>
public ElementLocation InitialTargetsLocation => GetAttributeLocation(XMakeAttributes.initialTargets);
/// <summary>
/// Location of the Sdk attribute, if any
/// </summary>
public ElementLocation SdkLocation => GetAttributeLocation(XMakeAttributes.sdk);
/// <summary>
/// Location of the TreatAsLocalProperty attribute, if any
/// </summary>
public ElementLocation TreatAsLocalPropertyLocation => GetAttributeLocation(XMakeAttributes.treatAsLocalProperty);
/// <summary>
/// Has the project root element been explicitly loaded for a build or has it been implicitly loaded
/// as part of building another project.
/// </summary>
/// <remarks>
/// Internal code that wants to set this to true should call <see cref="MarkAsExplicitlyLoaded"/>.
/// The setter is private to make it more difficult to downgrade an existing PRE to an implicitly loaded state, which should never happen.
/// </remarks>
internal bool IsExplicitlyLoaded { get; private set; }
/// <summary>
/// Retrieves the root element cache with which this root element is associated.
/// </summary>
internal ProjectRootElementCacheBase ProjectRootElementCache { get; }
/// <summary>
/// Gets a value indicating whether this PRE is known by its containing collection.
/// </summary>
internal bool IsMemberOfProjectCollection => _projectFileLocation != null;
/// <summary>
/// Indicates whether there are any targets in this project
/// that use the "Returns" attribute. If so, then this project file
/// is automatically assumed to be "Returns-enabled", and the default behavior
/// for targets without Returns attributes changes from using the Outputs to
/// returning nothing by default.
/// </summary>
internal bool ContainsTargetsWithReturnsAttribute { get; set; }
/// <summary>
/// Gets the ProjectExtensions child, if any, otherwise null.
/// </summary>
/// <remarks>
/// Not public as we do not wish to encourage the use of ProjectExtensions.
/// </remarks>
internal ProjectExtensionsElement ProjectExtensions
=> ChildrenReversed.OfType<ProjectExtensionsElement>().FirstOrDefault();
/// <summary>
/// Returns an unlocalized indication of how this file was last dirtied.
/// This is for debugging purposes only.
/// String formatting only occurs when retrieved.
/// </summary>
internal string LastDirtyReason
=> _dirtyReason == null ? null : String.Format(CultureInfo.InvariantCulture, _dirtyReason, _dirtyParameter);
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later.
/// Uses the global project collection.
/// </summary>
public static ProjectRootElement Create()
{
return Create(ProjectCollection.GlobalProjectCollection, Project.DefaultNewProjectTemplateOptions);
}
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later using the specified <see cref="NewProjectFileOptions"/>.
/// Uses the global project collection.
/// </summary>
public static ProjectRootElement Create(NewProjectFileOptions projectFileOptions)
{
return Create(ProjectCollection.GlobalProjectCollection, projectFileOptions);
}
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later.
/// Uses the specified project collection.
/// </summary>
public static ProjectRootElement Create(ProjectCollection projectCollection)
{
return Create(projectCollection.ProjectRootElementCache);
}
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later using the specified <see cref="ProjectCollection"/> and <see cref="NewProjectFileOptions"/>.
/// </summary>
public static ProjectRootElement Create(ProjectCollection projectCollection, NewProjectFileOptions projectFileOptions)
{
ErrorUtilities.VerifyThrowArgumentNull(projectCollection, nameof(projectCollection));
return Create(projectCollection.ProjectRootElementCache, projectFileOptions);
}
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later.
/// Uses the global project collection.
/// </summary>
public static ProjectRootElement Create(string path)
{
return Create(path, ProjectCollection.GlobalProjectCollection, Project.DefaultNewProjectTemplateOptions);
}
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later using the specified path and <see cref="NewProjectFileOptions"/>.
/// Uses the global project collection.
/// </summary>
public static ProjectRootElement Create(string path, NewProjectFileOptions newProjectFileOptions)
{
return Create(path, ProjectCollection.GlobalProjectCollection, newProjectFileOptions);
}
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later.
/// Uses the specified project collection.
/// </summary>
public static ProjectRootElement Create(string path, ProjectCollection projectCollection)
{
return Create(path, projectCollection, Project.DefaultNewProjectTemplateOptions);
}
/// <summary>
/// Initialize an in-memory, empty ProjectRootElement instance that can be saved later.
/// Uses the specified project collection.
/// </summary>
public static ProjectRootElement Create(string path, ProjectCollection projectCollection, NewProjectFileOptions newProjectFileOptions)
{
ErrorUtilities.VerifyThrowArgumentLength(path, nameof(path));
ErrorUtilities.VerifyThrowArgumentNull(projectCollection, nameof(projectCollection));
var projectRootElement = new ProjectRootElement(
projectCollection.ProjectRootElementCache,
newProjectFileOptions) { FullPath = path };
return projectRootElement;
}
/// <summary>
/// Initialize a ProjectRootElement instance from an XmlReader.
/// Uses the global project collection.
/// May throw InvalidProjectFileException.
/// </summary>
public static ProjectRootElement Create(XmlReader xmlReader)
{
return Create(xmlReader, ProjectCollection.GlobalProjectCollection, preserveFormatting: false);
}
/// <summary>
/// Initialize a ProjectRootElement instance from an XmlReader.
/// Uses the specified project collection.
/// May throw InvalidProjectFileException.
/// </summary>
public static ProjectRootElement Create(XmlReader xmlReader, ProjectCollection projectCollection)
{
return Create(xmlReader, projectCollection, preserveFormatting: false);
}
/// <summary>
/// Initialize a ProjectRootElement instance from an XmlReader.
/// Uses the specified project collection.
/// May throw InvalidProjectFileException.
/// </summary>
public static ProjectRootElement Create(XmlReader xmlReader, ProjectCollection projectCollection, bool preserveFormatting)
{
ErrorUtilities.VerifyThrowArgumentNull(projectCollection, nameof(projectCollection));
return new ProjectRootElement(xmlReader, projectCollection.ProjectRootElementCache, true /*Explicitly loaded*/,
preserveFormatting);
}
/// <summary>
/// Initialize a ProjectRootElement instance by loading from the specified file path.
/// Uses the global project collection.
/// May throw InvalidProjectFileException.
/// </summary>
public static ProjectRootElement Open(string path)
{
return Open(path, ProjectCollection.GlobalProjectCollection);
}
/// <summary>
/// Initialize a ProjectRootElement instance by loading from the specified file path.
/// Uses the specified project collection.
/// May throw InvalidProjectFileException.
/// </summary>
public static ProjectRootElement Open(string path, ProjectCollection projectCollection)
{
return Open(path, projectCollection,
preserveFormatting: null);
}
/// <summary>
/// Initialize a ProjectRootElement instance by loading from the specified file path.
/// Uses the specified project collection and preserves the formatting of the document if specified.
/// </summary>
public static ProjectRootElement Open(string path, ProjectCollection projectCollection, bool? preserveFormatting)
{
ErrorUtilities.VerifyThrowArgumentLength(path, nameof(path));
ErrorUtilities.VerifyThrowArgumentNull(projectCollection, nameof(projectCollection));
path = FileUtilities.NormalizePath(path);
return Open(path, projectCollection.ProjectRootElementCache, true /*Is explicitly loaded*/, preserveFormatting);
}
/// <summary>
/// Returns the ProjectRootElement for the given path if it has been loaded, or null if it is not currently in memory.
/// Uses the global project collection.
/// </summary>
/// <param name="path">The path of the ProjectRootElement, cannot be null.</param>
/// <returns>The loaded ProjectRootElement, or null if it is not currently in memory.</returns>
/// <remarks>
/// It is possible for ProjectRootElements to be brought into memory and discarded due to memory pressure. Therefore
/// this method returning false does not indicate that it has never been loaded, only that it is not currently in memory.
/// </remarks>
public static ProjectRootElement TryOpen(string path)
{
ErrorUtilities.VerifyThrowArgumentLength(path, nameof(path));
return TryOpen(path, ProjectCollection.GlobalProjectCollection);
}
/// <summary>
/// Returns the ProjectRootElement for the given path if it has been loaded, or null if it is not currently in memory.
/// Uses the specified project collection.
/// </summary>
/// <param name="path">The path of the ProjectRootElement, cannot be null.</param>
/// <param name="projectCollection">The <see cref="ProjectCollection"/> to load the project into.</param>
/// <returns>The loaded ProjectRootElement, or null if it is not currently in memory.</returns>
/// <remarks>
/// It is possible for ProjectRootElements to be brought into memory and discarded due to memory pressure. Therefore
/// this method returning false does not indicate that it has never been loaded, only that it is not currently in memory.
/// </remarks>
public static ProjectRootElement TryOpen(string path, ProjectCollection projectCollection)
{
return TryOpen(path, projectCollection, preserveFormatting: null);
}
/// <summary>
/// Returns the ProjectRootElement for the given path if it has been loaded, or null if it is not currently in memory.
/// Uses the specified project collection.
/// </summary>
/// <param name="path">The path of the ProjectRootElement, cannot be null.</param>
/// <param name="projectCollection">The <see cref="ProjectCollection"/> to load the project into.</param>
/// <param name="preserveFormatting">
/// The formatting to open with. Must match the formatting in the collection to succeed.
/// </param>
/// <returns>The loaded ProjectRootElement, or null if it is not currently in memory.</returns>
/// <remarks>
/// It is possible for ProjectRootElements to be brought into memory and discarded due to memory pressure. Therefore
/// this method returning false does not indicate that it has never been loaded, only that it is not currently in memory.
/// </remarks>
public static ProjectRootElement TryOpen(string path, ProjectCollection projectCollection, bool? preserveFormatting)
{
ErrorUtilities.VerifyThrowArgumentLength(path, nameof(path));
ErrorUtilities.VerifyThrowArgumentNull(projectCollection, nameof(projectCollection));
path = FileUtilities.NormalizePath(path);
ProjectRootElement projectRootElement = projectCollection.ProjectRootElementCache.TryGet(path, preserveFormatting);
return projectRootElement;
}
/// <summary>
/// Convenience method that picks a location based on a heuristic:
/// If import groups exist, inserts into the last one without a condition on it.
/// Otherwise, creates an import at the end of the project.
/// </summary>
public ProjectImportElement AddImport(string project)
{
ErrorUtilities.VerifyThrowArgumentLength(project, nameof(project));
ProjectImportGroupElement importGroupToAddTo =
ImportGroupsReversed.FirstOrDefault(importGroup => importGroup.Condition.Length <= 0);
ProjectImportElement import;
if (importGroupToAddTo != null)
{
import = importGroupToAddTo.AddImport(project);
}
else
{
import = CreateImportElement(project);
AppendChild(import);
}
return import;
}
/// <summary>
/// Convenience method that picks a location based on a heuristic:
/// Creates an import group at the end of the project.
/// </summary>
public ProjectImportGroupElement AddImportGroup()
{
ProjectImportGroupElement importGroup = CreateImportGroupElement();
AppendChild(importGroup);
return importGroup;
}
/// <summary>
/// Convenience method that picks a location based on a heuristic:
/// Finds item group with no condition with at least one item of same type, or else adds a new item group;
/// adds the item to that item group with items of the same type, ordered by include.
/// </summary>
/// <remarks>
/// Per the previous implementation, it actually finds the last suitable item group, not the first.
/// </remarks>
public ProjectItemElement AddItem(string itemType, string include)
{
return AddItem(itemType, include, null);
}
/// <summary>
/// Convenience method that picks a location based on a heuristic:
/// Finds first item group with no condition with at least one item of same type, or else an empty item group; or else adds a new item group;
/// adds the item to that item group with items of the same type, ordered by include.
/// Does not attempt to check whether the item matches an existing wildcard expression; that is only possible
/// in the evaluated world.
/// </summary>
/// <remarks>
/// Per the previous implementation, it actually finds the last suitable item group, not the first.
/// </remarks>
public ProjectItemElement AddItem(string itemType, string include, IEnumerable<KeyValuePair<string, string>> metadata)
{
ErrorUtilities.VerifyThrowArgumentLength(itemType, "itemType");
ErrorUtilities.VerifyThrowArgumentLength(include, "include");
ProjectItemGroupElement itemGroupToAddTo = null;
foreach (ProjectItemGroupElement itemGroup in ItemGroups)
{
if (itemGroup.Condition.Length > 0)
{
continue;
}
if (itemGroupToAddTo == null && itemGroup.Count == 0)
{
itemGroupToAddTo = itemGroup;