2 // Project.cs: Project class
5 // Marek Sieradzki (marek.sieradzki@gmail.com)
6 // Ankit Jain (jankit@novell.com)
8 // (C) 2005 Marek Sieradzki
9 // Copyright 2011 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.Specialized;
36 using System.Reflection;
39 using System.Xml.Schema;
40 using Microsoft.Build.Framework;
41 using Mono.XBuild.Framework;
42 using Mono.XBuild.CommandLine;
44 namespace Microsoft.Build.BuildEngine {
45 public class Project {
48 Dictionary <string, List <string>> conditionedProperties;
49 string[] defaultTargets;
51 BuildItemGroup evaluatedItems;
52 BuildItemGroup evaluatedItemsIgnoringCondition;
53 Dictionary <string, BuildItemGroup> evaluatedItemsByName;
54 Dictionary <string, BuildItemGroup> evaluatedItemsByNameIgnoringCondition;
55 BuildPropertyGroup evaluatedProperties;
56 string firstTargetName;
58 BuildPropertyGroup globalProperties;
59 GroupingCollection groupingCollection;
62 BuildItemGroupCollection itemGroups;
63 ImportCollection imports;
64 List<string> initialTargets;
65 Dictionary <string, BuildItemGroup> last_item_group_containing;
66 bool needToReevaluate;
68 BuildPropertyGroupCollection propertyGroups;
70 TaskDatabase taskDatabase;
71 TargetCollection targets;
72 DateTime timeOfLastDirty;
73 UsingTaskCollection usingTasks;
74 XmlDocument xmlDocument;
76 bool initialTargetsBuilt;
78 BuildSettings current_settings;
81 // This is used to keep track of "current" file,
82 // which is then used to set the reserved properties
83 // $(MSBuildThisFile*)
84 Stack<string> this_file_property_stack;
85 ProjectLoadSettings project_load_settings;
88 static string extensions_path;
89 static XmlNamespaceManager manager;
90 static string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
93 : this (Engine.GlobalEngine)
97 public Project (Engine engine) : this (engine, null)
101 public Project (Engine engine, string toolsVersion)
103 parentEngine = engine;
104 ToolsVersion = toolsVersion;
106 buildEnabled = ParentEngine.BuildEnabled;
107 xmlDocument = new XmlDocument ();
108 xmlDocument.PreserveWhitespace = false;
109 xmlDocument.AppendChild (xmlDocument.CreateElement ("Project", XmlNamespace));
110 xmlDocument.DocumentElement.SetAttribute ("xmlns", ns);
112 fullFileName = String.Empty;
113 timeOfLastDirty = DateTime.Now;
114 current_settings = BuildSettings.None;
115 project_load_settings = ProjectLoadSettings.None;
119 initialTargets = new List<string> ();
120 defaultTargets = new string [0];
121 batches = new Stack<Batch> ();
122 this_file_property_stack = new Stack<string> ();
124 globalProperties = new BuildPropertyGroup (null, this, null, false);
125 foreach (BuildProperty bp in parentEngine.GlobalProperties)
126 GlobalProperties.AddProperty (bp.Clone (true));
132 [MonoTODO ("Not tested")]
133 public void AddNewImport (string importLocation,
134 string importCondition)
136 if (importLocation == null)
137 throw new ArgumentNullException ("importLocation");
139 XmlElement importElement = xmlDocument.CreateElement ("Import", XmlNamespace);
140 xmlDocument.DocumentElement.AppendChild (importElement);
141 importElement.SetAttribute ("Project", importLocation);
142 if (!String.IsNullOrEmpty (importCondition))
143 importElement.SetAttribute ("Condition", importCondition);
145 AddImport (importElement, null, false);
146 MarkProjectAsDirty ();
150 public BuildItem AddNewItem (string itemName,
153 return AddNewItem (itemName, itemInclude, false);
156 [MonoTODO ("Adds item not in the same place as MS")]
157 public BuildItem AddNewItem (string itemName,
159 bool treatItemIncludeAsLiteral)
163 if (itemGroups.Count == 0)
164 big = AddNewItemGroup ();
166 if (last_item_group_containing.ContainsKey (itemName)) {
167 big = last_item_group_containing [itemName];
170 BuildItemGroup [] groups = new BuildItemGroup [itemGroups.Count];
171 itemGroups.CopyTo (groups, 0);
176 BuildItem item = big.AddNewItem (itemName, itemInclude, treatItemIncludeAsLiteral);
178 MarkProjectAsDirty ();
184 [MonoTODO ("Not tested")]
185 public BuildItemGroup AddNewItemGroup ()
187 XmlElement element = xmlDocument.CreateElement ("ItemGroup", XmlNamespace);
188 xmlDocument.DocumentElement.AppendChild (element);
190 BuildItemGroup big = new BuildItemGroup (element, this, null, false);
191 itemGroups.Add (big);
192 MarkProjectAsDirty ();
198 [MonoTODO ("Ignores insertAtEndOfProject")]
199 public BuildPropertyGroup AddNewPropertyGroup (bool insertAtEndOfProject)
201 XmlElement element = xmlDocument.CreateElement ("PropertyGroup", XmlNamespace);
202 xmlDocument.DocumentElement.AppendChild (element);
204 BuildPropertyGroup bpg = new BuildPropertyGroup (element, this, null, false);
205 propertyGroups.Add (bpg);
206 MarkProjectAsDirty ();
212 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
213 public void AddNewUsingTaskFromAssemblyFile (string taskName,
216 if (taskName == null)
217 throw new ArgumentNullException ("taskName");
218 if (assemblyFile == null)
219 throw new ArgumentNullException ("assemblyFile");
221 XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
222 xmlDocument.DocumentElement.AppendChild (element);
223 element.SetAttribute ("TaskName", taskName);
224 element.SetAttribute ("AssemblyFile", assemblyFile);
226 UsingTask ut = new UsingTask (element, this, null);
228 MarkProjectAsDirty ();
231 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
232 public void AddNewUsingTaskFromAssemblyName (string taskName,
235 if (taskName == null)
236 throw new ArgumentNullException ("taskName");
237 if (assemblyName == null)
238 throw new ArgumentNullException ("assemblyName");
240 XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
241 xmlDocument.DocumentElement.AppendChild (element);
242 element.SetAttribute ("TaskName", taskName);
243 element.SetAttribute ("AssemblyName", assemblyName);
245 UsingTask ut = new UsingTask (element, this, null);
247 MarkProjectAsDirty ();
250 [MonoTODO ("Not tested")]
253 return Build (new string [0]);
256 [MonoTODO ("Not tested")]
257 public bool Build (string targetName)
259 if (targetName == null)
260 return Build ((string[]) null);
262 return Build (new string [1] { targetName });
265 [MonoTODO ("Not tested")]
266 public bool Build (string [] targetNames)
268 return Build (targetNames, null);
271 [MonoTODO ("Not tested")]
272 public bool Build (string [] targetNames,
273 IDictionary targetOutputs)
275 return Build (targetNames, targetOutputs, BuildSettings.None);
278 [MonoTODO ("Not tested")]
279 public bool Build (string [] targetNames,
280 IDictionary targetOutputs,
281 BuildSettings buildFlags)
285 ParentEngine.StartProjectBuild (this, targetNames);
287 // Invoking this to emit a warning in case of unsupported
289 GetToolsVersionToUse (true);
291 string current_directory = Environment.CurrentDirectory;
293 current_settings = buildFlags;
294 if (!String.IsNullOrEmpty (fullFileName))
295 Directory.SetCurrentDirectory (Path.GetDirectoryName (fullFileName));
297 result = BuildInternal (targetNames, targetOutputs, buildFlags);
298 } catch (InvalidProjectFileException ie) {
299 ParentEngine.LogErrorWithFilename (fullFileName, ie.Message);
300 ParentEngine.LogMessage (MessageImportance.Low, String.Format ("{0}: {1}", fullFileName, ie.ToString ()));
301 } catch (Exception e) {
302 ParentEngine.LogErrorWithFilename (fullFileName, e.Message);
303 ParentEngine.LogMessage (MessageImportance.Low, String.Format ("{0}: {1}", fullFileName, e.ToString ()));
306 ParentEngine.EndProjectBuild (this, result);
307 current_settings = BuildSettings.None;
308 Directory.SetCurrentDirectory (current_directory);
315 bool BuildInternal (string [] targetNames,
316 IDictionary targetOutputs,
317 BuildSettings buildFlags)
320 if (buildFlags == BuildSettings.None) {
321 needToReevaluate = false;
326 ProcessBeforeAndAfterTargets ();
329 if (targetNames == null || targetNames.Length == 0) {
330 if (defaultTargets != null && defaultTargets.Length != 0) {
331 targetNames = defaultTargets;
332 } else if (firstTargetName != null) {
333 targetNames = new string [1] { firstTargetName};
335 if (targets == null || targets.Count == 0) {
336 LogError (fullFileName, "No target found in the project");
344 if (!initialTargetsBuilt) {
345 foreach (string target in initialTargets) {
346 if (!BuildTarget (target.Trim (), targetOutputs))
349 initialTargetsBuilt = true;
352 foreach (string target in targetNames) {
354 throw new ArgumentNullException ("Target name cannot be null");
356 if (!BuildTarget (target.Trim (), targetOutputs))
363 bool BuildTarget (string target_name, IDictionary targetOutputs)
365 if (target_name == null)
366 throw new ArgumentException ("targetNames cannot contain null strings");
368 if (!targets.Exists (target_name)) {
369 LogError (fullFileName, "Target named '{0}' not found in the project.", target_name);
373 string key = GetKeyForTarget (target_name);
374 if (!targets [target_name].Build (key))
378 if (ParentEngine.BuiltTargetsOutputByName.TryGetValue (key, out outputs)) {
379 if (targetOutputs != null)
380 targetOutputs.Add (target_name, outputs);
385 internal string GetKeyForTarget (string target_name)
387 return GetKeyForTarget (target_name, true);
390 internal string GetKeyForTarget (string target_name, bool include_global_properties)
392 // target name is case insensitive
393 return fullFileName + ":" + target_name.ToLower () +
394 (include_global_properties ? (":" + GlobalPropertiesToString (GlobalProperties))
398 string GlobalPropertiesToString (BuildPropertyGroup bgp)
400 StringBuilder sb = new StringBuilder ();
401 foreach (BuildProperty bp in bgp)
402 sb.AppendFormat (" {0}:{1}", bp.Name, bp.FinalValue);
403 return sb.ToString ();
407 void ProcessBeforeAndAfterTargets ()
409 var beforeTable = Targets.AsIEnumerable ()
410 .SelectMany (target => GetTargetNamesFromString (target.BeforeTargets),
411 (target, before_target) => new {before_target, name = target.Name})
412 .ToLookup (x => x.before_target, x => x.name)
413 .ToDictionary (x => x.Key, x => x.Distinct ().ToList ());
415 foreach (var pair in beforeTable) {
416 if (targets.Exists (pair.Key))
417 targets [pair.Key].BeforeThisTargets = pair.Value;
419 LogWarning (FullFileName, "Target '{0}', not found in the project", pair.Key);
422 var afterTable = Targets.AsIEnumerable ()
423 .SelectMany (target => GetTargetNamesFromString (target.AfterTargets),
424 (target, after_target) => new {after_target, name = target.Name})
425 .ToLookup (x => x.after_target, x => x.name)
426 .ToDictionary (x => x.Key, x => x.Distinct ().ToList ());
428 foreach (var pair in afterTable) {
429 if (targets.Exists (pair.Key))
430 targets [pair.Key].AfterThisTargets = pair.Value;
432 LogWarning (FullFileName, "Target '{0}', not found in the project", pair.Key);
436 string[] GetTargetNamesFromString (string targets)
438 Expression expr = new Expression ();
439 expr.Parse (targets, ParseOptions.AllowItemsNoMetadataAndSplit);
440 return (string []) expr.ConvertTo (this, typeof (string []));
445 public string [] GetConditionedPropertyValues (string propertyName)
447 if (conditionedProperties.ContainsKey (propertyName))
448 return conditionedProperties [propertyName].ToArray ();
450 return new string [0];
453 public BuildItemGroup GetEvaluatedItemsByName (string itemName)
455 if (needToReevaluate) {
456 needToReevaluate = false;
460 if (evaluatedItemsByName.ContainsKey (itemName))
461 return evaluatedItemsByName [itemName];
463 return new BuildItemGroup (this);
466 public BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition (string itemName)
468 if (needToReevaluate) {
469 needToReevaluate = false;
473 if (evaluatedItemsByNameIgnoringCondition.ContainsKey (itemName))
474 return evaluatedItemsByNameIgnoringCondition [itemName];
476 return new BuildItemGroup (this);
479 public string GetEvaluatedProperty (string propertyName)
481 if (needToReevaluate) {
482 needToReevaluate = false;
486 if (propertyName == null)
487 throw new ArgumentNullException ("propertyName");
489 BuildProperty bp = evaluatedProperties [propertyName];
491 return bp == null ? null : (string) bp;
494 [MonoTODO ("We should remember that node and not use XPath to get it")]
495 public string GetProjectExtensions (string id)
497 if (id == null || id == String.Empty)
500 XmlNode node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
505 return node.InnerXml;
509 public void Load (string projectFileName)
511 Load (projectFileName, ProjectLoadSettings.None);
514 public void Load (string projectFileName, ProjectLoadSettings settings)
516 project_load_settings = settings;
517 if (String.IsNullOrEmpty (projectFileName))
518 throw new ArgumentNullException ("projectFileName");
520 if (!File.Exists (projectFileName))
521 throw new ArgumentException (String.Format ("Project file {0} not found", projectFileName),
524 this.fullFileName = Utilities.FromMSBuildPath (Path.GetFullPath (projectFileName));
525 PushThisFileProperty (fullFileName);
527 string filename = fullFileName;
528 if (String.Compare (Path.GetExtension (fullFileName), ".sln", true) == 0) {
529 Project tmp_project = ParentEngine.CreateNewProject ();
530 tmp_project.FullFileName = filename;
531 SolutionParser sln_parser = new SolutionParser ();
532 sln_parser.ParseSolution (fullFileName, tmp_project, delegate (int errorNumber, string message) {
533 LogWarning (filename, message);
535 filename = fullFileName + ".proj";
537 tmp_project.Save (filename);
538 ParentEngine.RemoveLoadedProject (tmp_project);
539 DoLoad (new StreamReader (filename));
541 if (Environment.GetEnvironmentVariable ("XBUILD_EMIT_SOLUTION") == null)
542 File.Delete (filename);
545 DoLoad (new StreamReader (filename));
549 [MonoTODO ("Not tested")]
550 public void Load (TextReader textReader)
552 Load (textReader, ProjectLoadSettings.None);
555 public void Load (TextReader textReader, ProjectLoadSettings projectLoadSettings)
557 project_load_settings = projectLoadSettings;
558 fullFileName = String.Empty;
562 public void LoadXml (string projectXml)
564 LoadXml (projectXml, ProjectLoadSettings.None);
567 public void LoadXml (string projectXml, ProjectLoadSettings projectLoadSettings)
569 project_load_settings = projectLoadSettings;
570 fullFileName = String.Empty;
571 DoLoad (new StringReader (projectXml));
572 MarkProjectAsDirty ();
576 public void MarkProjectAsDirty ()
579 timeOfLastDirty = DateTime.Now;
582 [MonoTODO ("Not tested")]
583 public void RemoveAllItemGroups ()
585 int length = ItemGroups.Count;
586 BuildItemGroup [] groups = new BuildItemGroup [length];
587 ItemGroups.CopyTo (groups, 0);
589 for (int i = 0; i < length; i++)
590 RemoveItemGroup (groups [i]);
592 MarkProjectAsDirty ();
596 [MonoTODO ("Not tested")]
597 public void RemoveAllPropertyGroups ()
599 int length = PropertyGroups.Count;
600 BuildPropertyGroup [] groups = new BuildPropertyGroup [length];
601 PropertyGroups.CopyTo (groups, 0);
603 for (int i = 0; i < length; i++)
604 RemovePropertyGroup (groups [i]);
606 MarkProjectAsDirty ();
611 public void RemoveItem (BuildItem itemToRemove)
613 if (itemToRemove == null)
614 throw new ArgumentNullException ("itemToRemove");
616 if (!itemToRemove.FromXml && !itemToRemove.HasParentItem)
617 throw new InvalidOperationException ("The object passed in is not part of the project.");
619 BuildItemGroup big = itemToRemove.ParentItemGroup;
621 if (big.Count == 1) {
622 // ParentItemGroup for items from xml and that have parent is the same
623 groupingCollection.Remove (big);
625 if (big.ParentProject != this)
626 throw new InvalidOperationException ("The object passed in is not part of the project.");
628 if (itemToRemove.FromXml)
629 big.RemoveItem (itemToRemove);
631 big.RemoveItem (itemToRemove.ParentItem);
634 MarkProjectAsDirty ();
638 [MonoTODO ("Not tested")]
639 public void RemoveItemGroup (BuildItemGroup itemGroupToRemove)
641 if (itemGroupToRemove == null)
642 throw new ArgumentNullException ("itemGroupToRemove");
644 groupingCollection.Remove (itemGroupToRemove);
645 MarkProjectAsDirty ();
649 // NOTE: does not modify imported projects
650 public void RemoveItemGroupsWithMatchingCondition (string matchingCondition)
652 throw new NotImplementedException ();
656 public void RemoveItemsByName (string itemName)
658 if (itemName == null)
659 throw new ArgumentNullException ("itemName");
661 throw new NotImplementedException ();
664 [MonoTODO ("Not tested")]
665 public void RemovePropertyGroup (BuildPropertyGroup propertyGroupToRemove)
667 if (propertyGroupToRemove == null)
668 throw new ArgumentNullException ("propertyGroupToRemove");
670 groupingCollection.Remove (propertyGroupToRemove);
671 MarkProjectAsDirty ();
675 // NOTE: does not modify imported projects
676 public void RemovePropertyGroupsWithMatchingCondition (string matchCondition)
678 throw new NotImplementedException ();
682 public void ResetBuildStatus ()
684 // hack to allow built targets to be removed
690 public void Save (string projectFileName)
692 Save (projectFileName, Encoding.Default);
696 [MonoTODO ("Ignores encoding")]
697 public void Save (string projectFileName, Encoding encoding)
699 xmlDocument.Save (projectFileName);
703 public void Save (TextWriter outTextWriter)
705 xmlDocument.Save (outTextWriter);
709 public void SetImportedProperty (string propertyName,
710 string propertyValue,
712 Project importProject)
714 SetImportedProperty (propertyName, propertyValue, condition, importProject,
715 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
718 public void SetImportedProperty (string propertyName,
719 string propertyValue,
721 Project importedProject,
722 PropertyPosition position)
724 SetImportedProperty (propertyName, propertyValue, condition, importedProject,
725 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
729 public void SetImportedProperty (string propertyName,
730 string propertyValue,
732 Project importedProject,
733 PropertyPosition position,
734 bool treatPropertyValueAsLiteral)
736 throw new NotImplementedException ();
739 public void SetProjectExtensions (string id, string xmlText)
742 throw new ArgumentNullException ("id");
744 throw new ArgumentNullException ("xmlText");
746 XmlNode projectExtensions, node;
748 projectExtensions = xmlDocument.SelectSingleNode ("/tns:Project/tns:ProjectExtensions", XmlNamespaceManager);
750 if (projectExtensions == null) {
751 projectExtensions = xmlDocument.CreateElement ("ProjectExtensions", XmlNamespace);
752 xmlDocument.DocumentElement.AppendChild (projectExtensions);
754 node = xmlDocument.CreateElement (id, XmlNamespace);
755 node.InnerXml = xmlText;
756 projectExtensions.AppendChild (node);
758 node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
761 node = xmlDocument.CreateElement (id, XmlNamespace);
762 projectExtensions.AppendChild (node);
765 node.InnerXml = xmlText;
769 MarkProjectAsDirty ();
772 public void SetProperty (string propertyName,
773 string propertyValue)
775 SetProperty (propertyName, propertyValue, "true",
776 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
779 public void SetProperty (string propertyName,
780 string propertyValue,
783 SetProperty (propertyName, propertyValue, condition,
784 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
787 public void SetProperty (string propertyName,
788 string propertyValue,
790 PropertyPosition position)
792 SetProperty (propertyName, propertyValue, condition,
793 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
797 public void SetProperty (string propertyName,
798 string propertyValue,
800 PropertyPosition position,
801 bool treatPropertyValueAsLiteral)
803 throw new NotImplementedException ();
806 internal void Unload ()
811 internal void CheckUnloaded ()
814 throw new InvalidOperationException ("This project object has been unloaded from the MSBuild engine and is no longer valid.");
817 internal void NeedToReevaluate ()
819 needToReevaluate = true;
822 // Does the actual loading.
823 void DoLoad (TextReader textReader)
826 ParentEngine.RemoveLoadedProject (this);
828 xmlDocument.Load (textReader);
830 if (xmlDocument.DocumentElement.Name == "VisualStudioProject")
831 throw new InvalidProjectFileException (String.Format (
832 "Project file '{0}' is a VS2003 project, which is not " +
833 "supported by xbuild. You need to convert it to msbuild " +
834 "format to build with xbuild.", fullFileName));
836 if (SchemaFile != null) {
837 xmlDocument.Schemas.Add (XmlSchema.Read (
838 new StreamReader (SchemaFile), ValidationCallBack));
839 xmlDocument.Validate (ValidationCallBack);
842 if (xmlDocument.DocumentElement.Name != "Project") {
843 throw new InvalidProjectFileException (String.Format (
844 "The element <{0}> is unrecognized, or not supported in this context.", xmlDocument.DocumentElement.Name));
847 if (xmlDocument.DocumentElement.GetAttribute ("xmlns") != ns) {
848 throw new InvalidProjectFileException (
849 @"The default XML namespace of the project must be the MSBuild XML namespace." +
850 " If the project is authored in the MSBuild 2003 format, please add " +
851 "xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" to the <Project> element. " +
852 "If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format. ");
855 ParentEngine.AddLoadedProject (this);
856 } catch (Exception e) {
857 throw new InvalidProjectFileException (String.Format ("{0}: {1}",
858 fullFileName, e.Message), e);
860 if (textReader != null)
872 groupingCollection = new GroupingCollection (this);
873 imports = new ImportCollection (groupingCollection);
874 usingTasks = new UsingTaskCollection (this);
875 itemGroups = new BuildItemGroupCollection (groupingCollection);
876 propertyGroups = new BuildPropertyGroupCollection (groupingCollection);
877 targets = new TargetCollection (this);
878 last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
880 string effective_tools_version = GetToolsVersionToUse (false);
881 taskDatabase = new TaskDatabase ();
882 taskDatabase.CopyTasks (ParentEngine.GetDefaultTasks (effective_tools_version));
884 initialTargets = new List<string> ();
885 defaultTargets = new string [0];
886 PrepareForEvaluate (effective_tools_version);
887 ProcessElements (xmlDocument.DocumentElement, null);
893 void ProcessProjectAttributes (XmlAttributeCollection attributes)
895 foreach (XmlAttribute attr in attributes) {
897 case "InitialTargets":
898 initialTargets.AddRange (attr.Value.Split (
899 new char [] {';', ' '},
900 StringSplitOptions.RemoveEmptyEntries));
902 case "DefaultTargets":
903 // first non-empty DefaultTargets found is used
904 if (defaultTargets == null || defaultTargets.Length == 0)
905 defaultTargets = attr.Value.Split (new char [] {';', ' '},
906 StringSplitOptions.RemoveEmptyEntries);
907 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets",
908 DefaultTargets, PropertyType.Reserved));
914 internal void ProcessElements (XmlElement rootElement, ImportedProject ip)
916 ProcessProjectAttributes (rootElement.Attributes);
917 foreach (XmlNode xn in rootElement.ChildNodes) {
918 if (xn is XmlElement) {
919 XmlElement xe = (XmlElement) xn;
921 case "ProjectExtensions":
922 AddProjectExtensions (xe);
933 AddUsingTask (xe, ip);
936 AddImport (xe, ip, true);
939 AddItemGroup (xe, ip);
941 case "PropertyGroup":
942 AddPropertyGroup (xe, ip);
948 throw new InvalidProjectFileException (String.Format ("Invalid element '{0}' in project file.", xe.Name));
954 void PrepareForEvaluate (string effective_tools_version)
956 evaluatedItems = new BuildItemGroup (null, this, null, true);
957 evaluatedItemsIgnoringCondition = new BuildItemGroup (null, this, null, true);
958 evaluatedItemsByName = new Dictionary <string, BuildItemGroup> (StringComparer.OrdinalIgnoreCase);
959 evaluatedItemsByNameIgnoringCondition = new Dictionary <string, BuildItemGroup> (StringComparer.OrdinalIgnoreCase);
960 if (building && current_settings == BuildSettings.None)
961 RemoveBuiltTargets ();
963 InitializeProperties (effective_tools_version);
968 groupingCollection.Evaluate ();
970 //FIXME: UsingTasks aren't really evaluated. (shouldn't use expressions or anything)
971 foreach (UsingTask usingTask in UsingTasks)
972 usingTask.Evaluate ();
975 // Removes entries of all earlier built targets for this project
976 void RemoveBuiltTargets ()
978 ParentEngine.ClearBuiltTargetsForProject (this);
981 void InitializeProperties (string effective_tools_version)
985 evaluatedProperties = new BuildPropertyGroup (null, null, null, true);
986 conditionedProperties = new Dictionary<string, List<string>> ();
988 foreach (BuildProperty gp in GlobalProperties) {
989 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
990 evaluatedProperties.AddProperty (bp);
993 foreach (BuildProperty gp in GlobalProperties)
994 ParentEngine.GlobalProperties.AddProperty (gp);
996 // add properties that we dont have from parent engine's
998 foreach (BuildProperty gp in ParentEngine.GlobalProperties) {
999 if (evaluatedProperties [gp.Name] == null) {
1000 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
1001 evaluatedProperties.AddProperty (bp);
1005 foreach (DictionaryEntry de in Environment.GetEnvironmentVariables ()) {
1006 bp = new BuildProperty ((string) de.Key, (string) de.Value, PropertyType.Environment);
1007 evaluatedProperties.AddProperty (bp);
1010 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFile", Path.GetFileName (fullFileName),
1011 PropertyType.Reserved));
1012 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFullPath", fullFileName, PropertyType.Reserved));
1013 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectName",
1014 Path.GetFileNameWithoutExtension (fullFileName),
1015 PropertyType.Reserved));
1016 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectExtension",
1017 Path.GetExtension (fullFileName),
1018 PropertyType.Reserved));
1020 string toolsPath = parentEngine.Toolsets [effective_tools_version].ToolsPath;
1021 if (toolsPath == null)
1022 throw new Exception (String.Format ("Invalid tools version '{0}', no tools path set for this.", effective_tools_version));
1023 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", toolsPath, PropertyType.Reserved));
1024 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", toolsPath, PropertyType.Reserved));
1025 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsRoot", Path.GetDirectoryName (toolsPath), PropertyType.Reserved));
1026 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsVersion", effective_tools_version, PropertyType.Reserved));
1027 SetExtensionsPathProperties (DefaultExtensionsPath);
1028 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets", DefaultTargets, PropertyType.Reserved));
1029 evaluatedProperties.AddProperty (new BuildProperty ("OS", OS, PropertyType.Environment));
1031 // FIXME: make some internal method that will work like GetDirectoryName but output String.Empty on null/String.Empty
1033 if (FullFileName == String.Empty)
1034 projectDir = Environment.CurrentDirectory;
1036 projectDir = Path.GetDirectoryName (FullFileName);
1038 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDirectory", projectDir, PropertyType.Reserved));
1040 if (this_file_property_stack.Count > 0)
1041 // Just re-inited the properties, but according to the stack,
1042 // we should have a MSBuild*This* property set
1043 SetMSBuildThisFileProperties (this_file_property_stack.Peek ());
1046 internal void SetExtensionsPathProperties (string extn_path)
1048 if (!String.IsNullOrEmpty (extn_path)) {
1049 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath", extn_path, PropertyType.Reserved));
1050 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath32", extn_path, PropertyType.Reserved));
1051 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath64", extn_path, PropertyType.Reserved));
1056 // ToolsVersion property
1057 // ToolsVersion attribute on the project
1058 // parentEngine's DefaultToolsVersion
1059 string GetToolsVersionToUse (bool emitWarning)
1061 if (!String.IsNullOrEmpty (ToolsVersion))
1062 return ToolsVersion;
1064 if (!HasToolsVersionAttribute)
1065 return parentEngine.DefaultToolsVersion;
1067 if (parentEngine.Toolsets [DefaultToolsVersion] == null) {
1069 LogWarning (FullFileName, "Project has unknown ToolsVersion '{0}'. Using the default tools version '{1}' instead.",
1070 DefaultToolsVersion, parentEngine.DefaultToolsVersion);
1071 return parentEngine.DefaultToolsVersion;
1074 return DefaultToolsVersion;
1077 void AddProjectExtensions (XmlElement xmlElement)
1081 void AddMessage (XmlElement xmlElement)
1085 void AddTarget (XmlElement xmlElement, ImportedProject importedProject)
1087 Target target = new Target (xmlElement, this, importedProject);
1088 targets.AddTarget (target);
1090 if (firstTargetName == null)
1091 firstTargetName = target.Name;
1094 void AddUsingTask (XmlElement xmlElement, ImportedProject importedProject)
1096 UsingTask usingTask;
1098 usingTask = new UsingTask (xmlElement, this, importedProject);
1099 UsingTasks.Add (usingTask);
1102 void AddImport (XmlElement xmlElement, ImportedProject importingProject, bool evaluate_properties)
1104 // eval all the properties etc till the import
1105 if (evaluate_properties)
1106 groupingCollection.Evaluate (EvaluationType.Property);
1109 PushThisFileProperty (importingProject != null ? importingProject.FullFileName : FullFileName);
1111 string project_attribute = xmlElement.GetAttribute ("Project");
1112 if (String.IsNullOrEmpty (project_attribute))
1113 throw new InvalidProjectFileException ("The required attribute \"Project\" is missing from element <Import>.");
1115 Import.ForEachExtensionPathTillFound (xmlElement, this, importingProject,
1116 (importPath, from_source_msg) => AddSingleImport (xmlElement, importPath, importingProject, from_source_msg));
1118 PopThisFileProperty ();
1122 bool AddSingleImport (XmlElement xmlElement, string projectPath, ImportedProject importingProject, string from_source_msg)
1124 Import import = new Import (xmlElement, projectPath, this, importingProject);
1125 if (!ConditionParser.ParseAndEvaluate (import.Condition, this)) {
1126 ParentEngine.LogMessage (MessageImportance.Low,
1127 "Not importing project '{0}' as the condition '{1}' is false",
1128 import.ProjectPath, import.Condition);
1132 Import existingImport;
1133 if (Imports.TryGetImport (import, out existingImport)) {
1134 if (importingProject == null)
1135 LogWarning (fullFileName,
1136 "Cannot import project '{0}' again. It was already imported by " +
1138 projectPath, existingImport.ContainedInProjectFileName);
1140 LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
1141 "A circular reference was found involving the import of '{0}'. " +
1142 "It was earlier imported by '{1}'. Only " +
1143 "the first import of this file will be used, ignoring others.",
1144 import.EvaluatedProjectPath, existingImport.ContainedInProjectFileName);
1149 if (String.Compare (fullFileName, import.EvaluatedProjectPath) == 0) {
1150 LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
1151 "The main project file was imported here, which creates a circular " +
1152 "reference. Ignoring this import.");
1157 if (project_load_settings != ProjectLoadSettings.IgnoreMissingImports &&
1158 !import.CheckEvaluatedProjectPathExists ())
1161 Imports.Add (import);
1162 string importingFile = importingProject != null ? importingProject.FullFileName : FullFileName;
1163 ParentEngine.LogMessage (MessageImportance.Low,
1164 "{0}: Importing project {1} {2}",
1165 importingFile, import.EvaluatedProjectPath, from_source_msg);
1167 import.Evaluate (project_load_settings == ProjectLoadSettings.IgnoreMissingImports);
1171 void AddItemGroup (XmlElement xmlElement, ImportedProject importedProject)
1173 BuildItemGroup big = new BuildItemGroup (xmlElement, this, importedProject, false);
1174 ItemGroups.Add (big);
1177 void AddPropertyGroup (XmlElement xmlElement, ImportedProject importedProject)
1179 BuildPropertyGroup bpg = new BuildPropertyGroup (xmlElement, this, importedProject, false);
1180 PropertyGroups.Add (bpg);
1183 void AddChoose (XmlElement xmlElement, ImportedProject importedProject)
1185 BuildChoose bc = new BuildChoose (xmlElement, this, importedProject);
1186 groupingCollection.Add (bc);
1189 static void ValidationCallBack (object sender, ValidationEventArgs e)
1191 Console.WriteLine ("Validation Error: {0}", e.Message);
1194 public bool BuildEnabled {
1196 return buildEnabled;
1199 buildEnabled = value;
1204 public Encoding Encoding {
1205 get { return encoding; }
1208 public string DefaultTargets {
1210 return String.Join ("; ", defaultTargets);
1213 xmlDocument.DocumentElement.SetAttribute ("DefaultTargets", value);
1215 defaultTargets = value.Split (new char [] {';', ' '},
1216 StringSplitOptions.RemoveEmptyEntries);
1220 public BuildItemGroup EvaluatedItems {
1222 if (needToReevaluate) {
1223 needToReevaluate = false;
1226 return evaluatedItems;
1230 public BuildItemGroup EvaluatedItemsIgnoringCondition {
1232 if (needToReevaluate) {
1233 needToReevaluate = false;
1236 return evaluatedItemsIgnoringCondition;
1240 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByName {
1242 // FIXME: do we need to do this here?
1243 if (needToReevaluate) {
1244 needToReevaluate = false;
1247 return evaluatedItemsByName;
1251 internal IEnumerable EvaluatedItemsByNameAsDictionaryEntries {
1253 if (EvaluatedItemsByName.Count == 0)
1256 foreach (KeyValuePair<string, BuildItemGroup> pair in EvaluatedItemsByName) {
1257 foreach (BuildItem bi in pair.Value)
1258 yield return new DictionaryEntry (pair.Key, bi.ConvertToITaskItem (null, ExpressionOptions.ExpandItemRefs));
1263 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByNameIgnoringCondition {
1265 // FIXME: do we need to do this here?
1266 if (needToReevaluate) {
1267 needToReevaluate = false;
1270 return evaluatedItemsByNameIgnoringCondition;
1274 // For batching implementation
1275 Dictionary<string, BuildItemGroup> perBatchItemsByName;
1276 Dictionary<string, BuildItemGroup> commonItemsByName;
1279 public Dictionary<string, BuildItemGroup> perBatchItemsByName;
1280 public Dictionary<string, BuildItemGroup> commonItemsByName;
1282 public Batch (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1284 this.perBatchItemsByName = perBatchItemsByName;
1285 this.commonItemsByName = commonItemsByName;
1289 Stack<Batch> Batches {
1290 get { return batches; }
1293 internal void PushBatch (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1295 batches.Push (new Batch (perBatchItemsByName, commonItemsByName));
1296 SetBatchedItems (perBatchItemsByName, commonItemsByName);
1299 internal void PopBatch ()
1302 if (batches.Count > 0) {
1303 Batch b = batches.Peek ();
1304 SetBatchedItems (b.perBatchItemsByName, b.commonItemsByName);
1306 SetBatchedItems (null, null);
1310 void SetBatchedItems (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1312 this.perBatchItemsByName = perBatchItemsByName;
1313 this.commonItemsByName = commonItemsByName;
1317 internal bool TryGetEvaluatedItemByNameBatched (string itemName, out BuildItemGroup group)
1319 if (perBatchItemsByName != null && perBatchItemsByName.TryGetValue (itemName, out group))
1322 if (commonItemsByName != null && commonItemsByName.TryGetValue (itemName, out group))
1326 return EvaluatedItemsByName.TryGetValue (itemName, out group);
1329 internal string GetMetadataBatched (string itemName, string metadataName)
1331 BuildItemGroup group = null;
1332 if (itemName == null) {
1333 //unqualified, all items in a batch(bucket) have the
1334 //same metadata values
1335 group = GetFirst<BuildItemGroup> (perBatchItemsByName.Values);
1337 group = GetFirst<BuildItemGroup> (commonItemsByName.Values);
1340 TryGetEvaluatedItemByNameBatched (itemName, out group);
1343 if (group != null) {
1344 foreach (BuildItem item in group) {
1345 if (item.HasMetadata (metadataName))
1346 return item.GetEvaluatedMetadata (metadataName);
1349 return String.Empty;
1352 internal IEnumerable<BuildItemGroup> GetAllItemGroups ()
1354 if (perBatchItemsByName == null && commonItemsByName == null)
1355 foreach (BuildItemGroup group in EvaluatedItemsByName.Values)
1358 if (perBatchItemsByName != null)
1359 foreach (BuildItemGroup group in perBatchItemsByName.Values)
1362 if (commonItemsByName != null)
1363 foreach (BuildItemGroup group in commonItemsByName.Values)
1367 T GetFirst<T> (ICollection<T> list)
1372 foreach (T t in list)
1378 // Used for MSBuild*This* set of properties
1379 internal void PushThisFileProperty (string full_filename)
1381 string last_file = this_file_property_stack.Count == 0 ? String.Empty : this_file_property_stack.Peek ();
1382 this_file_property_stack.Push (full_filename);
1383 if (last_file != full_filename)
1384 // first time, or different from previous one
1385 SetMSBuildThisFileProperties (full_filename);
1388 internal void PopThisFileProperty ()
1390 string last_file = this_file_property_stack.Pop ();
1391 if (this_file_property_stack.Count > 0 && last_file != this_file_property_stack.Peek ())
1392 SetMSBuildThisFileProperties (this_file_property_stack.Peek ());
1395 void SetMSBuildThisFileProperties (string full_filename)
1397 if (String.IsNullOrEmpty (full_filename))
1400 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFile", Path.GetFileName (full_filename), PropertyType.Reserved));
1401 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileFullPath", full_filename, PropertyType.Reserved));
1402 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileName", Path.GetFileNameWithoutExtension (full_filename), PropertyType.Reserved));
1403 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileExtension", Path.GetExtension (full_filename), PropertyType.Reserved));
1405 string project_dir = Path.GetDirectoryName (full_filename) + Path.DirectorySeparatorChar;
1406 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileDirectory", project_dir, PropertyType.Reserved));
1407 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileDirectoryNoRoot",
1408 project_dir.Substring (Path.GetPathRoot (project_dir).Length),
1409 PropertyType.Reserved));
1413 internal void LogWarning (string filename, string message, params object[] messageArgs)
1415 BuildWarningEventArgs bwea = new BuildWarningEventArgs (
1416 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1418 ParentEngine.EventSource.FireWarningRaised (this, bwea);
1421 internal void LogError (string filename, string message,
1422 params object[] messageArgs)
1424 BuildErrorEventArgs beea = new BuildErrorEventArgs (
1425 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1427 ParentEngine.EventSource.FireErrorRaised (this, beea);
1430 internal static string DefaultExtensionsPath {
1432 if (extensions_path == null) {
1433 // NOTE: code from mcs/tools/gacutil/driver.cs
1434 PropertyInfo gac = typeof (System.Environment).GetProperty (
1435 "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
1438 MethodInfo get_gac = gac.GetGetMethod (true);
1439 string gac_path = (string) get_gac.Invoke (null, null);
1440 extensions_path = Path.GetFullPath (Path.Combine (
1441 gac_path, Path.Combine ("..", "xbuild")));
1444 return extensions_path;
1448 public BuildPropertyGroup EvaluatedProperties {
1450 if (needToReevaluate) {
1451 needToReevaluate = false;
1454 return evaluatedProperties;
1458 internal IEnumerable EvaluatedPropertiesAsDictionaryEntries {
1460 foreach (BuildProperty bp in EvaluatedProperties)
1461 yield return new DictionaryEntry (bp.Name, bp.Value);
1465 public string FullFileName {
1466 get { return fullFileName; }
1467 set { fullFileName = value; }
1470 public BuildPropertyGroup GlobalProperties {
1471 get { return globalProperties; }
1474 throw new ArgumentNullException ("value");
1477 throw new InvalidOperationException ("GlobalProperties can not be set to persisted property group.");
1479 globalProperties = value;
1483 public bool IsDirty {
1484 get { return isDirty; }
1487 public bool IsValidated {
1488 get { return isValidated; }
1489 set { isValidated = value; }
1492 public BuildItemGroupCollection ItemGroups {
1493 get { return itemGroups; }
1496 public ImportCollection Imports {
1497 get { return imports; }
1500 public string InitialTargets {
1502 return String.Join ("; ", initialTargets.ToArray ());
1505 initialTargets.Clear ();
1506 xmlDocument.DocumentElement.SetAttribute ("InitialTargets", value);
1508 initialTargets.AddRange (value.Split (
1509 new char [] {';', ' '}, StringSplitOptions.RemoveEmptyEntries));
1513 public Engine ParentEngine {
1514 get { return parentEngine; }
1517 public BuildPropertyGroupCollection PropertyGroups {
1518 get { return propertyGroups; }
1521 public string SchemaFile {
1522 get { return schemaFile; }
1523 set { schemaFile = value; }
1526 public TargetCollection Targets {
1527 get { return targets; }
1530 public DateTime TimeOfLastDirty {
1531 get { return timeOfLastDirty; }
1534 public UsingTaskCollection UsingTasks {
1535 get { return usingTasks; }
1540 get { return xmlDocument.InnerXml; }
1543 // corresponds to the xml attribute
1544 public string DefaultToolsVersion {
1546 if (xmlDocument != null)
1547 return xmlDocument.DocumentElement.GetAttribute ("ToolsVersion");
1551 if (xmlDocument != null)
1552 xmlDocument.DocumentElement.SetAttribute ("ToolsVersion", value);
1556 public bool HasToolsVersionAttribute {
1558 return xmlDocument != null && xmlDocument.DocumentElement.HasAttribute ("ToolsVersion");
1562 public string ToolsVersion {
1566 internal Dictionary <string, BuildItemGroup> LastItemGroupContaining {
1567 get { return last_item_group_containing; }
1570 internal static XmlNamespaceManager XmlNamespaceManager {
1572 if (manager == null) {
1573 manager = new XmlNamespaceManager (new NameTable ());
1574 manager.AddNamespace ("tns", ns);
1581 internal TaskDatabase TaskDatabase {
1582 get { return taskDatabase; }
1585 internal XmlDocument XmlDocument {
1586 get { return xmlDocument; }
1589 internal static string XmlNamespace {
1595 PlatformID pid = Environment.OSVersion.Platform;
1603 return "Windows_NT";