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.BuildEngine;
32 using Microsoft.Build.Execution;
33 using Microsoft.Build.Framework;
34 using Microsoft.Build.Evaluation;
37 using Microsoft.Build.Exceptions;
39 namespace Microsoft.Build.Internal
48 public BuildEngine4 (BuildSubmission submission)
50 this.submission = submission;
51 event_source = new EventSource ();
52 if (submission.BuildManager.OngoingBuildParameters.Loggers != null)
53 foreach (var l in submission.BuildManager.OngoingBuildParameters.Loggers)
54 l.Initialize (event_source);
57 BuildSubmission submission;
58 ProjectInstance project;
59 ProjectTargetInstance current_target;
60 ProjectTaskInstance current_task;
61 EventSource event_source;
63 public ProjectCollection Projects {
64 get { return submission.BuildManager.OngoingBuildParameters.ProjectCollection; }
68 // While we are not faced to implement those features, there are some modern task execution requirements.
70 // This will have to be available for "out of process" nodes (see NodeAffinity).
71 // NodeAffinity is set per project file at BuildManager.HostServices.
72 // When NodeAffinity is set to OutOfProc, it should probably launch different build host
73 // that runs separate build tasks. (.NET has MSBuildTaskHost.exe which I guess is about that.)
75 // Also note that the complete implementation has to support LoadInSeparateAppDomainAttribute
76 // (which is most likely derived from AppDomainIsolatedBuildTask) that marks a task to run
77 // in separate AppDomain.
79 public void BuildProject (Func<bool> checkCancel, BuildResult result, ProjectInstance project, IEnumerable<string> targetNames, IDictionary<string,string> globalProperties, IDictionary<string,string> targetOutputs, string toolsVersion)
81 var parameters = submission.BuildManager.OngoingBuildParameters;
82 var buildTaskFactory = new BuildTaskFactory (BuildTaskDatabase.GetDefaultTaskDatabase (parameters.GetToolset (toolsVersion)), submission.BuildRequest.ProjectInstance.TaskDatabase);
83 BuildProject (new InternalBuildArguments () { CheckCancel = checkCancel, Result = result, Project = project, TargetNames = targetNames, GlobalProperties = globalProperties, TargetOutputs = targetOutputs, ToolsVersion = toolsVersion, BuildTaskFactory = buildTaskFactory });
86 class InternalBuildArguments
88 public Func<bool> CheckCancel;
89 public BuildResult Result;
90 public ProjectInstance Project;
91 public IEnumerable<string> TargetNames;
92 public IDictionary<string,string> GlobalProperties;
93 public IDictionary<string,string> TargetOutputs;
94 public string ToolsVersion;
95 public BuildTaskFactory BuildTaskFactory;
97 public void AddTargetResult (string targetName, TargetResult targetResult)
99 if (!Result.HasResultsForTarget (targetName))
100 Result.AddResultsForTarget (targetName, targetResult);
104 void BuildProject (InternalBuildArguments args)
106 var request = submission.BuildRequest;
107 var parameters = submission.BuildManager.OngoingBuildParameters;
108 this.project = args.Project;
110 event_source.FireBuildStarted (this, new BuildStartedEventArgs ("Build Started", null));
112 var initialPropertiesFormatted = "Initial Properties:\n" + string.Join (Environment.NewLine, project.Properties.OrderBy (p => p.Name).Select (p => string.Format ("{0} = {1}", p.Name, p.EvaluatedValue)).ToArray ());
113 event_source.FireMessageRaised (this, new BuildMessageEventArgs (initialPropertiesFormatted, null, null, MessageImportance.Low));
115 // null targets -> success. empty targets -> success(!)
116 if (request.TargetNames == null)
117 args.Result.OverallResult = BuildResultCode.Success;
119 foreach (var targetName in request.TargetNames.Where (t => t != null))
120 args.AddTargetResult (targetName, BuildTargetByName (targetName, args));
122 // FIXME: check .NET behavior, whether cancellation always results in failure.
123 args.Result.OverallResult = args.CheckCancel () ? BuildResultCode.Failure : args.Result.ResultsByTarget.Select (p => p.Value).Any (r => r.ResultCode == TargetResultCode.Failure) ? BuildResultCode.Failure : BuildResultCode.Success;
125 event_source.FireBuildFinished (this, new BuildFinishedEventArgs ("Build Finished.", null, args.Result.OverallResult == BuildResultCode.Success));
128 TargetResult BuildTargetByName (string targetName, InternalBuildArguments args)
130 var targetResult = new TargetResult ();
132 var request = submission.BuildRequest;
133 var parameters = submission.BuildManager.OngoingBuildParameters;
134 ProjectTargetInstance target;
136 // FIXME: check skip condition
138 targetResult.Skip ();
139 // null key is allowed and regarded as blind success(!) (as long as it could retrieve target)
140 else if (!request.ProjectInstance.Targets.TryGetValue (targetName, out target))
141 targetResult.Failure (new InvalidOperationException (string.Format ("target '{0}' was not found in project '{1}'", targetName, project.FullPath)));
143 current_target = target;
145 if (!DoBuildTarget (targetResult, args))
148 current_target = null;
150 Func<string,ITaskItem> creator = s => new TargetOutputTaskItem () { ItemSpec = s };
151 var items = args.Project.GetAllItems (target.Outputs, string.Empty, creator, creator, s => true, (t, s) => {
153 targetResult.Success (items);
154 event_source.FireTargetFinished (this, new TargetFinishedEventArgs ("Target Finished", null, targetName, project.FullPath, target.FullPath, true));
159 bool DoBuildTarget (TargetResult targetResult, InternalBuildArguments args)
161 var request = submission.BuildRequest;
162 var target = current_target;
164 // process DependsOnTargets first.
165 foreach (var dep in project.ExpandString (target.DependsOnTargets).Split (';').Where (s => !string.IsNullOrEmpty (s)).Select (s => s.Trim ())) {
166 var result = BuildTargetByName (dep, args);
167 args.AddTargetResult (dep, result);
168 if (result.ResultCode == TargetResultCode.Failure) {
169 targetResult.Failure (null);
174 event_source.FireTargetStarted (this, new TargetStartedEventArgs ("Target Started", null, target.Name, project.FullPath, target.FullPath));
176 // Here we check cancellation (only after TargetStarted event).
177 if (args.CheckCancel ()) {
178 targetResult.Failure (new BuildAbortedException ("Build has canceled"));
182 var propsToRestore = new Dictionary<string,string> ();
183 var itemsToRemove = new List<ProjectItemInstance> ();
185 foreach (var c in target.Children.OfType<ProjectPropertyGroupTaskInstance> ()) {
186 if (!args.Project.EvaluateCondition (c.Condition))
188 foreach (var p in c.Properties) {
189 if (!args.Project.EvaluateCondition (p.Condition))
191 var value = args.Project.ExpandString (p.Value);
192 propsToRestore.Add (p.Name, project.GetPropertyValue (value));
193 project.SetProperty (p.Name, value);
196 foreach (var c in target.Children.OfType<ProjectItemGroupTaskInstance> ()) {
197 if (!args.Project.EvaluateCondition (c.Condition))
199 foreach (var item in c.Items) {
200 Func<string,ProjectItemInstance> creator = i => new ProjectItemInstance (project, item.ItemType, item.Metadata.Select (m => new KeyValuePair<string,string> (m.Name, m.Value)), i);
201 foreach (var ti in project.GetAllItems (item.Include, item.Exclude, creator, creator, s => s == item.ItemType, (ti, s) => ti.SetMetadata ("RecurseDir", s)))
202 itemsToRemove.Add (ti);
205 foreach (var c in target.Children.OfType<ProjectOnErrorInstance> ()) {
206 if (!args.Project.EvaluateCondition (c.Condition))
208 throw new NotImplementedException ();
210 foreach (var ti in target.Children.OfType<ProjectTaskInstance> ()) {
211 var host = request.HostServices == null ? null : request.HostServices.GetHostObject (request.ProjectFullPath, target.Name, ti.Name);
212 if (!args.Project.EvaluateCondition (ti.Condition)) {
213 event_source.FireMessageRaised (this, new BuildMessageEventArgs (string.Format ("Task '{0}' was skipped because condition '{1}' wasn't met.", ti.Name, ti.Condition), null, null, MessageImportance.Low));
218 var factoryIdentityParameters = new Dictionary<string,string> ();
220 factoryIdentityParameters ["MSBuildRuntime"] = ti.MSBuildRuntime;
221 factoryIdentityParameters ["MSBuildArchitecture"] = ti.MSBuildArchitecture;
223 var task = args.BuildTaskFactory.CreateTask (ti.Name, factoryIdentityParameters, this);
224 event_source.FireMessageRaised (this, new BuildMessageEventArgs (string.Format ("Using task {0} from {1}", ti.Name, task.GetType ().AssemblyQualifiedName), null, null, MessageImportance.Low));
225 task.HostObject = host;
226 task.BuildEngine = this;
227 // FIXME: this cannot be that simple, value has to be converted to the appropriate target type.
228 var props = task.GetType ().GetProperties ()
229 .Where (p => p.CanWrite && p.GetCustomAttributes (typeof(RequiredAttribute), true).Any ());
230 var missings = props.Where (p => !ti.Parameters.Any (tp => tp.Key.Equals (p.Name, StringComparison.OrdinalIgnoreCase)));
232 throw new InvalidOperationException (string.Format ("Task {0} of type {1} is used without specifying mandatory property: {2}",
233 ti.Name, task.GetType (), string.Join (", ", missings.Select (p => p.Name).ToArray ())));
234 foreach (var p in ti.Parameters) {
235 var prop = task.GetType ().GetProperty (p.Key);
236 var value = project.ExpandString (p.Value);
238 throw new InvalidOperationException (string.Format ("Task {0} does not have property {1}", ti.Name, p.Key));
240 throw new InvalidOperationException (string.Format ("Task {0} has property {1} but it is read-only.", ti.Name, p.Key));
241 prop.SetValue (task, ConvertTo (value, prop.PropertyType), null);
243 event_source.FireTaskStarted (this, new TaskStartedEventArgs ("Task Started", null, project.FullPath, ti.FullPath, ti.Name));
244 if (!task.Execute ()) {
245 event_source.FireTaskFinished (this, new TaskFinishedEventArgs ("Task Finished", null, project.FullPath, ti.FullPath, ti.Name, false));
246 targetResult.Failure (null);
247 if (!ContinueOnError) {
248 event_source.FireTargetFinished (this, new TargetFinishedEventArgs ("Target Failed", null, target.Name, project.FullPath, target.FullPath, false));
252 event_source.FireTaskFinished (this, new TaskFinishedEventArgs ("Task Finished", null, project.FullPath, ti.FullPath, ti.Name, true));
253 foreach (var to in ti.Outputs) {
254 var toItem = to as ProjectTaskOutputItemInstance;
255 var toProp = to as ProjectTaskOutputPropertyInstance;
256 string taskParameter = toItem != null ? toItem.TaskParameter : toProp.TaskParameter;
257 var pi = task.GetType ().GetProperty (taskParameter);
259 throw new InvalidOperationException (string.Format ("Task {0} does not have property {1} specified as TaskParameter", ti.Name, toItem.TaskParameter));
261 throw new InvalidOperationException (string.Format ("Task {0} has property {1} specified as TaskParameter, but it is write-only", ti.Name, toItem.TaskParameter));
263 args.Project.AddItem (toItem.ItemType, ConvertFrom (pi.GetValue (task, null)));
265 args.Project.SetProperty (toProp.PropertyName, ConvertFrom (pi.GetValue (task, null)));
270 // restore temporary property state to the original state.
271 foreach (var p in propsToRestore) {
272 if (p.Value == string.Empty)
273 project.RemoveProperty (p.Key);
275 project.SetProperty (p.Key, p.Value);
277 foreach (var item in itemsToRemove)
278 project.RemoveItem (item);
283 object ConvertTo (string source, Type targetType)
285 if (targetType == typeof (ITaskItem) || targetType.IsSubclassOf (typeof (ITaskItem)))
286 return new TargetOutputTaskItem () { ItemSpec = source };
287 if (targetType.IsArray)
288 return new ArrayList (source.Split (';').Where (s => !string.IsNullOrEmpty (s)).Select (s => ConvertTo (s, targetType.GetElementType ())).ToArray ())
289 .ToArray (targetType.GetElementType ());
291 return Convert.ChangeType (source, targetType);
294 string ConvertFrom (object source)
298 if (source is ITaskItem)
299 return ((ITaskItem) source).ItemSpec;
300 if (source.GetType ().IsArray)
301 return string.Join (":", ((Array) source).Cast<object> ().Select (o => ConvertFrom (o)).ToArray ());
303 return (string) Convert.ChangeType (source, typeof (string));
306 class TargetOutputTaskItem : ITaskItem2
308 Hashtable metadata = new Hashtable ();
310 #region ITaskItem2 implementation
311 public string GetMetadataValueEscaped (string metadataName)
313 return ProjectCollection.Escape ((string) metadata [metadataName]);
315 public void SetMetadataValueLiteral (string metadataName, string metadataValue)
317 metadata [metadataName] = ProjectCollection.Unescape (metadataValue);
319 public IDictionary CloneCustomMetadataEscaped ()
321 var ret = new Hashtable ();
322 foreach (DictionaryEntry e in metadata)
323 ret [e.Key] = ProjectCollection.Escape ((string) e.Value);
326 public string EvaluatedIncludeEscaped {
327 get { return ProjectCollection.Escape (ItemSpec); }
328 set { ItemSpec = ProjectCollection.Unescape (value); }
331 #region ITaskItem implementation
332 public IDictionary CloneCustomMetadata ()
334 return new Hashtable (metadata);
336 public void CopyMetadataTo (ITaskItem destinationItem)
338 foreach (DictionaryEntry e in metadata)
339 destinationItem.SetMetadata ((string) e.Key, (string) e.Value);
341 public string GetMetadata (string metadataName)
343 return (string) metadata [metadataName];
345 public void RemoveMetadata (string metadataName)
347 metadata.Remove (metadataName);
349 public void SetMetadata (string metadataName, string metadataValue)
351 metadata [metadataName] = metadataValue;
353 public string ItemSpec { get; set; }
354 public int MetadataCount {
355 get { return metadata.Count; }
357 public ICollection MetadataNames {
358 get { return metadata.Keys; }
364 #region IBuildEngine4 implementation
366 // task objects are not in use anyways though...
368 class TaskObjectRegistration
370 public TaskObjectRegistration (object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection)
375 AllowEarlyCollection = allowEarlyCollection;
377 public object Key { get; private set; }
378 public object Object { get; private set; }
379 public RegisteredTaskObjectLifetime Lifetime { get; private set; }
380 public bool AllowEarlyCollection { get; private set; }
383 List<TaskObjectRegistration> task_objects = new List<TaskObjectRegistration> ();
385 public object GetRegisteredTaskObject (object key, RegisteredTaskObjectLifetime lifetime)
387 var reg = task_objects.FirstOrDefault (t => t.Key == key && t.Lifetime == lifetime);
388 return reg != null ? reg.Object : null;
391 public void RegisterTaskObject (object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection)
393 task_objects.Add (new TaskObjectRegistration (key, obj, lifetime, allowEarlyCollection));
396 public object UnregisterTaskObject (object key, RegisteredTaskObjectLifetime lifetime)
398 var reg = task_objects.FirstOrDefault (t => t.Key == key && t.Lifetime == lifetime);
400 task_objects.Remove (reg);
406 #region IBuildEngine3 implementation
408 public BuildEngineResult BuildProjectFilesInParallel (string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<string>[] removeGlobalProperties, string[] toolsVersion, bool returnTargetOutputs)
410 throw new NotImplementedException ();
413 public void Reacquire ()
415 throw new NotImplementedException ();
420 throw new NotImplementedException ();
425 #region IBuildEngine2 implementation
427 public bool BuildProjectFile (string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion)
429 var proj = GetProjectInstance (projectFileName, toolsVersion);
430 var globalPropertiesThatMakeSense = new Dictionary<string,string> ();
431 foreach (DictionaryEntry p in globalProperties)
432 globalPropertiesThatMakeSense [(string) p.Key] = (string) p.Value;
433 var result = new BuildResult ();
434 var outputs = new Dictionary<string, string> ();
435 BuildProject (() => false, result, proj, targetNames, globalPropertiesThatMakeSense, outputs, toolsVersion);
436 foreach (var p in outputs)
437 targetOutputs [p.Key] = p.Value;
438 return result.OverallResult == BuildResultCode.Success;
441 public bool BuildProjectFilesInParallel (string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion)
443 throw new NotImplementedException ();
446 public bool IsRunningMultipleNodes {
448 throw new NotImplementedException ();
452 ProjectInstance GetProjectInstance (string projectFileName, string toolsVersion)
454 string fullPath = Path.GetFullPath (projectFileName);
455 if (submission.BuildRequest.ProjectFullPath == fullPath)
456 return submission.BuildRequest.ProjectInstance;
457 // FIXME: could also be filtered by global properties
458 // http://msdn.microsoft.com/en-us/library/microsoft.build.evaluation.projectcollection.getloadedprojects.aspx
459 var project = Projects.GetLoadedProjects (projectFileName).FirstOrDefault (p => p.ToolsVersion == toolsVersion);
461 throw new InvalidOperationException (string.Format ("Project '{0}' is not loaded", projectFileName));
462 return submission.BuildManager.GetProjectInstanceForBuild (project);
467 #region IBuildEngine implementation
469 public bool BuildProjectFile (string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs)
471 return BuildProjectFile (projectFileName, targetNames, globalProperties, targetOutputs, Projects.DefaultToolsVersion);
474 public void LogCustomEvent (CustomBuildEventArgs e)
476 event_source.FireCustomEventRaised (this, e);
479 public void LogErrorEvent (BuildErrorEventArgs e)
481 event_source.FireErrorRaised (this, e);
484 public void LogMessageEvent (BuildMessageEventArgs e)
486 event_source.FireMessageRaised (this, e);
489 public void LogWarningEvent (BuildWarningEventArgs e)
491 event_source.FireWarningRaised (this, e);
494 public int ColumnNumberOfTaskNode {
495 get { return current_task.Location != null ? current_task.Location.Column : 0; }
498 public bool ContinueOnError {
499 get { return current_task != null && project.EvaluateCondition (current_task.Condition) && EvaluateContinueOnError (current_task.ContinueOnError); }
502 bool EvaluateContinueOnError (string value)
505 case "WarnAndContinue":
506 case "ErrorAndContinue":
511 // empty means "stop on error", so don't pass empty string to EvaluateCondition().
512 return !string.IsNullOrEmpty (value) && project.EvaluateCondition (value);
515 public int LineNumberOfTaskNode {
516 get { return current_task.Location != null ? current_task.Location.Line : 0; }
519 public string ProjectFileOfTaskNode {
520 get { return current_task.FullPath; }