2 // Engine.cs: Main engine of XBuild.
5 // Marek Sieradzki (marek.sieradzki@gmail.com)
7 // (C) 2005 Marek Sieradzki
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;
33 using Microsoft.Build.Framework;
34 using Microsoft.Build.Utilities;
35 using Mono.XBuild.Utilities;
37 namespace Microsoft.Build.BuildEngine {
42 Dictionary<string, TaskDatabase> defaultTasksTableByToolsVersion;
43 const string defaultTasksProjectName = "Microsoft.Common.tasks";
44 EventSource eventSource;
46 //ToolsetDefinitionLocations toolsetLocations;
47 BuildPropertyGroup global_properties;
48 //IDictionary importedProjects;
49 List <ILogger> loggers;
50 //bool onlyLogCriticalEvents;
51 Dictionary <string, Project> projects;
52 string defaultToolsVersion;
54 // the key here represents the project+target+global_properties set
55 Dictionary <string, ITaskItem[]> builtTargetsOutputByName;
56 Stack<Project> currentlyBuildingProjectsStack;
58 static Engine globalEngine;
59 static Version version;
63 version = new Version ("0.1");
67 : this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
71 public Engine (ToolsetDefinitionLocations locations)
72 : this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
74 //toolsetLocations = locations;
77 public Engine (BuildPropertyGroup globalProperties)
78 : this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
80 this.global_properties = globalProperties;
83 public Engine (BuildPropertyGroup globalProperties, ToolsetDefinitionLocations locations)
84 : this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
86 this.global_properties = globalProperties;
87 //toolsetLocations = locations;
90 // engine should be invoked with path where binary files are
91 // to find microsoft.build.tasks
92 public Engine (string binPath)
94 this.binPath = binPath;
95 this.buildEnabled = true;
96 this.projects = new Dictionary <string, Project> ();
97 this.eventSource = new EventSource ();
98 this.loggers = new List <ILogger> ();
99 this.buildStarted = false;
100 this.global_properties = new BuildPropertyGroup ();
101 this.builtTargetsOutputByName = new Dictionary<string, ITaskItem[]> ();
102 this.currentlyBuildingProjectsStack = new Stack<Project> ();
103 this.Toolsets = new ToolsetCollection ();
104 LoadDefaultToolsets ();
105 defaultTasksTableByToolsVersion = new Dictionary<string, TaskDatabase> ();
108 //FIXME: should be loaded from config file
109 void LoadDefaultToolsets ()
111 Toolsets.Add (new Toolset ("2.0",
112 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20)));
113 Toolsets.Add (new Toolset ("3.0",
114 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version30)));
115 Toolsets.Add (new Toolset ("3.5",
116 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35)));
118 Toolsets.Add (new Toolset ("4.0",
119 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40)));
124 public bool BuildProject (Project project)
127 throw new ArgumentException ("project");
128 builtTargetsOutputByName.Clear ();
129 return project.Build ();
133 public bool BuildProject (Project project, string targetName)
136 throw new ArgumentException ("project");
137 if (targetName == null)
140 return BuildProject (project, new string[] { targetName}, null, BuildSettings.None);
144 public bool BuildProject (Project project, string[] targetNames)
146 return BuildProject (project, targetNames, null, BuildSettings.None);
150 public bool BuildProject (Project project,
151 string[] targetNames,
152 IDictionary targetOutputs)
154 return BuildProject (project, targetNames, targetOutputs, BuildSettings.None);
157 public bool BuildProject (Project project,
158 string[] targetNames,
159 IDictionary targetOutputs,
160 BuildSettings buildFlags)
163 throw new ArgumentException ("project");
164 if (targetNames == null)
167 if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
168 builtTargetsOutputByName.Clear ();
170 if (defaultToolsVersion != null)
171 // it has been explicitly set, xbuild does this..
172 project.ToolsVersion = defaultToolsVersion;
173 return project.Build (targetNames, targetOutputs, buildFlags);
177 public bool BuildProjectFile (string projectFile)
179 return BuildProjectFile (projectFile, new string [0]);
183 public bool BuildProjectFile (string projectFile,
186 return BuildProjectFile (projectFile,
187 targetName == null ? new string [0] : new string [] {targetName});
191 public bool BuildProjectFile (string projectFile,
192 string[] targetNames)
194 return BuildProjectFile (projectFile, targetNames, null);
198 public bool BuildProjectFile (string projectFile,
199 string[] targetNames,
200 BuildPropertyGroup globalProperties)
202 return BuildProjectFile (projectFile, targetNames, globalProperties, null, BuildSettings.None);
206 public bool BuildProjectFile (string projectFile,
207 string[] targetNames,
208 BuildPropertyGroup globalProperties,
209 IDictionary targetOutputs)
211 return BuildProjectFile (projectFile, targetNames, globalProperties, targetOutputs, BuildSettings.None);
214 public bool BuildProjectFile (string projectFile,
215 string[] targetNames,
216 BuildPropertyGroup globalProperties,
217 IDictionary targetOutputs,
218 BuildSettings buildFlags)
220 return BuildProjectFile (projectFile, targetNames, globalProperties, targetOutputs, buildFlags, null);
223 //FIXME: add a test for null @toolsVersion
224 public bool BuildProjectFile (string projectFile,
225 string[] targetNames,
226 BuildPropertyGroup globalProperties,
227 IDictionary targetOutputs,
228 BuildSettings buildFlags, string toolsVersion)
233 result = BuildProjectFileInternal (projectFile, targetNames, globalProperties, targetOutputs, buildFlags, toolsVersion);
235 } catch (InvalidProjectFileException ie) {
236 this.LogErrorWithFilename (projectFile, ie.Message);
237 this.LogMessage (MessageImportance.Low, String.Format ("{0}: {1}", projectFile, ie.ToString ()));
239 } catch (Exception e) {
241 this.LogErrorWithFilename (projectFile, e.Message);
242 this.LogMessage (MessageImportance.Low, String.Format ("{0}: {1}", projectFile, e.ToString ()));
246 EndEngineBuild (result);
250 bool BuildProjectFileInternal (string projectFile,
251 string[] targetNames,
252 BuildPropertyGroup globalProperties,
253 IDictionary targetOutputs,
254 BuildSettings buildFlags, string toolsVersion)
257 if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
258 builtTargetsOutputByName.Clear ();
262 bool newProject = false;
263 if (!projects.TryGetValue (projectFile, out project)) {
264 project = CreateNewProject ();
268 BuildPropertyGroup engine_old_grp = null;
269 BuildPropertyGroup project_old_grp = null;
270 if (globalProperties != null) {
271 engine_old_grp = GlobalProperties.Clone (true);
272 project_old_grp = project.GlobalProperties.Clone (true);
274 // Override project's global properties with the
275 // ones explicitlcur_y specified here
276 foreach (BuildProperty bp in globalProperties)
277 project.GlobalProperties.AddProperty (bp);
280 project.NeedToReevaluate ();
284 project.Load (projectFile);
287 string oldProjectToolsVersion = project.ToolsVersion;
288 if (String.IsNullOrEmpty (toolsVersion) && defaultToolsVersion != null)
289 // no tv specified, let the project inherit it from the
290 // engine. 'defaultToolsVersion' will be effective only
291 // it has been overridden. Otherwise, the project's own
293 project.ToolsVersion = defaultToolsVersion;
295 project.ToolsVersion = toolsVersion;
298 return project.Build (targetNames, targetOutputs, buildFlags);
300 project.ToolsVersion = oldProjectToolsVersion;
303 if (globalProperties != null) {
304 GlobalProperties = engine_old_grp;
305 project.GlobalProperties = project_old_grp;
312 if (BinPath == null) {
313 throw new InvalidOperationException ("Before a project can be instantiated, " +
314 "Engine.BinPath must be set to the location on disk where MSBuild " +
315 "is installed. This is used to evaluate $(MSBuildBinPath).");
319 public Project CreateNewProject ()
321 return new Project (this);
324 public Project GetLoadedProject (string projectFullFileName)
326 if (projectFullFileName == null)
327 throw new ArgumentNullException ("projectFullFileName");
330 projects.TryGetValue (projectFullFileName, out project);
335 internal void RemoveLoadedProject (Project p)
337 if (!String.IsNullOrEmpty (p.FullFileName)) {
338 ClearBuiltTargetsForProject (p);
339 projects.Remove (p.FullFileName);
343 internal void AddLoadedProject (Project p)
345 if (p.FullFileName != String.Empty)
346 projects.Add (p.FullFileName, p);
349 public void UnloadProject (Project project)
352 throw new ArgumentNullException ("project");
354 if (project.ParentEngine != this)
355 throw new InvalidOperationException ("The \"Project\" object specified does not belong to the correct \"Engine\" object.");
357 project.CheckUnloaded ();
359 RemoveLoadedProject (project);
364 public void UnloadAllProjects ()
366 IList<Project> values = new List<Project> (projects.Values);
367 foreach (Project p in values)
372 public void RegisterLogger (ILogger logger)
375 throw new ArgumentNullException ("logger");
377 logger.Initialize (eventSource);
378 loggers.Add (logger);
382 public void UnregisterAllLoggers ()
384 // FIXME: check if build succeeded
385 // FIXME: it shouldn't be here
387 LogBuildFinished (true);
388 foreach (ILogger i in loggers) {
394 void StartEngineBuild ()
402 void EndEngineBuild (bool succeeded)
404 if (buildStarted && currentlyBuildingProjectsStack.Count == 0) {
405 LogBuildFinished (succeeded);
406 buildStarted = false;
410 internal void StartProjectBuild (Project project, string [] target_names)
414 if (currentlyBuildingProjectsStack.Count == 0 ||
415 String.Compare (currentlyBuildingProjectsStack.Peek ().FullFileName, project.FullFileName) != 0)
416 LogProjectStarted (project, target_names);
418 currentlyBuildingProjectsStack.Push (project);
421 internal void EndProjectBuild (Project project, bool succeeded)
424 throw new Exception ("build isnt started currently");
426 Project top_project = currentlyBuildingProjectsStack.Pop ();
428 if (String.Compare (project.FullFileName, top_project.FullFileName) != 0)
429 throw new Exception (String.Format (
430 "INTERNAL ERROR: Project finishing is not the same as the one on top " +
431 "of the stack. Project: {0} Top of stack: {1}",
432 project.FullFileName, top_project.FullFileName));
434 if (currentlyBuildingProjectsStack.Count == 0 ||
435 String.Compare (top_project.FullFileName, currentlyBuildingProjectsStack.Peek ().FullFileName) != 0)
436 LogProjectFinished (top_project, succeeded);
438 EndEngineBuild (succeeded);
441 internal void ClearBuiltTargetsForProject (Project project)
443 string project_key = project.GetKeyForTarget (String.Empty, false);
444 var to_remove_keys = BuiltTargetsOutputByName.Keys.Where (key => key.StartsWith (project_key)).ToList ();
445 foreach (string to_remove_key in to_remove_keys)
446 BuiltTargetsOutputByName.Remove (to_remove_key);
449 void LogProjectStarted (Project project, string [] target_names)
452 if (target_names == null || target_names.Length == 0)
453 targets = String.Empty;
455 targets = String.Join (";", target_names);
457 ProjectStartedEventArgs psea = new ProjectStartedEventArgs ("Project started.", null, project.FullFileName, targets,
458 project.EvaluatedPropertiesAsDictionaryEntries, project.EvaluatedItemsByNameAsDictionaryEntries);
460 eventSource.FireProjectStarted (this, psea);
463 void LogProjectFinished (Project project, bool succeeded)
465 ProjectFinishedEventArgs pfea;
466 pfea = new ProjectFinishedEventArgs ("Project started.", null, project.FullFileName, succeeded);
467 eventSource.FireProjectFinished (this, pfea);
470 void LogBuildStarted ()
472 BuildStartedEventArgs bsea;
473 bsea = new BuildStartedEventArgs ("Build started.", null);
474 eventSource.FireBuildStarted (this, bsea);
477 void LogBuildFinished (bool succeeded)
479 BuildFinishedEventArgs bfea;
480 bfea = new BuildFinishedEventArgs ("Build finished.", null, succeeded);
481 eventSource.FireBuildFinished (this, bfea);
484 internal TaskDatabase GetDefaultTasks (string toolsVersion)
487 if (defaultTasksTableByToolsVersion.TryGetValue (toolsVersion, out db))
490 var toolset = Toolsets [toolsVersion];
492 throw new UnknownToolsVersionException (toolsVersion);
494 string toolsPath = toolset.ToolsPath;
495 string tasksFile = Path.Combine (toolsPath, defaultTasksProjectName);
496 this.LogMessage (MessageImportance.Low, "Loading default tasks for ToolsVersion: {0} from {1}", toolsVersion, tasksFile);
498 // set a empty taskdb here, because the project loading the tasks
499 // file will try to get the default task db
500 defaultTasksTableByToolsVersion [toolsVersion] = new TaskDatabase ();
502 db = defaultTasksTableByToolsVersion [toolsVersion] = RegisterDefaultTasks (tasksFile);
507 TaskDatabase RegisterDefaultTasks (string tasksFile)
509 Project defaultTasksProject = CreateNewProject ();
512 if (File.Exists (tasksFile)) {
513 defaultTasksProject.Load (tasksFile);
514 db = defaultTasksProject.TaskDatabase;
516 this.LogWarning ("Default tasks file {0} not found, ignoring.", tasksFile);
517 db = new TaskDatabase ();
523 public string BinPath {
524 get { return binPath; }
525 set { binPath = value; }
528 public bool BuildEnabled {
529 get { return buildEnabled; }
530 set { buildEnabled = value; }
533 public static Version Version {
534 get { return version; }
537 public static Engine GlobalEngine {
539 if (globalEngine == null)
540 globalEngine = new Engine ();
545 public BuildPropertyGroup GlobalProperties {
546 get { return global_properties; }
547 set { global_properties = value; }
550 public ToolsetCollection Toolsets {
554 public string DefaultToolsVersion {
556 // This is used as the fall back version if the
557 // project can't find a version to use
558 // Hard-coded to 2.0, so it allows even vs2005 projects
559 // to build correctly, as they won't have a ToolsVersion
561 return String.IsNullOrEmpty (defaultToolsVersion)
563 : defaultToolsVersion;
566 if (Toolsets [value] == null)
567 throw new UnknownToolsVersionException (value);
568 defaultToolsVersion = value;
572 public bool IsBuilding {
573 get { return buildStarted; }
576 public bool OnlyLogCriticalEvents {
577 get { return eventSource.OnlyLogCriticalEvents; }
578 set { eventSource.OnlyLogCriticalEvents = value; }
581 internal EventSource EventSource {
582 get { return eventSource; }
585 internal Dictionary<string, ITaskItem[]> BuiltTargetsOutputByName {
586 get { return builtTargetsOutputByName; }