File: Engine.cs

package info (click to toggle)
mono 2.10.8.1-8+deb7u1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 371,404 kB
  • ctags: 440,979
  • sloc: cs: 2,625,726; xml: 1,867,358; ansic: 394,850; sh: 13,823; makefile: 9,937; perl: 2,231; asm: 716; python: 473; cpp: 376; sql: 95; sed: 16
file content (595 lines) | stat: -rw-r--r-- 17,773 bytes parent folder | download
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
//
// Engine.cs: Main engine of XBuild.
//
// Author:
//   Marek Sieradzki (marek.sieradzki@gmail.com)
// 
// (C) 2005 Marek Sieradzki
//
// 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.

#if NET_2_0

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.XBuild.Utilities;

namespace Microsoft.Build.BuildEngine {
	public class Engine {
		
		string			binPath;
		bool			buildEnabled;
		Dictionary<string, TaskDatabase> defaultTasksTableByToolsVersion;
		const string		defaultTasksProjectName = "Microsoft.Common.tasks";
		EventSource		eventSource;
		bool			buildStarted;
		//ToolsetDefinitionLocations toolsetLocations;
		BuildPropertyGroup	global_properties;
		//IDictionary		importedProjects;
		List <ILogger>		loggers;
		//bool			onlyLogCriticalEvents;
		Dictionary <string, Project>	projects;
		string defaultToolsVersion;

		// the key here represents the project+target+global_properties set
		Dictionary <string, ITaskItem[]> builtTargetsOutputByName;
		Stack<Project> currentlyBuildingProjectsStack;

		static Engine		globalEngine;
		static Version		version;

		static Engine ()
		{
			version = new Version ("0.1");
		}
		
		public Engine ()
			: this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
		{
		}

		public Engine (ToolsetDefinitionLocations locations)
			: this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
		{
			//toolsetLocations = locations;
		}
		
		public Engine (BuildPropertyGroup globalProperties)
			: this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
		{
			this.global_properties = globalProperties;
		}

		public Engine (BuildPropertyGroup globalProperties, ToolsetDefinitionLocations locations)
			: this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
		{
			this.global_properties = globalProperties;
			//toolsetLocations = locations;
		}

		// engine should be invoked with path where binary files are
		// to find microsoft.build.tasks
		public Engine (string binPath)
		{
			this.binPath = binPath;
			this.buildEnabled = true;
			this.projects = new Dictionary <string, Project> ();
			this.eventSource = new EventSource ();
			this.loggers = new List <ILogger> ();
			this.buildStarted = false;
			this.global_properties = new BuildPropertyGroup ();
			this.builtTargetsOutputByName = new Dictionary<string, ITaskItem[]> ();
			this.currentlyBuildingProjectsStack = new Stack<Project> ();
			this.Toolsets = new ToolsetCollection ();
			LoadDefaultToolsets ();
			defaultTasksTableByToolsVersion = new Dictionary<string, TaskDatabase> ();
		}

		//FIXME: should be loaded from config file
		void LoadDefaultToolsets ()
		{
			Toolsets.Add (new Toolset ("2.0",
						ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20)));
			Toolsets.Add (new Toolset ("3.0",
						ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version30)));
			Toolsets.Add (new Toolset ("3.5",
						ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35)));
#if NET_4_0
			Toolsets.Add (new Toolset ("4.0",
						ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40)));
#endif
		}
		
		[MonoTODO]
		public bool BuildProject (Project project)
		{
			if (project == null)
				throw new ArgumentException ("project");
			builtTargetsOutputByName.Clear ();
			return project.Build ();
		}
		
		[MonoTODO]
		public bool BuildProject (Project project, string targetName)
		{
			if (project == null)
				throw new ArgumentException ("project");
			if (targetName == null)
				return false;

			return BuildProject (project, new string[] { targetName}, null, BuildSettings.None);
		}
		
		[MonoTODO]
		public bool BuildProject (Project project, string[] targetNames)
		{
			return BuildProject (project, targetNames, null, BuildSettings.None);
		}

		[MonoTODO]
		public bool BuildProject (Project project,
					  string[] targetNames,
					  IDictionary targetOutputs)
		{
			return BuildProject (project, targetNames, targetOutputs, BuildSettings.None);
		}
		
		public bool BuildProject (Project project,
					  string[] targetNames,
					  IDictionary targetOutputs,
					  BuildSettings buildFlags)
		{
			if (project == null)
				throw new ArgumentException ("project");
			if (targetNames == null)
				return false;

			if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
				builtTargetsOutputByName.Clear ();

			if (defaultToolsVersion != null)
				// it has been explicitly set, xbuild does this..
				project.ToolsVersion = defaultToolsVersion;
			return project.Build (targetNames, targetOutputs, buildFlags);
		}

		[MonoTODO]
		public bool BuildProjectFile (string projectFile)
		{
			return BuildProjectFile (projectFile, new string [0]);
		}
		
		[MonoTODO]
		public bool BuildProjectFile (string projectFile,
					      string targetName)
		{
			return BuildProjectFile (projectFile,
			                         targetName == null ? new string [0] : new string [] {targetName});
		}
		
		[MonoTODO]
		public bool BuildProjectFile (string projectFile,
					      string[] targetNames)
		{
			return BuildProjectFile (projectFile, targetNames, null);
		}
		
		[MonoTODO]
		public bool BuildProjectFile (string projectFile,
					      string[] targetNames,
					      BuildPropertyGroup globalProperties)
		{
			return BuildProjectFile (projectFile, targetNames, globalProperties, null, BuildSettings.None);
		}
		
		[MonoTODO]
		public bool BuildProjectFile (string projectFile,
					      string[] targetNames,
					      BuildPropertyGroup globalProperties,
					      IDictionary targetOutputs)
		{
			return BuildProjectFile (projectFile, targetNames, globalProperties, targetOutputs, BuildSettings.None);
		}
		
		public bool BuildProjectFile (string projectFile,
					      string[] targetNames,
					      BuildPropertyGroup globalProperties,
					      IDictionary targetOutputs,
					      BuildSettings buildFlags)
		{
			return BuildProjectFile (projectFile, targetNames, globalProperties, targetOutputs, buildFlags, null);
		}
			
		//FIXME: add a test for null @toolsVersion
		public bool BuildProjectFile (string projectFile,
					      string[] targetNames,
					      BuildPropertyGroup globalProperties,
					      IDictionary targetOutputs,
					      BuildSettings buildFlags, string toolsVersion)
		{
			bool result = false;
			try {
				StartEngineBuild ();
				result = BuildProjectFileInternal (projectFile, targetNames, globalProperties, targetOutputs, buildFlags, toolsVersion);
				return result;
			} catch (InvalidProjectFileException ie) {
				this.LogErrorWithFilename (projectFile, ie.Message);
				this.LogMessage (MessageImportance.Low, String.Format ("{0}: {1}", projectFile, ie.ToString ()));
				return false;
			} catch (Exception e) {
				if (buildStarted) {
					this.LogErrorWithFilename (projectFile, e.Message);
					this.LogMessage (MessageImportance.Low, String.Format ("{0}: {1}", projectFile, e.ToString ()));
				}
				throw;
			} finally {
				EndEngineBuild (result);
			}
		}

		bool BuildProjectFileInternal (string projectFile,
					      string[] targetNames,
					      BuildPropertyGroup globalProperties,
					      IDictionary targetOutputs,
					      BuildSettings buildFlags, string toolsVersion)
		{

			if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
				builtTargetsOutputByName.Clear ();

			Project project;

			bool newProject = false;
			if (!projects.TryGetValue (projectFile, out project)) {
				project = CreateNewProject ();
				newProject = true;
			}

			BuildPropertyGroup engine_old_grp = null;
			BuildPropertyGroup project_old_grp = null;
			if (globalProperties != null) {
				engine_old_grp = GlobalProperties.Clone (true);
				project_old_grp = project.GlobalProperties.Clone (true);

				// Override project's global properties with the
				// ones explicitlcur_y specified here
				foreach (BuildProperty bp in globalProperties)
					project.GlobalProperties.AddProperty (bp);

				if (!newProject)
					project.NeedToReevaluate ();
			}

			if (newProject)
				project.Load (projectFile);

			try {
				string oldProjectToolsVersion = project.ToolsVersion;
				if (String.IsNullOrEmpty (toolsVersion) && defaultToolsVersion != null)
					// no tv specified, let the project inherit it from the
					// engine. 'defaultToolsVersion' will be effective only
					// it has been overridden. Otherwise, the project's own
					// tv will be used.
					project.ToolsVersion = defaultToolsVersion;
				else
					project.ToolsVersion = toolsVersion;

				try {
					return project.Build (targetNames, targetOutputs, buildFlags);
				} finally {
					project.ToolsVersion = oldProjectToolsVersion;
				}
			} finally {
				if (globalProperties != null) {
					GlobalProperties = engine_old_grp;
					project.GlobalProperties = project_old_grp;
				}
			}
		}

		void CheckBinPath ()
		{
			if (BinPath == null) {
				throw new InvalidOperationException ("Before a project can be instantiated, " +
					"Engine.BinPath must be set to the location on disk where MSBuild " + 
					"is installed. This is used to evaluate $(MSBuildBinPath).");
			}
		}

		public Project CreateNewProject ()
		{
			return new Project (this);
		}

		public Project GetLoadedProject (string projectFullFileName)
		{
			if (projectFullFileName == null)
				throw new ArgumentNullException ("projectFullFileName");
			
			Project project;
			projects.TryGetValue (projectFullFileName, out project);

			return project;
		}

		internal void RemoveLoadedProject (Project p)
		{
			if (!String.IsNullOrEmpty (p.FullFileName)) {
				ClearBuiltTargetsForProject (p);
				projects.Remove (p.FullFileName);
			}
		}

		internal void AddLoadedProject (Project p)
		{
			if (p.FullFileName != String.Empty)
				projects.Add (p.FullFileName, p);
		}
	
		public void UnloadProject (Project project)
		{
			if (project == null)
				throw new ArgumentNullException ("project");

			if (project.ParentEngine != this)
				throw new InvalidOperationException ("The \"Project\" object specified does not belong to the correct \"Engine\" object.");
			
			project.CheckUnloaded ();
			
			RemoveLoadedProject (project);
			
			project.Unload ();
		}

		public void UnloadAllProjects ()
		{
			IList<Project> values = new List<Project> (projects.Values);
			foreach (Project p in values)
				UnloadProject (p);
		}

		[MonoTODO]
		public void RegisterLogger (ILogger logger)
		{
			if (logger == null)
				throw new ArgumentNullException ("logger");
			
			logger.Initialize (eventSource);
			loggers.Add (logger);
		}
		
		[MonoTODO]
		public void UnregisterAllLoggers ()
		{
			// FIXME: check if build succeeded
			// FIXME: it shouldn't be here
			if (buildStarted)
				LogBuildFinished (true);
			foreach (ILogger i in loggers) {
				i.Shutdown ();
			}
			loggers.Clear ();
		}

		void StartEngineBuild ()
		{
			if (!buildStarted) {
				LogBuildStarted ();
				buildStarted = true;
			}
		}

		void EndEngineBuild (bool succeeded)
		{
			if (buildStarted && currentlyBuildingProjectsStack.Count == 0) {
				LogBuildFinished (succeeded);
				buildStarted = false;
			}
		}

		internal void StartProjectBuild (Project project, string [] target_names)
		{
			StartEngineBuild ();

			if (currentlyBuildingProjectsStack.Count == 0 ||
				String.Compare (currentlyBuildingProjectsStack.Peek ().FullFileName, project.FullFileName) != 0)
					LogProjectStarted (project, target_names);

			currentlyBuildingProjectsStack.Push (project);
		}

		internal void EndProjectBuild (Project project, bool succeeded)
		{
			if (!buildStarted)
				throw new Exception ("build isnt started currently");

			Project top_project = currentlyBuildingProjectsStack.Pop ();

			if (String.Compare (project.FullFileName, top_project.FullFileName) != 0)
				throw new Exception (String.Format (
							"INTERNAL ERROR: Project finishing is not the same as the one on top " +
							"of the stack. Project: {0} Top of stack: {1}",
							project.FullFileName, top_project.FullFileName));

			if (currentlyBuildingProjectsStack.Count == 0 ||
				String.Compare (top_project.FullFileName, currentlyBuildingProjectsStack.Peek ().FullFileName) != 0)
				LogProjectFinished (top_project, succeeded);

			EndEngineBuild (succeeded);
		}

		internal void ClearBuiltTargetsForProject (Project project)
		{
			string project_key = project.GetKeyForTarget (String.Empty, false);
			var to_remove_keys = BuiltTargetsOutputByName.Keys.Where (key => key.StartsWith (project_key)).ToList ();
			foreach (string to_remove_key in to_remove_keys)
				BuiltTargetsOutputByName.Remove (to_remove_key);
		}

		void LogProjectStarted (Project project, string [] target_names)
		{
			string targets;
			if (target_names == null || target_names.Length == 0)
				targets = String.Empty;
			else
				targets = String.Join (";", target_names);

			ProjectStartedEventArgs psea = new ProjectStartedEventArgs ("Project started.", null, project.FullFileName, targets,
					project.EvaluatedPropertiesAsDictionaryEntries, project.EvaluatedItemsByNameAsDictionaryEntries);

			eventSource.FireProjectStarted (this, psea);
		}

		void LogProjectFinished (Project project, bool succeeded)
		{
			ProjectFinishedEventArgs pfea;
			pfea = new ProjectFinishedEventArgs ("Project started.", null, project.FullFileName, succeeded);
			eventSource.FireProjectFinished (this, pfea);
		}

		void LogBuildStarted ()
		{
			BuildStartedEventArgs bsea;
			bsea = new BuildStartedEventArgs ("Build started.", null);
			eventSource.FireBuildStarted (this, bsea);
		}
		
		void LogBuildFinished (bool succeeded)
		{
			BuildFinishedEventArgs bfea;
			bfea = new BuildFinishedEventArgs ("Build finished.", null, succeeded);
			eventSource.FireBuildFinished (this, bfea);
		}

		internal TaskDatabase GetDefaultTasks (string toolsVersion)
		{
			TaskDatabase db;
			if (defaultTasksTableByToolsVersion.TryGetValue (toolsVersion, out db))
				return db;

			var toolset = Toolsets [toolsVersion];
			if (toolset == null)
				throw new UnknownToolsVersionException (toolsVersion);

			string toolsPath = toolset.ToolsPath;
			string tasksFile = Path.Combine (toolsPath, defaultTasksProjectName);
			this.LogMessage (MessageImportance.Low, "Loading default tasks for ToolsVersion: {0} from {1}", toolsVersion, tasksFile);

			// set a empty taskdb here, because the project loading the tasks
			// file will try to get the default task db
			defaultTasksTableByToolsVersion [toolsVersion] = new TaskDatabase ();

			db = defaultTasksTableByToolsVersion [toolsVersion] = RegisterDefaultTasks (tasksFile);

			return db;
		}
		
		TaskDatabase RegisterDefaultTasks (string tasksFile)
		{
			Project defaultTasksProject = CreateNewProject ();
			TaskDatabase db;
			
			if (File.Exists (tasksFile)) {
				defaultTasksProject.Load (tasksFile);
				db = defaultTasksProject.TaskDatabase;
			} else {
				this.LogWarning ("Default tasks file {0} not found, ignoring.", tasksFile);
				db = new TaskDatabase ();
			}

			return db;
		}

		public string BinPath {
			get { return binPath; }
			set { binPath = value; }
		}

		public bool BuildEnabled {
			get { return buildEnabled; }
			set { buildEnabled = value; }
		}

		public static Version Version {
			get { return version; }
		}

		public static Engine GlobalEngine {
			get {
				if (globalEngine == null)
					globalEngine = new Engine ();
				return globalEngine;
			}
		}

		public BuildPropertyGroup GlobalProperties {
			get { return global_properties; }
			set { global_properties = value; }
		}
		
		public ToolsetCollection Toolsets {
			get; private set;
		}

		public string DefaultToolsVersion {
			get {
				if (String.IsNullOrEmpty (defaultToolsVersion))
#if NET_4_0
					return "4.0";
#elif NET_3_5
					return "3.5";
#else
					return "2.0";
#endif
				
				return defaultToolsVersion;
			}
			set {
				if (Toolsets [value] == null)
					throw new UnknownToolsVersionException (value);
				defaultToolsVersion = value;
			}
		}
		
		public bool IsBuilding {
			get { return buildStarted; }
		}
		
		public bool OnlyLogCriticalEvents {
			get { return eventSource.OnlyLogCriticalEvents; }
			set { eventSource.OnlyLogCriticalEvents = value; }
		}
		
		internal EventSource EventSource {
			get { return eventSource; }
		}
		
		internal Dictionary<string, ITaskItem[]> BuiltTargetsOutputByName {
			get { return builtTargetsOutputByName; }
		}
	}
}

#endif