5 // Atsushi Enomoto (atsushi@xamarin.com)
7 // Copyright (C) 2013 Xamarin Inc. (http://www.xamarin.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 using System.Collections;
30 using System.Collections.Generic;
31 using Microsoft.Build.Execution;
32 using Microsoft.Build.Framework;
33 using Microsoft.Build.Evaluation;
36 using Microsoft.Build.Exceptions;
37 using System.Globalization;
38 using Microsoft.Build.Construction;
39 using Microsoft.Build.Internal.Expressions;
42 namespace Microsoft.Build.Internal
51 public BuildEngine4 (BuildSubmission submission)
53 this.submission = submission;
54 event_source = new Microsoft.Build.BuildEngine.EventSource ();
55 if (submission.BuildManager.OngoingBuildParameters.Loggers != null)
56 foreach (var l in submission.BuildManager.OngoingBuildParameters.Loggers)
57 l.Initialize (event_source);
60 BuildSubmission submission;
61 ProjectInstance project;
62 ProjectTaskInstance current_task;
63 Microsoft.Build.BuildEngine.EventSource event_source;
65 public ProjectCollection Projects {
66 get { return submission.BuildManager.OngoingBuildParameters.ProjectCollection; }
70 // While we are not faced to implement those features, there are some modern task execution requirements.
72 // This will have to be available for "out of process" nodes (see NodeAffinity).
73 // NodeAffinity is set per project file at BuildManager.HostServices.
74 // When NodeAffinity is set to OutOfProc, it should probably launch different build host
75 // that runs separate build tasks. (.NET has MSBuildTaskHost.exe which I guess is about that.)
77 // Also note that the complete implementation has to support LoadInSeparateAppDomainAttribute
78 // (which is most likely derived from AppDomainIsolatedBuildTask) that marks a task to run
79 // in separate AppDomain.
81 public void BuildProject (Func<bool> checkCancel, BuildResult result, ProjectInstance project, IEnumerable<string> targetNames, IDictionary<string,string> globalProperties, IDictionary<string,string> targetOutputs, string toolsVersion)
83 if (toolsVersion == null)
84 throw new ArgumentNullException ("toolsVersion");
86 var parameters = submission.BuildManager.OngoingBuildParameters;
87 var toolset = parameters.GetToolset (toolsVersion);
89 throw new InvalidOperationException (string.Format ("Toolset version '{0}' was not resolved to valid toolset", toolsVersion));
90 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Using Toolset version {0}.", toolsVersion), null, null, MessageImportance.Low));
91 var buildTaskFactory = new BuildTaskFactory (BuildTaskDatabase.GetDefaultTaskDatabase (toolset), new BuildTaskDatabase (this, submission.BuildRequest.ProjectInstance));
92 BuildProject (new InternalBuildArguments () { CheckCancel = checkCancel, Result = result, Project = project, TargetNames = targetNames, GlobalProperties = globalProperties, TargetOutputs = targetOutputs, ToolsVersion = toolsVersion, BuildTaskFactory = buildTaskFactory });
95 class InternalBuildArguments
97 public Func<bool> CheckCancel;
98 public BuildResult Result;
99 public ProjectInstance Project;
100 public IEnumerable<string> TargetNames;
101 public IDictionary<string,string> GlobalProperties;
102 public IDictionary<string,string> TargetOutputs;
103 public string ToolsVersion;
104 public BuildTaskFactory BuildTaskFactory;
106 public void AddTargetResult (string targetName, TargetResult targetResult)
108 if (!Result.HasResultsForTarget (targetName))
109 Result.AddResultsForTarget (targetName, targetResult);
113 void BuildProject (InternalBuildArguments args)
115 var request = submission.BuildRequest;
116 var parameters = submission.BuildManager.OngoingBuildParameters;
117 this.project = args.Project;
119 string directoryBackup = Directory.GetCurrentDirectory ();
120 Directory.SetCurrentDirectory (project.Directory);
121 event_source.FireBuildStarted (this, new BuildStartedEventArgs ("Build Started", null, DateTime.Now));
125 var initialGlobalPropertiesFormatted = "Initial Global Properties:\n" + string.Join (Environment.NewLine, project.Properties.OrderBy (p => p.Name).Where (p => p.IsImmutable).Select (p => string.Format ("{0} = {1}", p.Name, p.EvaluatedValue)).ToArray ());
126 LogMessageEvent (new BuildMessageEventArgs (initialGlobalPropertiesFormatted, null, null, MessageImportance.Low));
127 var initialProjectPropertiesFormatted = "Initial Project Properties:\n" + string.Join (Environment.NewLine, project.Properties.OrderBy (p => p.Name).Where (p => !p.IsImmutable).Select (p => string.Format ("{0} = {1}", p.Name, p.EvaluatedValue)).ToArray ());
128 LogMessageEvent (new BuildMessageEventArgs (initialProjectPropertiesFormatted, null, null, MessageImportance.Low));
129 var initialItemsFormatted = "Initial Items:\n" + string.Join (Environment.NewLine, project.Items.OrderBy (i => i.ItemType).Select (i => string.Format ("{0} : {1}", i.ItemType, i.EvaluatedInclude)).ToArray ());
130 LogMessageEvent (new BuildMessageEventArgs (initialItemsFormatted, null, null, MessageImportance.Low));
132 // null targets -> success. empty targets -> success(!)
133 foreach (var targetName in (request.ProjectInstance.InitialTargets).Where (t => t != null))
134 BuildTargetByName (targetName, args);
135 if (request.TargetNames == null)
136 args.Result.OverallResult = args.CheckCancel () ? BuildResultCode.Failure : args.Result.ResultsByTarget.Any (p => p.Value.ResultCode == TargetResultCode.Failure) ? BuildResultCode.Failure : BuildResultCode.Success;
138 foreach (var targetName in (args.TargetNames ?? request.TargetNames).Where (t => t != null))
139 BuildTargetByName (targetName, args);
141 // FIXME: check .NET behavior, whether cancellation always results in failure.
142 args.Result.OverallResult = args.CheckCancel () ? BuildResultCode.Failure : args.Result.ResultsByTarget.Any (p => p.Value.ResultCode == TargetResultCode.Failure) ? BuildResultCode.Failure : BuildResultCode.Success;
144 } catch (Exception ex) {
145 args.Result.OverallResult = BuildResultCode.Failure;
146 LogErrorEvent (new BuildErrorEventArgs (null, null, project.FullPath, 0, 0, 0, 0, "Unhandled exception occured during a build", null, null));
147 LogMessageEvent (new BuildMessageEventArgs ("Exception details: " + ex, null, null, MessageImportance.Low));
148 throw; // BuildSubmission re-catches this.
150 event_source.FireBuildFinished (this, new BuildFinishedEventArgs ("Build Finished.", null, args.Result.OverallResult == BuildResultCode.Success, DateTime.Now));
151 Directory.SetCurrentDirectory (directoryBackup);
155 bool BuildTargetByName (string targetName, InternalBuildArguments args)
157 var request = submission.BuildRequest;
158 var parameters = submission.BuildManager.OngoingBuildParameters;
159 ProjectTargetInstance target;
160 TargetResult dummyResult;
162 if (args.Result.ResultsByTarget.TryGetValue (targetName, out dummyResult) && dummyResult.ResultCode == TargetResultCode.Success) {
163 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' was skipped because it was already built successfully.", targetName), null, null, MessageImportance.Low));
164 return true; // do not add result.
167 var targetResult = new TargetResult ();
169 // null key is allowed and regarded as blind success(!) (as long as it could retrieve target)
170 if (!request.ProjectInstance.Targets.TryGetValue (targetName, out target))
171 // FIXME: from MSBuild.exe it is given MSB4057. Can we assign a number too?
172 throw new InvalidOperationException (string.Format ("target '{0}' was not found in project '{1}'", targetName, project.FullPath));
173 else if (!args.Project.EvaluateCondition (target.Condition)) {
174 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' was skipped because condition '{1}' was not met.", target.Name, target.Condition), null, null, MessageImportance.Low));
175 targetResult.Skip ();
177 // process DependsOnTargets first.
178 foreach (var dep in project.ExpandString (target.DependsOnTargets).Split (';').Select (s => s.Trim ()).Where (s => !string.IsNullOrEmpty (s))) {
179 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' depends on '{1}'.", target.Name, dep), null, null, MessageImportance.Low));
180 if (!BuildTargetByName (dep, args)) {
181 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Quit target '{0}', as dependency target '{1}' has failed.", target.Name, dep), null, null, MessageImportance.Low));
186 Func<string,ITaskItem> creator = s => new TargetOutputTaskItem () { ItemSpec = s };
188 event_source.FireTargetStarted (this, new TargetStartedEventArgs ("Target Started", null, target.Name, project.FullPath, target.FullPath));
190 // FIXME: examine in which scenario Inputs/Outputs inconsistency results in errors. Now it rather prevents csproj build.
191 /*if (!string.IsNullOrEmpty (target.Inputs) != !string.IsNullOrEmpty (target.Outputs)) {
192 targetResult.Failure (new InvalidProjectFileException (target.Location, null, string.Format ("Target {0} has mismatching Inputs and Outputs specification. When one is specified, another one has to be specified too.", targetName), null, null, null));
195 if (!string.IsNullOrEmpty (target.Inputs)) {
196 var inputs = args.Project.GetAllItems (target.Inputs, string.Empty, creator, creator, s => true, (t, s) => {
198 if (!inputs.Any ()) {
199 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' was skipped because there is no input.", target.Name), null, null, MessageImportance.Low));
202 var outputs = args.Project.GetAllItems (target.Outputs, string.Empty, creator, creator, s => true, (t, s) => {
204 var needsUpdates = GetOlderOutputsThanInputs (inputs, outputs).FirstOrDefault ();
205 if (needsUpdates != null)
206 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' needs to be built because new output {1} is needed.", target.Name, needsUpdates.ItemSpec), null, null, MessageImportance.Low));
208 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' was skipped because all the outputs are newer than all the inputs.", target.Name), null, null, MessageImportance.Low));
214 targetResult.Skip ();
216 if (DoBuildTarget (target, targetResult, args)) {
217 var items = args.Project.GetAllItems (target.Outputs, string.Empty, creator, creator, s => true, (t, s) => {
219 targetResult.Success (items);
224 event_source.FireTargetFinished (this, new TargetFinishedEventArgs ("Target Finished", null, targetName, project.FullPath, target.FullPath, targetResult.ResultCode != TargetResultCode.Failure));
227 args.AddTargetResult (targetName, targetResult);
229 return targetResult.ResultCode != TargetResultCode.Failure;
232 IEnumerable<ITaskItem> GetOlderOutputsThanInputs (IEnumerable<ITaskItem> inputs, IEnumerable<ITaskItem> outputs)
234 return outputs.Where (o => !File.Exists (o.GetMetadata ("FullPath")) || inputs.Any (i => string.CompareOrdinal (i.GetMetadata ("LastModifiedTime"), o.GetMetadata ("LastModifiedTime")) > 0));
237 // FIXME: Exception should be caught at caller site.
238 bool DoBuildTarget (ProjectTargetInstance target, TargetResult targetResult, InternalBuildArguments args)
240 var request = submission.BuildRequest;
242 // Here we check cancellation (only after TargetStarted event).
243 if (args.CheckCancel ()) {
244 targetResult.Failure (new BuildAbortedException ("Build has canceled"));
249 foreach (var child in target.Children) {
250 // Evaluate additional target properties
251 var tp = child as ProjectPropertyGroupTaskInstance;
253 if (!args.Project.EvaluateCondition (tp.Condition))
255 foreach (var p in tp.Properties) {
256 if (!args.Project.EvaluateCondition (p.Condition))
258 var value = args.Project.ExpandString (p.Value);
259 project.SetProperty (p.Name, value);
264 var ii = child as ProjectItemGroupTaskInstance;
266 if (!args.Project.EvaluateCondition (ii.Condition))
268 foreach (var item in ii.Items) {
269 if (!args.Project.EvaluateCondition (item.Condition))
271 project.AddItem (item.ItemType, project.ExpandString (item.Include));
276 var task = child as ProjectTaskInstance;
279 if (!args.Project.EvaluateCondition (task.Condition)) {
280 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Task '{0}' was skipped because condition '{1}' wasn't met.", task.Name, task.Condition), null, null, MessageImportance.Low));
283 if (!RunBuildTask (target, task, targetResult, args))
288 var onError = child as ProjectOnErrorInstance;
290 continue; // evaluated under catch clause.
292 throw new NotSupportedException (string.Format ("Unexpected Target element children \"{0}\"", child.GetType ()));
294 } catch (Exception ex) {
295 // fallback task specified by OnError element
296 foreach (var c in target.Children.OfType<ProjectOnErrorInstance> ()) {
297 if (!args.Project.EvaluateCondition (c.Condition))
299 foreach (var fallbackTarget in project.ExpandString (c.ExecuteTargets).Split (';'))
300 BuildTargetByName (fallbackTarget, args);
302 int line = target.Location != null ? target.Location.Line : 0;
303 int col = target.Location != null ? target.Location.Column : 0;
304 LogErrorEvent (new BuildErrorEventArgs (null, null, target.FullPath, line, col, 0, 0, ex.Message, null, null));
305 targetResult.Failure (ex);
311 bool RunBuildTask (ProjectTargetInstance target, ProjectTaskInstance taskInstance, TargetResult targetResult, InternalBuildArguments args)
313 var request = submission.BuildRequest;
315 var host = request.HostServices == null ? null : request.HostServices.GetHostObject (request.ProjectFullPath, target.Name, taskInstance.Name);
317 // Create Task instance.
318 var factoryIdentityParameters = new Dictionary<string,string> ();
320 factoryIdentityParameters ["MSBuildRuntime"] = taskInstance.MSBuildRuntime;
321 factoryIdentityParameters ["MSBuildArchitecture"] = taskInstance.MSBuildArchitecture;
323 var task = args.BuildTaskFactory.CreateTask (taskInstance.Name, factoryIdentityParameters, this);
325 throw new InvalidOperationException (string.Format ("TaskFactory {0} returned null Task", args.BuildTaskFactory));
326 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Using task {0} from {1}", taskInstance.Name, task.GetType ()), null, null, MessageImportance.Low));
327 task.HostObject = host;
328 task.BuildEngine = this;
330 // Prepare task parameters.
331 var evaluator = new ExpressionEvaluator (project);
332 var evaluatedTaskParams = taskInstance.Parameters.Select (p => new KeyValuePair<string,string> (p.Key, project.ExpandString (evaluator, p.Value)));
334 var requiredProps = task.GetType ().GetProperties ()
335 .Where (p => p.CanWrite && p.GetCustomAttributes (typeof (RequiredAttribute), true).Any ());
336 var missings = requiredProps.Where (p => !evaluatedTaskParams.Any (tp => tp.Key.Equals (p.Name, StringComparison.OrdinalIgnoreCase)));
338 throw new InvalidOperationException (string.Format ("Task {0} of type {1} is used without specifying mandatory property: {2}",
339 taskInstance.Name, task.GetType (), string.Join (", ", missings.Select (p => p.Name).ToArray ())));
341 foreach (var p in evaluatedTaskParams) {
342 switch (p.Key.ToLower ()) {
344 case "continueonerror":
347 var prop = task.GetType ().GetProperty (p.Key);
349 throw new InvalidOperationException (string.Format ("Task {0} does not have property {1}", taskInstance.Name, p.Key));
351 throw new InvalidOperationException (string.Format ("Task {0} has property {1} but it is read-only.", taskInstance.Name, p.Key));
352 if (string.IsNullOrEmpty (p.Value) && !requiredProps.Contains (prop))
355 prop.SetValue (task, ConvertTo (p.Value, prop.PropertyType, evaluator), null);
356 } catch (Exception ex) {
357 throw new InvalidOperationException (string.Format ("Failed to convert '{0}' for property '{1}' of type {2}", p.Value, prop.Name, prop.PropertyType), ex);
362 bool taskSuccess = false;
363 event_source.FireTaskStarted (this, new TaskStartedEventArgs ("Task Started", null, project.FullPath, taskInstance.FullPath, taskInstance.Name));
365 taskSuccess = task.Execute ();
368 targetResult.Failure (null);
369 if (!ContinueOnError) {
373 // Evaluate task output properties and items.
374 foreach (var to in taskInstance.Outputs) {
375 if (!project.EvaluateCondition (to.Condition))
377 var toItem = to as ProjectTaskOutputItemInstance;
378 var toProp = to as ProjectTaskOutputPropertyInstance;
379 string taskParameter = toItem != null ? toItem.TaskParameter : toProp.TaskParameter;
380 var pi = task.GetType ().GetProperty (taskParameter);
382 throw new InvalidOperationException (string.Format ("Task {0} does not have property {1} specified as TaskParameter", taskInstance.Name, toItem.TaskParameter));
384 throw new InvalidOperationException (string.Format ("Task {0} has property {1} specified as TaskParameter, but it is write-only", taskInstance.Name, toItem.TaskParameter));
385 var value = pi.GetValue (task, null);
386 var valueString = ConvertFrom (value);
387 if (toItem != null) {
388 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Output Item {0} from TaskParameter {1}: {2}", toItem.ItemType, toItem.TaskParameter, valueString), null, null, MessageImportance.Low));
389 Action<ITaskItem> addItem = i => {
390 var metadata = new ArrayList (i.MetadataNames).ToArray ().Cast<string> ().Select (n => new KeyValuePair<string,string> (n, i.GetMetadata (n)));
391 args.Project.AddItem (toItem.ItemType, i.ItemSpec, metadata);
393 var taskItemArray = value as ITaskItem [];
394 if (taskItemArray != null) {
395 foreach (var ti in taskItemArray)
398 var taskItem = value as ITaskItem;
399 if (taskItem != null)
402 foreach (var item in valueString.Split (';'))
403 args.Project.AddItem (toItem.ItemType, item);
406 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Output Property {0} from TaskParameter {1}: {2}", toProp.PropertyName, toProp.TaskParameter, valueString), null, null, MessageImportance.Low));
407 args.Project.SetProperty (toProp.PropertyName, valueString);
412 event_source.FireTaskFinished (this, new TaskFinishedEventArgs ("Task Finished", null, project.FullPath, taskInstance.FullPath, taskInstance.Name, taskSuccess));
417 object ConvertTo (string source, Type targetType, ExpressionEvaluator evaluator)
419 if (targetType == typeof (ITaskItem) || targetType.IsSubclassOf (typeof (ITaskItem))) {
420 var item = evaluator.EvaluatedTaskItems.FirstOrDefault (i => string.Equals (i.ItemSpec, source.Trim (), StringComparison.OrdinalIgnoreCase));
421 var ret = new TargetOutputTaskItem () { ItemSpec = source.Trim () };
423 foreach (string name in item.MetadataNames)
424 ret.SetMetadata (name, item.GetMetadata (name));
427 if (targetType.IsArray)
428 return new ArrayList (source.Split (';').Select (s => s.Trim ()).Where (s => !string.IsNullOrEmpty (s)).Select (s => ConvertTo (s, targetType.GetElementType (), evaluator)).ToArray ())
429 .ToArray (targetType.GetElementType ());
430 if (targetType == typeof (bool)) {
431 switch (source != null ? source.ToLower (CultureInfo.InvariantCulture) : string.Empty) {
443 return Convert.ChangeType (source == "" ? null : source, targetType);
446 string ConvertFrom (object source)
450 if (source is ITaskItem)
451 return ((ITaskItem) source).ItemSpec;
452 if (source.GetType ().IsArray)
453 return string.Join (";", ((Array) source).Cast<object> ().Select (o => ConvertFrom (o)).ToArray ());
455 return (string) Convert.ChangeType (source, typeof (string));
458 class TargetOutputTaskItem : ITaskItem2
460 Hashtable metadata = new Hashtable ();
462 #region ITaskItem2 implementation
463 public string GetMetadataValueEscaped (string metadataName)
465 return ProjectCollection.Escape ((string) metadata [metadataName]);
467 public void SetMetadataValueLiteral (string metadataName, string metadataValue)
469 metadata [metadataName] = ProjectCollection.Unescape (metadataValue);
471 public IDictionary CloneCustomMetadataEscaped ()
473 var ret = new Hashtable ();
474 foreach (DictionaryEntry e in metadata)
475 ret [e.Key] = ProjectCollection.Escape ((string) e.Value);
478 public string EvaluatedIncludeEscaped {
479 get { return ProjectCollection.Escape (ItemSpec); }
480 set { ItemSpec = ProjectCollection.Unescape (value); }
483 #region ITaskItem implementation
484 public IDictionary CloneCustomMetadata ()
486 return new Hashtable (metadata);
488 public void CopyMetadataTo (ITaskItem destinationItem)
490 foreach (DictionaryEntry e in metadata)
491 destinationItem.SetMetadata ((string) e.Key, (string) e.Value);
493 public string GetMetadata (string metadataName)
495 var wk = ProjectCollection.GetWellKnownMetadata (metadataName, ItemSpec, Path.GetFullPath, null);
498 var ret = (string) metadata [metadataName];
499 return ret ?? string.Empty;
501 public void RemoveMetadata (string metadataName)
503 metadata.Remove (metadataName);
505 public void SetMetadata (string metadataName, string metadataValue)
507 metadata [metadataName] = metadataValue;
509 public string ItemSpec { get; set; }
510 public int MetadataCount {
511 get { return metadata.Count; }
513 public ICollection MetadataNames {
514 get { return metadata.Keys; }
518 public override string ToString ()
525 #region IBuildEngine4 implementation
527 // task objects are not in use anyways though...
529 class TaskObjectRegistration
531 public TaskObjectRegistration (object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection)
536 AllowEarlyCollection = allowEarlyCollection;
538 public object Key { get; private set; }
539 public object Object { get; private set; }
540 public RegisteredTaskObjectLifetime Lifetime { get; private set; }
541 public bool AllowEarlyCollection { get; private set; }
544 List<TaskObjectRegistration> task_objects = new List<TaskObjectRegistration> ();
546 public object GetRegisteredTaskObject (object key, RegisteredTaskObjectLifetime lifetime)
548 var reg = task_objects.FirstOrDefault (t => t.Key == key && t.Lifetime == lifetime);
549 return reg != null ? reg.Object : null;
552 public void RegisterTaskObject (object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection)
554 task_objects.Add (new TaskObjectRegistration (key, obj, lifetime, allowEarlyCollection));
557 public object UnregisterTaskObject (object key, RegisteredTaskObjectLifetime lifetime)
559 var reg = task_objects.FirstOrDefault (t => t.Key == key && t.Lifetime == lifetime);
561 task_objects.Remove (reg);
567 #region IBuildEngine3 implementation
569 public BuildEngineResult BuildProjectFilesInParallel (string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<string>[] removeGlobalProperties, string[] toolsVersion, bool returnTargetOutputs)
571 throw new NotImplementedException ();
574 public void Reacquire ()
576 throw new NotImplementedException ();
581 throw new NotImplementedException ();
586 #region IBuildEngine2 implementation
588 // To NOT reuse this IBuildEngine instance for different build, we create another BuildManager and BuildSubmisson and then run it.
589 public bool BuildProjectFile (string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion)
591 toolsVersion = string.IsNullOrEmpty (toolsVersion) ? project.ToolsVersion : toolsVersion;
592 var globalPropertiesThatMakeSense = new Dictionary<string,string> ();
593 foreach (DictionaryEntry p in globalProperties)
594 globalPropertiesThatMakeSense [(string) p.Key] = (string) p.Value;
595 var projectToBuild = new ProjectInstance (ProjectRootElement.Create (XmlReader.Create (projectFileName)), globalPropertiesThatMakeSense, toolsVersion, Projects);
596 IDictionary<string,TargetResult> outs;
597 var ret = projectToBuild.Build (targetNames ?? new string [] {"Build"}, Projects.Loggers, out outs);
598 foreach (var p in outs)
599 targetOutputs [p.Key] = p.Value.Items ?? new ITaskItem [0];
603 public bool BuildProjectFilesInParallel (string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion)
605 throw new NotImplementedException ();
608 public bool IsRunningMultipleNodes {
610 throw new NotImplementedException ();
614 ProjectInstance GetProjectInstance (string projectFileName, string toolsVersion)
616 string fullPath = Path.GetFullPath (projectFileName);
617 if (submission.BuildRequest.ProjectFullPath == fullPath)
618 return submission.BuildRequest.ProjectInstance;
619 // FIXME: could also be filtered by global properties
620 // http://msdn.microsoft.com/en-us/library/microsoft.build.evaluation.projectcollection.getloadedprojects.aspx
621 var project = Projects.GetLoadedProjects (projectFileName).FirstOrDefault (p => p.ToolsVersion == toolsVersion);
623 throw new InvalidOperationException (string.Format ("Project '{0}' is not loaded", projectFileName));
624 return submission.BuildManager.GetProjectInstanceForBuild (project);
629 #region IBuildEngine implementation
631 public bool BuildProjectFile (string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs)
633 return BuildProjectFile (projectFileName, targetNames, globalProperties, targetOutputs, Projects.DefaultToolsVersion);
636 public void LogCustomEvent (CustomBuildEventArgs e)
638 event_source.FireCustomEventRaised (this, e);
641 public void LogErrorEvent (BuildErrorEventArgs e)
643 event_source.FireErrorRaised (this, e);
646 public void LogMessageEvent (BuildMessageEventArgs e)
648 event_source.FireMessageRaised (this, e);
651 public void LogWarningEvent (BuildWarningEventArgs e)
653 event_source.FireWarningRaised (this, e);
656 public int ColumnNumberOfTaskNode {
657 get { return current_task.Location != null ? current_task.Location.Column : 0; }
660 public bool ContinueOnError {
661 get { return current_task != null && project.EvaluateCondition (current_task.Condition) && EvaluateContinueOnError (current_task.ContinueOnError); }
664 bool EvaluateContinueOnError (string value)
667 case "WarnAndContinue":
668 case "ErrorAndContinue":
673 // empty means "stop on error", so don't pass empty string to EvaluateCondition().
674 return !string.IsNullOrEmpty (value) && project.EvaluateCondition (value);
677 public int LineNumberOfTaskNode {
678 get { return current_task.Location != null ? current_task.Location.Line : 0; }
681 public string ProjectFileOfTaskNode {
682 get { return current_task.FullPath; }