This repository was archived by the owner on Oct 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathProject.cs
3107 lines (2649 loc) · 101 KB
/
Project.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
// Project.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
// Viktoria Dudka <viktoriad@remobjects.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
// Copyright (c) 2009 RemObjects Software
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using MonoDevelop.Core;
using MonoDevelop.Core.Serialization;
using MonoDevelop.Projects;
using System.Threading.Tasks;
using MonoDevelop.Projects.MSBuild;
using System.Xml;
using MonoDevelop.Core.Instrumentation;
using MonoDevelop.Core.Assemblies;
using MonoDevelop.Projects.Extensions;
using System.Collections.Immutable;
using System.Threading;
namespace MonoDevelop.Projects
{
/// <summary>
/// A project
/// </summary>
/// <remarks>
/// This is the base class for MonoDevelop projects. A project is a solution item which has a list of
/// source code files and which can be built to generate an output.
/// </remarks>
public class Project : SolutionItem
{
string[] flavorGuids = new string[0];
static Counter ProjectOpenedCounter = InstrumentationService.CreateCounter ("Project Opened", "Project Model", id:"Ide.Project.Open");
string[] buildActions;
MSBuildProject sourceProject;
string productVersion;
string schemaVersion;
bool modifiedInMemory;
bool msbuildUpdatePending;
ProjectExtension projectExtension;
List<string> defaultImports;
ProjectItemCollection items;
IEnumerable<string> loadedAvailableItemNames = ImmutableList<string>.Empty;
protected Project ()
{
items = new ProjectItemCollection (this);
FileService.FileChanged += HandleFileChanged;
Runtime.SystemAssemblyService.DefaultRuntimeChanged += OnDefaultRuntimeChanged;
files = new ProjectFileCollection ();
Items.Bind (files);
DependencyResolutionEnabled = true;
}
public ProjectItemCollection Items {
get { return items; }
}
protected Project (params string[] flavorGuids): this()
{
this.flavorGuids = flavorGuids;
}
protected Project (ProjectCreateInformation projectCreateInfo, XmlElement projectOptions): this()
{
var ids = projectOptions != null ? projectOptions.GetAttribute ("flavorIds") : null;
if (!string.IsNullOrEmpty (ids)) {
this.flavorGuids = ids.Split (new [] {';'}, StringSplitOptions.RemoveEmptyEntries);
}
}
protected override void OnSetShared ()
{
base.OnSetShared ();
items.SetShared ();
files.SetShared ();
}
internal class CreationContext
{
public MSBuildProject Project { get; set; }
public string TypeGuid { get; set; }
public string[] FlavorGuids { get; set; }
internal static CreationContext Create (MSBuildProject p, string typeGuid)
{
return new CreationContext {
Project = p,
TypeGuid = typeGuid
};
}
internal static CreationContext Create (string typeGuid, string[] flavorGuids)
{
return new CreationContext {
TypeGuid = typeGuid,
FlavorGuids = flavorGuids
};
}
}
CreationContext creationContext;
internal void SetCreationContext (CreationContext ctx)
{
creationContext = ctx;
}
protected override void OnInitialize ()
{
base.OnInitialize ();
if (creationContext != null) {
if (IsExtensionChainCreated)
throw new InvalidOperationException ("Extension chain already created for this object");
TypeGuid = creationContext.TypeGuid;
string projectTypeGuids;
if (creationContext.Project != null) {
this.sourceProject = creationContext.Project;
IMSBuildPropertySet globalGroup = sourceProject.GetGlobalPropertyGroup ();
projectTypeGuids = globalGroup.GetValue ("ProjectTypeGuids");
if (projectTypeGuids != null) {
var subtypeGuids = new List<string> ();
foreach (string guid in projectTypeGuids.Split (';')) {
string sguid = guid.Trim ();
if (sguid.Length > 0 && string.Compare (sguid, creationContext.TypeGuid, StringComparison.OrdinalIgnoreCase) != 0)
subtypeGuids.Add (guid);
}
flavorGuids = subtypeGuids.ToArray ();
}
} else {
sourceProject = new MSBuildProject ();
sourceProject.FileName = FileName;
flavorGuids = creationContext.FlavorGuids;
}
}
if (sourceProject == null) {
sourceProject = new MSBuildProject ();
sourceProject.FileName = FileName;
}
}
protected override void OnExtensionChainInitialized ()
{
projectExtension = ExtensionChain.GetExtension<ProjectExtension> ();
base.OnExtensionChainInitialized ();
if (creationContext != null && creationContext.Project != null)
FileName = creationContext.Project.FileName;
MSBuildEngineSupport = MSBuildProjectService.GetMSBuildSupportForProject (this);
InitFormatProperties ();
}
void OnDefaultRuntimeChanged (object o, EventArgs args)
{
// If the default runtime changes, the project builder for this project may change
// so it has to be created again.
CleanupProjectBuilder ();
}
public IEnumerable<string> FlavorGuids {
get { return flavorGuids; }
}
public IPropertySet ProjectProperties {
get { return MSBuildProject.GetGlobalPropertyGroup (); }
}
public MSBuildProject MSBuildProject {
get {
if (msbuildUpdatePending && !saving)
WriteProjectAsync (new ProgressMonitor ()).Wait ();
return sourceProject;
}
}
public virtual Project GetRealProject() {
// Normal MSBuild projects just use themselves for the type system and other extensions.
return this;
}
public List<string> DefaultImports {
get {
if (defaultImports == null) {
var list = new List<string> ();
ProjectExtension.OnGetDefaultImports (list);
defaultImports = list;
}
return defaultImports;
}
}
new public ProjectConfiguration CreateConfiguration (string name, ConfigurationKind kind = ConfigurationKind.Blank)
{
return (ProjectConfiguration) base.CreateConfiguration (name, kind);
}
protected virtual void OnGetDefaultImports (List<string> imports)
{
}
public string ToolsVersion { get; private set; }
internal bool CheckAllFlavorsSupported ()
{
return FlavorGuids.All (g => ProjectExtension.SupportsFlavor (g));
}
ProjectExtension ProjectExtension {
get {
if (projectExtension == null)
AssertExtensionChainCreated ();
return projectExtension;
}
}
public MSBuildSupport MSBuildEngineSupport { get; private set; }
protected override void OnModified (SolutionItemModifiedEventArgs args)
{
if (!Loading) {
modifiedInMemory = true;
msbuildUpdatePending = true;
}
base.OnModified (args);
}
protected override Task OnLoad (ProgressMonitor monitor)
{
return Task.Run (delegate {
if (sourceProject == null || sourceProject.IsNewProject) {
sourceProject = MSBuildProject.LoadAsync (FileName).Result;
if (MSBuildEngineSupport == MSBuildSupport.NotSupported)
sourceProject.UseMSBuildEngine = false;
sourceProject.Evaluate ();
}
IMSBuildPropertySet globalGroup = sourceProject.GetGlobalPropertyGroup ();
// Avoid crash if there is not global group
if (globalGroup == null)
sourceProject.AddNewPropertyGroup (false);
ProjectExtension.OnPrepareForEvaluation (sourceProject);
ReadProject (monitor, sourceProject);
});
}
/// <summary>
/// Runs the generator target and sends file change notifications if any files were modified, returns the build result
/// </summary>
public Task<TargetEvaluationResult> PerformGeneratorAsync (ConfigurationSelector configuration, string generatorTarget)
{
return BindTask<TargetEvaluationResult> (async cancelToken => {
var cancelSource = new CancellationTokenSource ();
cancelToken.Register (() => cancelSource.Cancel ());
using (var monitor = new ProgressMonitor (cancelSource)) {
return await this.PerformGeneratorAsync (monitor, configuration, generatorTarget);
}
});
}
/// <summary>
/// Runs the generator target and sends file change notifications if any files were modified, returns the build result
/// </summary>
public async Task<TargetEvaluationResult> PerformGeneratorAsync (ProgressMonitor monitor, ConfigurationSelector configuration, string generatorTarget)
{
var fileInfo = await GetProjectFileTimestamps (monitor, configuration);
var evalResult = await this.RunTarget (monitor, generatorTarget, configuration);
SendFileChangeNotifications (monitor, configuration, fileInfo);
return evalResult;
}
/// <summary>
/// Returns a list containing FileInfo for all the source files in the project
/// </summary>
async Task<List<FileInfo>> GetProjectFileTimestamps (ProgressMonitor monitor, ConfigurationSelector configuration)
{
var infoList = new List<FileInfo> ();
var projectFiles = await this.GetSourceFilesAsync (monitor, configuration);
foreach (var projectFile in projectFiles) {
var info = new FileInfo (projectFile.FilePath);
infoList.Add (info);
}
return infoList;
}
/// <summary>
/// Sends a file change notification via FileService for any file that has changed since the timestamps in beforeFileInfo
/// </summary>
void SendFileChangeNotifications (ProgressMonitor monitor, ConfigurationSelector configuration, List<FileInfo> beforeFileInfo)
{
var changedFiles = new List<FileInfo> ();
foreach (var file in beforeFileInfo) {
var info = new FileInfo (file.FullName);
if (file.Exists && info.Exists) {
if (file.LastWriteTime != info.LastWriteTime) {
changedFiles.Add (info);
}
} else if (info.Exists) {
changedFiles.Add (info);
} else if (file.Exists) {
// not sure if this should or could happen, it doesn't really make much sense
FileService.NotifyFileRemoved (file.FullName);
}
}
FileService.NotifyFilesChanged (changedFiles.Select (cf => new FilePath (cf.FullName)));
}
/// <summary>
/// Gets the source files that are included in the project, including any that are added by `CoreCompileDependsOn`
/// </summary>
public Task<ProjectFile[]> GetSourceFilesAsync (ConfigurationSelector configuration)
{
if (sourceProject == null)
return Task.FromResult (new ProjectFile [0]);
return BindTask<ProjectFile []> (async cancelToken => {
var cancelSource = new CancellationTokenSource ();
cancelToken.Register (() => cancelSource.Cancel ());
using (var monitor = new ProgressMonitor (cancelSource)) {
return await GetSourceFilesAsync (monitor, configuration);
}
});
}
/// <summary>
/// Gets the source files that are included in the project, including any that are added by `CoreCompileDependsOn`
/// </summary>
public async Task<ProjectFile[]> GetSourceFilesAsync (ProgressMonitor monitor, ConfigurationSelector configuration)
{
// pre-load the results with the current list of files in the project
var results = new List<ProjectFile> ();
var buildActions = GetBuildActions ().Where (a => a != "Folder" && a != "--").ToArray ();
var config = configuration != null ? GetConfiguration (configuration) : null;
var pri = await CreateProjectInstaceForConfigurationAsync (config?.Name, config?.Platform, false);
foreach (var it in pri.EvaluatedItems.Where (i => buildActions.Contains (i.Name)))
results.Add (CreateProjectFile (it));
// add in any compile items that we discover from running the CoreCompile dependencies
var evaluatedCompileItems = await GetCompileItemsFromCoreCompileDependenciesAsync (monitor, configuration);
var addedItems = evaluatedCompileItems.Where (i => results.All (pi => pi.FilePath != i.FilePath)).ToList ();
results.AddRange (addedItems);
return results.ToArray ();
}
bool evaluatedCoreCompileDependencies;
readonly TaskCompletionSource<ProjectFile[]> evaluatedCompileItemsTask = new TaskCompletionSource<ProjectFile[]> ();
/// <summary>
/// Gets the list of files that are included as Compile items from the evaluation of the CoreCompile dependecy targets
/// </summary>
async Task<ProjectFile[]> GetCompileItemsFromCoreCompileDependenciesAsync (ProgressMonitor monitor, ConfigurationSelector configuration)
{
List<ProjectFile> result = null;
lock (evaluatedCompileItemsTask) {
if (!evaluatedCoreCompileDependencies) {
result = new List<ProjectFile> ();
evaluatedCoreCompileDependencies = true;
}
}
if (result != null) {
var coreCompileDependsOn = sourceProject.EvaluatedProperties.GetValue<string> ("CoreCompileDependsOn");
if (string.IsNullOrEmpty (coreCompileDependsOn)) {
evaluatedCompileItemsTask.SetResult (new ProjectFile [0]);
return evaluatedCompileItemsTask.Task.Result;
}
var dependsList = coreCompileDependsOn.Split (new [] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var dependTarget in dependsList) {
try {
// evaluate the Compile targets
var ctx = new TargetEvaluationContext ();
ctx.ItemsToEvaluate.Add ("Compile");
var evalResult = await this.RunTarget (monitor, dependTarget, configuration, ctx);
if (evalResult != null && !evalResult.BuildResult.HasErrors) {
var evalItems = evalResult
.Items
.Select (i => CreateProjectFile (i))
.ToList ();
result.AddRange (evalItems);
}
} catch (Exception ex) {
LoggingService.LogInternalError (string.Format ("Error running target {0}", dependTarget), ex);
}
}
evaluatedCompileItemsTask.SetResult (result.ToArray ());
}
return await evaluatedCompileItemsTask.Task;
}
ProjectFile CreateProjectFile (IMSBuildItemEvaluated item)
{
return new ProjectFile (MSBuildProjectService.FromMSBuildPath (sourceProject.BaseDirectory, item.Include), item.Name) { Project = this };
}
/// <summary>
/// Called just after the MSBuild project is loaded but before it is evaluated.
/// </summary>
/// <param name="project">The project</param>
/// <remarks>
/// Subclasses can override this method to transform the MSBuild project before it is evaluated.
/// For example, it can be used to add or remove imports, or to set custom values for properties.
/// Changes done in the MSBuild files are not saved.
/// </remarks>
protected virtual void OnPrepareForEvaluation (MSBuildProject project)
{
}
internal protected override async Task OnSave (ProgressMonitor monitor)
{
SetFastBuildCheckDirty ();
modifiedInMemory = false;
await WriteProjectAsync (monitor);
// Doesn't save the file to disk if the content did not change
if (await sourceProject.SaveAsync (FileName) && projectBuilder != null)
await projectBuilder.Refresh ();
}
protected override IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions ()
{
return base.CreateDefaultExtensions ().Concat (Enumerable.Repeat (new DefaultMSBuildProjectExtension (), 1));
}
internal protected override IEnumerable<string> GetItemTypeGuids ()
{
return base.GetItemTypeGuids ().Concat (flavorGuids);
}
protected override void OnGetProjectEventMetadata (IDictionary<string, string> metadata)
{
base.OnGetProjectEventMetadata (metadata);
var sb = new System.Text.StringBuilder ();
var first = true;
var projectTypes = this.GetTypeTags ().ToList ();
foreach (var p in projectTypes.Where (x => (x != "DotNet") || projectTypes.Count == 1)) {
if (!first)
sb.Append (", ");
sb.Append (p);
first = false;
}
metadata ["ProjectTypes"] = sb.ToString ();
}
protected override void OnEndLoad ()
{
base.OnEndLoad ();
ProjectOpenedCounter.Inc (1, null, GetProjectEventMetadata (null));
}
/// <summary>
/// Description of the project.
/// </summary>
private string description = "";
public string Description {
get { return description ?? ""; }
set {
description = value;
NotifyModified ("Description");
}
}
/// <summary>
/// Determines whether the provided file can be as part of this project
/// </summary>
/// <returns>
/// <c>true</c> if the file can be compiled; otherwise, <c>false</c>.
/// </returns>
/// <param name='fileName'>
/// File name
/// </param>
public bool IsCompileable (string fileName)
{
return ProjectExtension.OnGetIsCompileable (fileName);
}
protected virtual bool OnGetIsCompileable (string fileName)
{
return false;
}
/// <summary>
/// Determines whether the provided build action is a compile action
/// </summary>
/// <returns><c>true</c> if this instance is compile build action the specified buildAction; otherwise, <c>false</c>.</returns>
/// <param name="buildAction">Build action.</param>
public bool IsCompileBuildAction (string buildAction)
{
return ProjectExtension.OnGetIsCompileBuildAction (buildAction);
}
protected virtual bool OnGetIsCompileBuildAction (string buildAction)
{
return buildAction == BuildAction.Compile;
}
/// <summary>
/// Files of the project
/// </summary>
public ProjectFileCollection Files {
get { return files; }
}
private ProjectFileCollection files;
FilePath baseIntermediateOutputPath;
public FilePath BaseIntermediateOutputPath {
get {
if (!baseIntermediateOutputPath.IsNullOrEmpty)
return baseIntermediateOutputPath;
return BaseDirectory.Combine ("obj");
}
set {
if (value.IsNullOrEmpty)
value = FilePath.Null;
if (baseIntermediateOutputPath == value)
return;
NotifyModified ("BaseIntermediateOutputPath");
}
}
/// <summary>
/// Gets the project type and its base types.
/// </summary>
public IEnumerable<string> GetTypeTags ()
{
HashSet<string> sset = new HashSet<string> ();
ProjectExtension.OnGetTypeTags (sset);
return sset;
}
protected virtual void OnGetTypeTags (HashSet<string> types)
{
}
public bool HasFlavor<T> ()
{
return GetService (typeof(T)) != null;
}
public T GetFlavor<T> () where T:ProjectExtension
{
return (T) GetService (typeof(T));
}
internal IEnumerable<ProjectExtension> GetFlavors ()
{
return ExtensionChain.GetAllExtensions ().OfType<ProjectExtension> ();
}
/// <summary>
/// Gets or sets the icon of the project.
/// </summary>
/// <value>
/// The stock icon.
/// </value>
public IconId StockIcon {
get {
if (stockIcon != null)
return stockIcon.Value;
else
return ProjectExtension.StockIcon;
}
set { this.stockIcon = value; NotifyModified ("StockIcon"); }
}
IconId? stockIcon;
/// <summary>
/// List of languages that this project supports
/// </summary>
/// <value>
/// The identifiers of the supported languages.
/// </value>
public string[] SupportedLanguages {
get { return ProjectExtension.SupportedLanguages; }
}
protected virtual string[] OnGetSupportedLanguages ()
{
return new String[] { "" };
}
/// <summary>
/// Gets the default build action for a file
/// </summary>
/// <returns>
/// The default build action.
/// </returns>
/// <param name='fileName'>
/// File name.
/// </param>
public string GetDefaultBuildAction (string fileName)
{
return ProjectExtension.OnGetDefaultBuildAction (fileName);
}
protected virtual string OnGetDefaultBuildAction (string fileName)
{
return IsCompileable (fileName) ? BuildAction.Compile : BuildAction.None;
}
internal ProjectItem CreateProjectItem (IMSBuildItemEvaluated item)
{
return ProjectExtension.OnCreateProjectItem (item);
}
protected virtual ProjectItem OnCreateProjectItem (IMSBuildItemEvaluated item)
{
if (item.Name == "Folder")
return new ProjectFile ();
var type = MSBuildProjectService.GetProjectItemType (item.Name);
if (type != null)
return (ProjectItem) Activator.CreateInstance (type, true);
// Unknown item. Must be a file.
if (!string.IsNullOrEmpty (item.Include) && !UnsupportedItems.Contains (item.Name) && IsValidFile (item.Include))
return new ProjectFile ();
return new UnknownProjectItem (item.Name, item.Include);
}
bool IsValidFile (string path)
{
// If it is an absolute uri, it's not a valid file
try {
if (Uri.IsWellFormedUriString (path, UriKind.Absolute)) {
var f = new Uri (path);
return f.Scheme == "file";
}
} catch {
// Old mono versions may crash in IsWellFormedUriString if the path
// is not an uri.
}
return true;
}
// Items generated by VS but which MD is not using and should be ignored
internal static readonly IList<string> UnsupportedItems = new string[] {
"BootstrapperFile", "AppDesigner", "WebReferences", "WebReferenceUrl", "Service",
"ProjectReference", "Reference", // Reference elements are included here because they are special-cased for DotNetProject, and they are unsupported in other types of projects
"InternalsVisibleTo",
"InternalsVisibleToTest"
};
/// <summary>
/// Gets a project file.
/// </summary>
/// <returns>
/// The project file.
/// </returns>
/// <param name='fileName'>
/// File name.
/// </param>
public ProjectFile GetProjectFile (string fileName)
{
return files.GetFile (fileName);
}
/// <summary>
/// Determines whether a file belongs to this project
/// </summary>
/// <param name='fileName'>
/// File name
/// </param>
public bool IsFileInProject (string fileName)
{
return files.GetFile (fileName) != null;
}
/// <summary>
/// Gets a list of build actions supported by this project
/// </summary>
/// <remarks>
/// Common actions are grouped at the top, separated by a "--" entry *IF* there are
/// more "uncommon" actions than "common" actions
/// </remarks>
public string[] GetBuildActions ()
{
if (buildActions != null)
return buildActions;
// find all the actions in use and add them to the list of standard actions
HashSet<string> actions = new HashSet<string> ();
//ad the standard actions
foreach (string action in ProjectExtension.OnGetStandardBuildActions ().Concat (loadedAvailableItemNames))
actions.Add (action);
//add any more actions that are in the project file
foreach (ProjectFile pf in files)
actions.Add (pf.BuildAction);
//remove the "common" actions, since they're handled separately
IList<string> commonActions = ProjectExtension.OnGetCommonBuildActions ();
foreach (string action in commonActions)
if (actions.Contains (action))
actions.Remove (action);
//calculate dimensions for our new array and create it
int dashPos = commonActions.Count;
bool hasDash = commonActions.Count > 0 && actions.Count > 0;
int arrayLen = commonActions.Count + actions.Count;
int uncommonStart = hasDash ? dashPos + 1 : dashPos;
if (hasDash)
arrayLen++;
buildActions = new string[arrayLen];
//populate it
if (commonActions.Count > 0)
commonActions.CopyTo (buildActions, 0);
if (hasDash)
buildActions[dashPos] = "--";
if (actions.Count > 0)
actions.CopyTo (buildActions, uncommonStart);
//sort the actions
if (hasDash) {
//it may be better to leave common actions in the order that the project specified
//Array.Sort (buildActions, 0, commonActions.Count, StringComparer.Ordinal);
Array.Sort (buildActions, uncommonStart, arrayLen - uncommonStart, StringComparer.Ordinal);
} else {
Array.Sort (buildActions, StringComparer.Ordinal);
}
return buildActions;
}
/// <summary>
/// Gets a list of standard build actions.
/// </summary>
protected virtual IEnumerable<string> OnGetStandardBuildActions ()
{
return BuildAction.StandardActions;
}
/// <summary>
/// Gets a list of common build actions (common actions are shown first in the project build action list)
/// </summary>
protected virtual IList<string> OnGetCommonBuildActions ()
{
return BuildAction.StandardActions;
}
protected override void OnDispose ()
{
foreach (var item in items) {
IDisposable disp = item as IDisposable;
if (disp != null)
disp.Dispose ();
}
FileService.FileChanged -= HandleFileChanged;
Runtime.SystemAssemblyService.DefaultRuntimeChanged -= OnDefaultRuntimeChanged;
CleanupProjectBuilder ();
if (sourceProject != null) {
sourceProject.Dispose ();
sourceProject = null;
}
base.OnDispose ();
}
/// <summary>
/// Runs a build or execution target.
/// </summary>
/// <returns>
/// The result of the operation
/// </returns>
/// <param name='monitor'>
/// A progress monitor
/// </param>
/// <param name='target'>
/// Name of the target
/// </param>
/// <param name='configuration'>
/// Configuration to use to run the target
/// </param>
public async Task<TargetEvaluationResult> RunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context = null)
{
return await ProjectExtension.OnRunTarget (monitor, target, configuration, context);
}
public bool SupportsTarget (string target)
{
return !IsUnsupportedProject && ProjectExtension.OnGetSupportsTarget (target);
}
protected virtual bool OnGetSupportsTarget (string target)
{
return sourceProject.EvaluatedTargets.Any (t => t.Name == target);
}
/// <summary>
/// Runs a build or execution target.
/// </summary>
/// <returns>
/// The result of the operation
/// </returns>
/// <param name='monitor'>
/// A progress monitor
/// </param>
/// <param name='target'>
/// Name of the target
/// </param>
/// <param name='configuration'>
/// Configuration to use to run the target
/// </param>
/// <remarks>
/// Subclasses can override this method to provide a custom implementation of project operations such as
/// build or clean. The default implementation delegates the execution to the more specific OnBuild
/// and OnClean methods, or to the item handler for other targets.
/// </remarks>
internal protected virtual Task<TargetEvaluationResult> OnRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
if (target == ProjectService.BuildTarget)
return RunBuildTarget (monitor, configuration, context);
else if (target == ProjectService.CleanTarget)
return RunCleanTarget (monitor, configuration, context);
return RunMSBuildTarget (monitor, target, configuration, context);
}
async Task<TargetEvaluationResult> DoRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
if (target == ProjectService.BuildTarget) {
SolutionItemConfiguration conf = GetConfiguration (configuration);
if (conf != null && conf.CustomCommands.HasCommands (CustomCommandType.Build)) {
if (monitor.CancellationToken.IsCancellationRequested)
return new TargetEvaluationResult (BuildResult.CreateCancelled ().SetSource (this));
if (!await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Build, configuration)) {
var r = new BuildResult ();
r.AddError (GettextCatalog.GetString ("Custom command execution failed"));
return new TargetEvaluationResult (r.SetSource (this));
}
return new TargetEvaluationResult (BuildResult.CreateSuccess ().SetSource (this));
}
} else if (target == ProjectService.CleanTarget) {
SetFastBuildCheckDirty ();
SolutionItemConfiguration config = GetConfiguration (configuration);
if (config != null && config.CustomCommands.HasCommands (CustomCommandType.Clean)) {
if (monitor.CancellationToken.IsCancellationRequested)
return new TargetEvaluationResult (BuildResult.CreateCancelled ().SetSource (this));
if (!await config.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Clean, configuration)) {
var r = new BuildResult ();
r.AddError (GettextCatalog.GetString ("Custom command execution failed"));
return new TargetEvaluationResult (r.SetSource (this));
}
return new TargetEvaluationResult (BuildResult.CreateSuccess ().SetSource (this));
}
}
// Collect last write times for the files generated by this project
var fileTimes = new Dictionary<FilePath, DateTime> ();
foreach (var f in GetOutputFiles (configuration))
fileTimes [f] = File.GetLastWriteTime (f);
try {
var tr = await OnRunTarget (monitor, target, configuration, context);
tr.BuildResult.SourceTarget = this;
return tr;
} finally {
// If any of the project generated files changes, notify it
foreach (var e in fileTimes) {
if (File.GetLastWriteTime (e.Key) != e.Value)
FileService.NotifyFileChanged (e.Key);
}
}
}
async Task<TargetEvaluationResult> RunMSBuildTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
if (CheckUseMSBuildEngine (configuration)) {
LogWriter logWriter = new LogWriter (monitor.Log);
var configs = GetConfigurations (configuration);
string [] evaluateItems = context != null ? context.ItemsToEvaluate.ToArray () : new string [0];
string [] evaluateProperties = context != null ? context.PropertiesToEvaluate.ToArray () : new string [0];
var globalProperties = new Dictionary<string, string> ();
if (context != null) {
var md = (ProjectItemMetadata)context.GlobalProperties;
md.SetProject (sourceProject);
foreach (var p in md.GetProperties ())
globalProperties [p.Name] = p.Value;
}
MSBuildResult result = null;
await Task.Run (async delegate {
TimerCounter buildTimer = null;
switch (target) {
case "Build": buildTimer = Counters.BuildMSBuildProjectTimer; break;
case "Clean": buildTimer = Counters.CleanMSBuildProjectTimer; break;
}
var t1 = Counters.RunMSBuildTargetTimer.BeginTiming (GetProjectEventMetadata (configuration));
var t2 = buildTimer != null ? buildTimer.BeginTiming (GetProjectEventMetadata (configuration)) : null;
RemoteProjectBuilder builder = await GetProjectBuilder ();
if (builder.IsBusy)
builder = await RequestLockedBuilder ();
else
builder.Lock ();
try {
result = await builder.Run (configs, logWriter, MSBuildProjectService.DefaultMSBuildVerbosity, new [] { target }, evaluateItems, evaluateProperties, globalProperties, monitor.CancellationToken);
} finally {
builder.Unlock ();
if (builder != this.projectBuilder) {
// Dispose the builder after a while, so that it can be reused
Task.Delay (10000).ContinueWith (t => builder.Dispose ());
}
t1.End ();
if (t2 != null)
t2.End ();
}
System.Runtime.Remoting.RemotingServices.Disconnect (logWriter);
});
var br = new BuildResult ();
foreach (var err in result.Errors) {
FilePath file = null;
if (err.File != null)
file = Path.Combine (Path.GetDirectoryName (err.ProjectFile), err.File);
br.Append (new BuildError (file, err.LineNumber, err.ColumnNumber, err.Code, err.Message) {
Subcategory = err.Subcategory,
EndLine = err.EndLineNumber,
EndColumn = err.EndColumnNumber,
IsWarning = err.IsWarning,
HelpKeyword = err.HelpKeyword,
});
}
// Get the evaluated properties
var properties = new Dictionary<string, MSBuildPropertyEvaluated> ();
foreach (var p in result.Properties)
properties [p.Key] = new MSBuildPropertyEvaluated (sourceProject, p.Key, p.Value, p.Value);
var props = new MSBuildPropertyGroupEvaluated (sourceProject);
props.SetProperties (properties);