2 // Project.cs: Project class
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.
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.Specialized;
35 using System.Reflection;
38 using System.Xml.Schema;
39 using Microsoft.Build.Framework;
40 using Mono.XBuild.Framework;
41 using Mono.XBuild.CommandLine;
43 namespace Microsoft.Build.BuildEngine {
44 public class Project {
47 Dictionary <string, List <string>> conditionedProperties;
48 string[] defaultTargets;
50 BuildItemGroup evaluatedItems;
51 BuildItemGroup evaluatedItemsIgnoringCondition;
52 Dictionary <string, BuildItemGroup> evaluatedItemsByName;
53 Dictionary <string, BuildItemGroup> evaluatedItemsByNameIgnoringCondition;
54 BuildPropertyGroup evaluatedProperties;
55 string firstTargetName;
57 BuildPropertyGroup globalProperties;
58 GroupingCollection groupingCollection;
61 BuildItemGroupCollection itemGroups;
62 ImportCollection imports;
63 List<string> initialTargets;
64 Dictionary <string, BuildItemGroup> last_item_group_containing;
65 bool needToReevaluate;
67 BuildPropertyGroupCollection propertyGroups;
69 TaskDatabase taskDatabase;
70 TargetCollection targets;
71 DateTime timeOfLastDirty;
72 UsingTaskCollection usingTasks;
73 XmlDocument xmlDocument;
75 bool initialTargetsBuilt;
77 BuildSettings current_settings;
79 ProjectLoadSettings project_load_settings;
82 static string extensions_path;
83 static XmlNamespaceManager manager;
84 static string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
87 : this (Engine.GlobalEngine)
91 public Project (Engine engine) : this (engine, null)
95 public Project (Engine engine, string toolsVersion)
97 parentEngine = engine;
98 ToolsVersion = toolsVersion;
100 buildEnabled = ParentEngine.BuildEnabled;
101 xmlDocument = new XmlDocument ();
102 xmlDocument.PreserveWhitespace = false;
103 xmlDocument.AppendChild (xmlDocument.CreateElement ("Project", XmlNamespace));
104 xmlDocument.DocumentElement.SetAttribute ("xmlns", ns);
106 fullFileName = String.Empty;
107 timeOfLastDirty = DateTime.Now;
108 current_settings = BuildSettings.None;
109 project_load_settings = ProjectLoadSettings.None;
113 initialTargets = new List<string> ();
114 defaultTargets = new string [0];
115 batches = new Stack<Batch> ();
117 globalProperties = new BuildPropertyGroup (null, this, null, false);
118 foreach (BuildProperty bp in parentEngine.GlobalProperties)
119 GlobalProperties.AddProperty (bp.Clone (true));
125 [MonoTODO ("Not tested")]
126 public void AddNewImport (string importLocation,
127 string importCondition)
129 if (importLocation == null)
130 throw new ArgumentNullException ("importLocation");
132 XmlElement importElement = xmlDocument.CreateElement ("Import", XmlNamespace);
133 xmlDocument.DocumentElement.AppendChild (importElement);
134 importElement.SetAttribute ("Project", importLocation);
135 if (!String.IsNullOrEmpty (importCondition))
136 importElement.SetAttribute ("Condition", importCondition);
138 Import import = new Import (importElement, this, null);
139 imports.Add (import);
140 MarkProjectAsDirty ();
144 public BuildItem AddNewItem (string itemName,
147 return AddNewItem (itemName, itemInclude, false);
150 [MonoTODO ("Adds item not in the same place as MS")]
151 public BuildItem AddNewItem (string itemName,
153 bool treatItemIncludeAsLiteral)
157 if (itemGroups.Count == 0)
158 big = AddNewItemGroup ();
160 if (last_item_group_containing.ContainsKey (itemName)) {
161 big = last_item_group_containing [itemName];
164 BuildItemGroup [] groups = new BuildItemGroup [itemGroups.Count];
165 itemGroups.CopyTo (groups, 0);
170 BuildItem item = big.AddNewItem (itemName, itemInclude, treatItemIncludeAsLiteral);
172 MarkProjectAsDirty ();
178 [MonoTODO ("Not tested")]
179 public BuildItemGroup AddNewItemGroup ()
181 XmlElement element = xmlDocument.CreateElement ("ItemGroup", XmlNamespace);
182 xmlDocument.DocumentElement.AppendChild (element);
184 BuildItemGroup big = new BuildItemGroup (element, this, null, false);
185 itemGroups.Add (big);
186 MarkProjectAsDirty ();
192 [MonoTODO ("Ignores insertAtEndOfProject")]
193 public BuildPropertyGroup AddNewPropertyGroup (bool insertAtEndOfProject)
195 XmlElement element = xmlDocument.CreateElement ("PropertyGroup", XmlNamespace);
196 xmlDocument.DocumentElement.AppendChild (element);
198 BuildPropertyGroup bpg = new BuildPropertyGroup (element, this, null, false);
199 propertyGroups.Add (bpg);
200 MarkProjectAsDirty ();
206 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
207 public void AddNewUsingTaskFromAssemblyFile (string taskName,
210 if (taskName == null)
211 throw new ArgumentNullException ("taskName");
212 if (assemblyFile == null)
213 throw new ArgumentNullException ("assemblyFile");
215 XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
216 xmlDocument.DocumentElement.AppendChild (element);
217 element.SetAttribute ("TaskName", taskName);
218 element.SetAttribute ("AssemblyFile", assemblyFile);
220 UsingTask ut = new UsingTask (element, this, null);
222 MarkProjectAsDirty ();
225 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
226 public void AddNewUsingTaskFromAssemblyName (string taskName,
229 if (taskName == null)
230 throw new ArgumentNullException ("taskName");
231 if (assemblyName == null)
232 throw new ArgumentNullException ("assemblyName");
234 XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
235 xmlDocument.DocumentElement.AppendChild (element);
236 element.SetAttribute ("TaskName", taskName);
237 element.SetAttribute ("AssemblyName", assemblyName);
239 UsingTask ut = new UsingTask (element, this, null);
241 MarkProjectAsDirty ();
244 [MonoTODO ("Not tested")]
247 return Build (new string [0]);
250 [MonoTODO ("Not tested")]
251 public bool Build (string targetName)
253 if (targetName == null)
254 return Build ((string[]) null);
256 return Build (new string [1] { targetName });
259 [MonoTODO ("Not tested")]
260 public bool Build (string [] targetNames)
262 return Build (targetNames, null);
265 [MonoTODO ("Not tested")]
266 public bool Build (string [] targetNames,
267 IDictionary targetOutputs)
269 return Build (targetNames, targetOutputs, BuildSettings.None);
272 [MonoTODO ("Not tested")]
273 public bool Build (string [] targetNames,
274 IDictionary targetOutputs,
275 BuildSettings buildFlags)
279 ParentEngine.StartProjectBuild (this, targetNames);
280 string current_directory = Environment.CurrentDirectory;
282 current_settings = buildFlags;
283 if (!String.IsNullOrEmpty (fullFileName))
284 Directory.SetCurrentDirectory (Path.GetDirectoryName (fullFileName));
286 result = BuildInternal (targetNames, targetOutputs, buildFlags);
288 ParentEngine.EndProjectBuild (this, result);
289 current_settings = BuildSettings.None;
290 Directory.SetCurrentDirectory (current_directory);
297 bool BuildInternal (string [] targetNames,
298 IDictionary targetOutputs,
299 BuildSettings buildFlags)
302 if (buildFlags == BuildSettings.None) {
303 needToReevaluate = false;
307 if (targetNames == null || targetNames.Length == 0) {
308 if (defaultTargets != null && defaultTargets.Length != 0)
309 targetNames = defaultTargets;
310 else if (firstTargetName != null)
311 targetNames = new string [1] { firstTargetName};
316 if (!initialTargetsBuilt) {
317 foreach (string target in initialTargets) {
318 if (!BuildTarget (target.Trim (), targetOutputs))
321 initialTargetsBuilt = true;
324 foreach (string target in targetNames)
325 if (!BuildTarget (target.Trim (), targetOutputs))
331 bool BuildTarget (string target_name, IDictionary targetOutputs)
333 if (target_name == null)
334 throw new ArgumentException ("targetNames cannot contain null strings");
336 if (!targets.Exists (target_name)) {
337 LogError (fullFileName, "Target named '{0}' not found in the project.", target_name);
341 string key = GetKeyForTarget (target_name);
342 if (!targets [target_name].Build (key))
346 if (ParentEngine.BuiltTargetsOutputByName.TryGetValue (key, out outputs)) {
347 if (targetOutputs != null)
348 targetOutputs.Add (target_name, outputs);
353 internal string GetKeyForTarget (string target_name)
355 return GetKeyForTarget (target_name, true);
358 internal string GetKeyForTarget (string target_name, bool include_global_properties)
360 // target name is case insensitive
361 return fullFileName + ":" + target_name.ToLower () +
362 (include_global_properties ? (":" + GlobalPropertiesToString (GlobalProperties))
366 string GlobalPropertiesToString (BuildPropertyGroup bgp)
368 StringBuilder sb = new StringBuilder ();
369 foreach (BuildProperty bp in bgp)
370 sb.AppendFormat (" {0}:{1}", bp.Name, bp.FinalValue);
371 return sb.ToString ();
375 public string [] GetConditionedPropertyValues (string propertyName)
377 if (conditionedProperties.ContainsKey (propertyName))
378 return conditionedProperties [propertyName].ToArray ();
380 return new string [0];
383 public BuildItemGroup GetEvaluatedItemsByName (string itemName)
385 if (needToReevaluate) {
386 needToReevaluate = false;
390 if (evaluatedItemsByName.ContainsKey (itemName))
391 return evaluatedItemsByName [itemName];
393 return new BuildItemGroup (this);
396 public BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition (string itemName)
398 if (needToReevaluate) {
399 needToReevaluate = false;
403 if (evaluatedItemsByNameIgnoringCondition.ContainsKey (itemName))
404 return evaluatedItemsByNameIgnoringCondition [itemName];
406 return new BuildItemGroup (this);
409 public string GetEvaluatedProperty (string propertyName)
411 if (needToReevaluate) {
412 needToReevaluate = false;
416 if (propertyName == null)
417 throw new ArgumentNullException ("propertyName");
419 BuildProperty bp = evaluatedProperties [propertyName];
421 return bp == null ? null : (string) bp;
424 [MonoTODO ("We should remember that node and not use XPath to get it")]
425 public string GetProjectExtensions (string id)
427 if (id == null || id == String.Empty)
430 XmlNode node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
435 return node.InnerXml;
439 public void Load (string projectFileName)
441 Load (projectFileName, ProjectLoadSettings.None);
444 public void Load (string projectFileName, ProjectLoadSettings settings)
446 project_load_settings = settings;
447 if (String.IsNullOrEmpty (projectFileName))
448 throw new ArgumentNullException ("projectFileName");
450 if (!File.Exists (projectFileName))
451 throw new ArgumentException (String.Format ("Project file {0} not found", projectFileName),
454 this.fullFileName = Utilities.FromMSBuildPath (Path.GetFullPath (projectFileName));
456 string filename = fullFileName;
457 if (String.Compare (Path.GetExtension (fullFileName), ".sln", true) == 0) {
458 Project tmp_project = ParentEngine.CreateNewProject ();
459 SolutionParser sln_parser = new SolutionParser ();
460 sln_parser.ParseSolution (fullFileName, tmp_project, delegate (int errorNumber, string message) {
461 LogWarning (filename, message);
463 filename = fullFileName + ".proj";
465 tmp_project.Save (filename);
466 ParentEngine.RemoveLoadedProject (tmp_project);
467 DoLoad (new StreamReader (filename));
469 if (Environment.GetEnvironmentVariable ("XBUILD_EMIT_SOLUTION") == null)
470 File.Delete (filename);
473 DoLoad (new StreamReader (filename));
477 [MonoTODO ("Not tested")]
478 public void Load (TextReader textReader)
480 Load (textReader, ProjectLoadSettings.None);
483 public void Load (TextReader textReader, ProjectLoadSettings projectLoadSettings)
485 project_load_settings = projectLoadSettings;
486 fullFileName = String.Empty;
490 public void LoadXml (string projectXml)
492 LoadXml (projectXml, ProjectLoadSettings.None);
495 public void LoadXml (string projectXml, ProjectLoadSettings projectLoadSettings)
497 project_load_settings = projectLoadSettings;
498 fullFileName = String.Empty;
499 DoLoad (new StringReader (projectXml));
500 MarkProjectAsDirty ();
504 public void MarkProjectAsDirty ()
507 timeOfLastDirty = DateTime.Now;
510 [MonoTODO ("Not tested")]
511 public void RemoveAllItemGroups ()
513 int length = ItemGroups.Count;
514 BuildItemGroup [] groups = new BuildItemGroup [length];
515 ItemGroups.CopyTo (groups, 0);
517 for (int i = 0; i < length; i++)
518 RemoveItemGroup (groups [i]);
520 MarkProjectAsDirty ();
524 [MonoTODO ("Not tested")]
525 public void RemoveAllPropertyGroups ()
527 int length = PropertyGroups.Count;
528 BuildPropertyGroup [] groups = new BuildPropertyGroup [length];
529 PropertyGroups.CopyTo (groups, 0);
531 for (int i = 0; i < length; i++)
532 RemovePropertyGroup (groups [i]);
534 MarkProjectAsDirty ();
539 public void RemoveItem (BuildItem itemToRemove)
541 if (itemToRemove == null)
542 throw new ArgumentNullException ("itemToRemove");
544 if (!itemToRemove.FromXml && !itemToRemove.HasParentItem)
545 throw new InvalidOperationException ("The object passed in is not part of the project.");
547 BuildItemGroup big = itemToRemove.ParentItemGroup;
549 if (big.Count == 1) {
550 // ParentItemGroup for items from xml and that have parent is the same
551 groupingCollection.Remove (big);
553 if (big.ParentProject != this)
554 throw new InvalidOperationException ("The object passed in is not part of the project.");
556 if (itemToRemove.FromXml)
557 big.RemoveItem (itemToRemove);
559 big.RemoveItem (itemToRemove.ParentItem);
562 MarkProjectAsDirty ();
566 [MonoTODO ("Not tested")]
567 public void RemoveItemGroup (BuildItemGroup itemGroupToRemove)
569 if (itemGroupToRemove == null)
570 throw new ArgumentNullException ("itemGroupToRemove");
572 groupingCollection.Remove (itemGroupToRemove);
573 MarkProjectAsDirty ();
577 // NOTE: does not modify imported projects
578 public void RemoveItemGroupsWithMatchingCondition (string matchingCondition)
580 throw new NotImplementedException ();
584 public void RemoveItemsByName (string itemName)
586 if (itemName == null)
587 throw new ArgumentNullException ("itemName");
589 throw new NotImplementedException ();
592 [MonoTODO ("Not tested")]
593 public void RemovePropertyGroup (BuildPropertyGroup propertyGroupToRemove)
595 if (propertyGroupToRemove == null)
596 throw new ArgumentNullException ("propertyGroupToRemove");
598 groupingCollection.Remove (propertyGroupToRemove);
599 MarkProjectAsDirty ();
603 // NOTE: does not modify imported projects
604 public void RemovePropertyGroupsWithMatchingCondition (string matchCondition)
606 throw new NotImplementedException ();
610 public void ResetBuildStatus ()
612 // hack to allow built targets to be removed
618 public void Save (string projectFileName)
620 Save (projectFileName, Encoding.Default);
624 [MonoTODO ("Ignores encoding")]
625 public void Save (string projectFileName, Encoding encoding)
627 xmlDocument.Save (projectFileName);
631 public void Save (TextWriter outTextWriter)
633 xmlDocument.Save (outTextWriter);
637 public void SetImportedProperty (string propertyName,
638 string propertyValue,
640 Project importProject)
642 SetImportedProperty (propertyName, propertyValue, condition, importProject,
643 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
646 public void SetImportedProperty (string propertyName,
647 string propertyValue,
649 Project importedProject,
650 PropertyPosition position)
652 SetImportedProperty (propertyName, propertyValue, condition, importedProject,
653 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
657 public void SetImportedProperty (string propertyName,
658 string propertyValue,
660 Project importedProject,
661 PropertyPosition position,
662 bool treatPropertyValueAsLiteral)
664 throw new NotImplementedException ();
667 public void SetProjectExtensions (string id, string xmlText)
670 throw new ArgumentNullException ("id");
672 throw new ArgumentNullException ("xmlText");
674 XmlNode projectExtensions, node;
676 projectExtensions = xmlDocument.SelectSingleNode ("/tns:Project/tns:ProjectExtensions", XmlNamespaceManager);
678 if (projectExtensions == null) {
679 projectExtensions = xmlDocument.CreateElement ("ProjectExtensions", XmlNamespace);
680 xmlDocument.DocumentElement.AppendChild (projectExtensions);
682 node = xmlDocument.CreateElement (id, XmlNamespace);
683 node.InnerXml = xmlText;
684 projectExtensions.AppendChild (node);
686 node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
689 node = xmlDocument.CreateElement (id, XmlNamespace);
690 projectExtensions.AppendChild (node);
693 node.InnerXml = xmlText;
697 MarkProjectAsDirty ();
700 public void SetProperty (string propertyName,
701 string propertyValue)
703 SetProperty (propertyName, propertyValue, "true",
704 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
707 public void SetProperty (string propertyName,
708 string propertyValue,
711 SetProperty (propertyName, propertyValue, condition,
712 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
715 public void SetProperty (string propertyName,
716 string propertyValue,
718 PropertyPosition position)
720 SetProperty (propertyName, propertyValue, condition,
721 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
725 public void SetProperty (string propertyName,
726 string propertyValue,
728 PropertyPosition position,
729 bool treatPropertyValueAsLiteral)
731 throw new NotImplementedException ();
734 internal void Unload ()
739 internal void CheckUnloaded ()
742 throw new InvalidOperationException ("This project object has been unloaded from the MSBuild engine and is no longer valid.");
745 internal void NeedToReevaluate ()
747 needToReevaluate = true;
750 // Does the actual loading.
751 void DoLoad (TextReader textReader)
754 ParentEngine.RemoveLoadedProject (this);
756 xmlDocument.Load (textReader);
758 if (xmlDocument.DocumentElement.Name == "VisualStudioProject")
759 throw new InvalidProjectFileException (String.Format (
760 "Project file '{0}' is a VS2003 project, which is not " +
761 "supported by xbuild. You need to convert it to msbuild " +
762 "format to build with xbuild.", fullFileName));
764 if (SchemaFile != null) {
765 xmlDocument.Schemas.Add (XmlSchema.Read (
766 new StreamReader (SchemaFile), ValidationCallBack));
767 xmlDocument.Validate (ValidationCallBack);
770 if (xmlDocument.DocumentElement.Name != "Project") {
771 throw new InvalidProjectFileException (String.Format (
772 "The element <{0}> is unrecognized, or not supported in this context.", xmlDocument.DocumentElement.Name));
775 if (xmlDocument.DocumentElement.GetAttribute ("xmlns") != ns) {
776 throw new InvalidProjectFileException (
777 @"The default XML namespace of the project must be the MSBuild XML namespace." +
778 " If the project is authored in the MSBuild 2003 format, please add " +
779 "xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" to the <Project> element. " +
780 "If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format. ");
783 ParentEngine.AddLoadedProject (this);
784 } catch (Exception e) {
785 throw new InvalidProjectFileException (String.Format ("{0}: {1}",
786 fullFileName, e.Message), e);
788 if (textReader != null)
800 groupingCollection = new GroupingCollection (this);
801 imports = new ImportCollection (groupingCollection);
802 usingTasks = new UsingTaskCollection (this);
803 itemGroups = new BuildItemGroupCollection (groupingCollection);
804 propertyGroups = new BuildPropertyGroupCollection (groupingCollection);
805 targets = new TargetCollection (this);
806 last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
808 string effective_tools_version = GetToolsVersionToUse ();
809 taskDatabase = new TaskDatabase ();
810 taskDatabase.CopyTasks (ParentEngine.GetDefaultTasks (effective_tools_version));
812 initialTargets = new List<string> ();
813 defaultTargets = new string [0];
814 PrepareForEvaluate (effective_tools_version);
815 ProcessElements (xmlDocument.DocumentElement, null);
821 void ProcessProjectAttributes (XmlAttributeCollection attributes)
823 foreach (XmlAttribute attr in attributes) {
825 case "InitialTargets":
826 initialTargets.AddRange (attr.Value.Split (
827 new char [] {';', ' '},
828 StringSplitOptions.RemoveEmptyEntries));
830 case "DefaultTargets":
831 // first non-empty DefaultTargets found is used
832 if (defaultTargets == null || defaultTargets.Length == 0)
833 defaultTargets = attr.Value.Split (new char [] {';', ' '},
834 StringSplitOptions.RemoveEmptyEntries);
835 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets",
836 DefaultTargets, PropertyType.Reserved));
842 internal void ProcessElements (XmlElement rootElement, ImportedProject ip)
844 ProcessProjectAttributes (rootElement.Attributes);
845 foreach (XmlNode xn in rootElement.ChildNodes) {
846 if (xn is XmlElement) {
847 XmlElement xe = (XmlElement) xn;
849 case "ProjectExtensions":
850 AddProjectExtensions (xe);
861 AddUsingTask (xe, ip);
867 AddItemGroup (xe, ip);
869 case "PropertyGroup":
870 AddPropertyGroup (xe, ip);
876 throw new InvalidProjectFileException (String.Format ("Invalid element '{0}' in project file.", xe.Name));
882 void PrepareForEvaluate (string effective_tools_version)
884 evaluatedItems = new BuildItemGroup (null, this, null, true);
885 evaluatedItemsIgnoringCondition = new BuildItemGroup (null, this, null, true);
886 evaluatedItemsByName = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
887 evaluatedItemsByNameIgnoringCondition = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
888 if (building && current_settings == BuildSettings.None)
889 RemoveBuiltTargets ();
891 InitializeProperties (effective_tools_version);
896 groupingCollection.Evaluate ();
898 //FIXME: UsingTasks aren't really evaluated. (shouldn't use expressions or anything)
899 foreach (UsingTask usingTask in UsingTasks)
900 usingTask.Evaluate ();
903 // Removes entries of all earlier built targets for this project
904 void RemoveBuiltTargets ()
906 ParentEngine.ClearBuiltTargetsForProject (this);
909 void InitializeProperties (string effective_tools_version)
913 evaluatedProperties = new BuildPropertyGroup (null, null, null, true);
915 foreach (BuildProperty gp in GlobalProperties) {
916 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
917 EvaluatedProperties.AddProperty (bp);
920 foreach (BuildProperty gp in GlobalProperties)
921 ParentEngine.GlobalProperties.AddProperty (gp);
923 // add properties that we dont have from parent engine's
925 foreach (BuildProperty gp in ParentEngine.GlobalProperties) {
926 if (EvaluatedProperties [gp.Name] == null) {
927 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
928 EvaluatedProperties.AddProperty (bp);
932 foreach (DictionaryEntry de in Environment.GetEnvironmentVariables ()) {
933 bp = new BuildProperty ((string) de.Key, (string) de.Value, PropertyType.Environment);
934 EvaluatedProperties.AddProperty (bp);
937 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFile", Path.GetFileName (fullFileName),
938 PropertyType.Reserved));
939 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFullPath", fullFileName, PropertyType.Reserved));
940 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectName",
941 Path.GetFileNameWithoutExtension (fullFileName),
942 PropertyType.Reserved));
943 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectExtension",
944 Path.GetExtension (fullFileName),
945 PropertyType.Reserved));
947 string toolsPath = parentEngine.Toolsets [effective_tools_version].ToolsPath;
948 if (toolsPath == null)
949 throw new Exception (String.Format ("Invalid tools version '{0}', no tools path set for this.", effective_tools_version));
950 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", toolsPath, PropertyType.Reserved));
951 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", toolsPath, PropertyType.Reserved));
952 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsVersion", effective_tools_version, PropertyType.Reserved));
953 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath", ExtensionsPath, PropertyType.Reserved));
954 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath32", ExtensionsPath, PropertyType.Reserved));
955 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath64", ExtensionsPath, PropertyType.Reserved));
956 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets", DefaultTargets, PropertyType.Reserved));
957 EvaluatedProperties.AddProperty (new BuildProperty ("OS", OS, PropertyType.Environment));
959 // FIXME: make some internal method that will work like GetDirectoryName but output String.Empty on null/String.Empty
961 if (FullFileName == String.Empty)
962 projectDir = Environment.CurrentDirectory;
964 projectDir = Path.GetDirectoryName (FullFileName);
966 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDirectory", projectDir, PropertyType.Reserved));
970 // ToolsVersion property
971 // ToolsVersion attribute on the project
972 // parentEngine's DefaultToolsVersion
973 string GetToolsVersionToUse ()
975 if (!String.IsNullOrEmpty (ToolsVersion))
978 if (!HasToolsVersionAttribute)
979 return parentEngine.DefaultToolsVersion;
981 if (parentEngine.Toolsets [DefaultToolsVersion] == null) {
982 LogWarning (FullFileName, "Project has unknown ToolsVersion '{0}'. Using the default tools version '{1}' instead.",
983 DefaultToolsVersion, parentEngine.DefaultToolsVersion);
984 return parentEngine.DefaultToolsVersion;
987 return DefaultToolsVersion;
990 void AddProjectExtensions (XmlElement xmlElement)
994 void AddMessage (XmlElement xmlElement)
998 void AddTarget (XmlElement xmlElement, ImportedProject importedProject)
1000 Target target = new Target (xmlElement, this, importedProject);
1001 targets.AddTarget (target);
1003 if (firstTargetName == null)
1004 firstTargetName = target.Name;
1007 void AddUsingTask (XmlElement xmlElement, ImportedProject importedProject)
1009 UsingTask usingTask;
1011 usingTask = new UsingTask (xmlElement, this, importedProject);
1012 UsingTasks.Add (usingTask);
1015 void AddImport (XmlElement xmlElement, ImportedProject importingProject)
1017 // eval all the properties etc till the import
1018 groupingCollection.Evaluate (EvaluationType.Property);
1020 Import import = new Import (xmlElement, this, importingProject);
1021 if (!ConditionParser.ParseAndEvaluate (import.Condition, this))
1024 if (Imports.Contains (import)) {
1025 LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
1026 "A circular reference was found involving the import of {0}. Only" +
1027 " the first import of this file will be used, ignoring others.",
1028 import.ProjectPath);
1033 if (String.Compare (fullFileName, import.EvaluatedProjectPath) == 0) {
1034 LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
1035 "The main project file was imported here, which creates a circular " +
1036 "reference. Ignoring this import.");
1041 Imports.Add (import);
1042 import.Evaluate (project_load_settings == ProjectLoadSettings.IgnoreMissingImports);
1045 void AddItemGroup (XmlElement xmlElement, ImportedProject importedProject)
1047 BuildItemGroup big = new BuildItemGroup (xmlElement, this, importedProject, false);
1048 ItemGroups.Add (big);
1051 void AddPropertyGroup (XmlElement xmlElement, ImportedProject importedProject)
1053 BuildPropertyGroup bpg = new BuildPropertyGroup (xmlElement, this, importedProject, false);
1054 PropertyGroups.Add (bpg);
1057 void AddChoose (XmlElement xmlElement)
1059 BuildChoose bc = new BuildChoose (xmlElement, this);
1060 groupingCollection.Add (bc);
1063 static void ValidationCallBack (object sender, ValidationEventArgs e)
1065 Console.WriteLine ("Validation Error: {0}", e.Message);
1068 public bool BuildEnabled {
1070 return buildEnabled;
1073 buildEnabled = value;
1078 public Encoding Encoding {
1079 get { return encoding; }
1082 public string DefaultTargets {
1084 return String.Join ("; ", defaultTargets);
1087 xmlDocument.DocumentElement.SetAttribute ("DefaultTargets", value);
1089 defaultTargets = value.Split (new char [] {';', ' '},
1090 StringSplitOptions.RemoveEmptyEntries);
1094 public BuildItemGroup EvaluatedItems {
1096 if (needToReevaluate) {
1097 needToReevaluate = false;
1100 return evaluatedItems;
1104 public BuildItemGroup EvaluatedItemsIgnoringCondition {
1106 if (needToReevaluate) {
1107 needToReevaluate = false;
1110 return evaluatedItemsIgnoringCondition;
1114 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByName {
1116 // FIXME: do we need to do this here?
1117 if (needToReevaluate) {
1118 needToReevaluate = false;
1121 return evaluatedItemsByName;
1125 internal IEnumerable EvaluatedItemsByNameAsDictionaryEntries {
1127 if (EvaluatedItemsByName.Count == 0)
1130 foreach (KeyValuePair<string, BuildItemGroup> pair in EvaluatedItemsByName) {
1131 foreach (BuildItem bi in pair.Value)
1132 yield return new DictionaryEntry (pair.Key, bi.ConvertToITaskItem (null, ExpressionOptions.ExpandItemRefs));
1137 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByNameIgnoringCondition {
1139 // FIXME: do we need to do this here?
1140 if (needToReevaluate) {
1141 needToReevaluate = false;
1144 return evaluatedItemsByNameIgnoringCondition;
1148 // For batching implementation
1149 Dictionary<string, BuildItemGroup> perBatchItemsByName;
1150 Dictionary<string, BuildItemGroup> commonItemsByName;
1153 public Dictionary<string, BuildItemGroup> perBatchItemsByName;
1154 public Dictionary<string, BuildItemGroup> commonItemsByName;
1156 public Batch (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1158 this.perBatchItemsByName = perBatchItemsByName;
1159 this.commonItemsByName = commonItemsByName;
1163 Stack<Batch> Batches {
1164 get { return batches; }
1167 internal void PushBatch (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1169 batches.Push (new Batch (perBatchItemsByName, commonItemsByName));
1170 SetBatchedItems (perBatchItemsByName, commonItemsByName);
1173 internal void PopBatch ()
1176 if (batches.Count > 0) {
1177 Batch b = batches.Peek ();
1178 SetBatchedItems (b.perBatchItemsByName, b.commonItemsByName);
1180 SetBatchedItems (null, null);
1184 void SetBatchedItems (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1186 this.perBatchItemsByName = perBatchItemsByName;
1187 this.commonItemsByName = commonItemsByName;
1191 internal bool TryGetEvaluatedItemByNameBatched (string itemName, out BuildItemGroup group)
1193 if (perBatchItemsByName != null && perBatchItemsByName.TryGetValue (itemName, out group))
1196 if (commonItemsByName != null && commonItemsByName.TryGetValue (itemName, out group))
1200 return EvaluatedItemsByName.TryGetValue (itemName, out group);
1203 internal string GetMetadataBatched (string itemName, string metadataName)
1205 BuildItemGroup group = null;
1206 if (itemName == null) {
1207 //unqualified, all items in a batch(bucket) have the
1208 //same metadata values
1209 group = GetFirst<BuildItemGroup> (perBatchItemsByName.Values);
1211 group = GetFirst<BuildItemGroup> (commonItemsByName.Values);
1214 TryGetEvaluatedItemByNameBatched (itemName, out group);
1217 if (group != null) {
1218 foreach (BuildItem item in group) {
1219 if (item.HasMetadata (metadataName))
1220 return item.GetEvaluatedMetadata (metadataName);
1223 return String.Empty;
1226 internal IEnumerable<BuildItemGroup> GetAllItemGroups ()
1228 if (perBatchItemsByName == null && commonItemsByName == null)
1229 foreach (BuildItemGroup group in EvaluatedItemsByName.Values)
1232 if (perBatchItemsByName != null)
1233 foreach (BuildItemGroup group in perBatchItemsByName.Values)
1236 if (commonItemsByName != null)
1237 foreach (BuildItemGroup group in commonItemsByName.Values)
1241 T GetFirst<T> (ICollection<T> list)
1246 foreach (T t in list)
1252 internal void LogWarning (string filename, string message, params object[] messageArgs)
1254 BuildWarningEventArgs bwea = new BuildWarningEventArgs (
1255 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1257 ParentEngine.EventSource.FireWarningRaised (this, bwea);
1260 internal void LogError (string filename, string message,
1261 params object[] messageArgs)
1263 BuildErrorEventArgs beea = new BuildErrorEventArgs (
1264 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1266 ParentEngine.EventSource.FireErrorRaised (this, beea);
1269 static string ExtensionsPath {
1271 if (extensions_path == null) {
1272 // NOTE: code from mcs/tools/gacutil/driver.cs
1273 PropertyInfo gac = typeof (System.Environment).GetProperty (
1274 "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
1277 MethodInfo get_gac = gac.GetGetMethod (true);
1278 string gac_path = (string) get_gac.Invoke (null, null);
1279 extensions_path = Path.GetFullPath (Path.Combine (
1280 gac_path, Path.Combine ("..", "xbuild")));
1283 return extensions_path;
1287 public BuildPropertyGroup EvaluatedProperties {
1289 if (needToReevaluate) {
1290 needToReevaluate = false;
1293 return evaluatedProperties;
1297 internal IEnumerable EvaluatedPropertiesAsDictionaryEntries {
1299 foreach (BuildProperty bp in EvaluatedProperties)
1300 yield return new DictionaryEntry (bp.Name, bp.Value);
1304 public string FullFileName {
1305 get { return fullFileName; }
1306 set { fullFileName = value; }
1309 public BuildPropertyGroup GlobalProperties {
1310 get { return globalProperties; }
1313 throw new ArgumentNullException ("value");
1316 throw new InvalidOperationException ("GlobalProperties can not be set to persisted property group.");
1318 globalProperties = value;
1322 public bool IsDirty {
1323 get { return isDirty; }
1326 public bool IsValidated {
1327 get { return isValidated; }
1328 set { isValidated = value; }
1331 public BuildItemGroupCollection ItemGroups {
1332 get { return itemGroups; }
1335 public ImportCollection Imports {
1336 get { return imports; }
1339 public string InitialTargets {
1341 return String.Join ("; ", initialTargets.ToArray ());
1344 initialTargets.Clear ();
1345 xmlDocument.DocumentElement.SetAttribute ("InitialTargets", value);
1347 initialTargets.AddRange (value.Split (
1348 new char [] {';', ' '}, StringSplitOptions.RemoveEmptyEntries));
1352 public Engine ParentEngine {
1353 get { return parentEngine; }
1356 public BuildPropertyGroupCollection PropertyGroups {
1357 get { return propertyGroups; }
1360 public string SchemaFile {
1361 get { return schemaFile; }
1362 set { schemaFile = value; }
1365 public TargetCollection Targets {
1366 get { return targets; }
1369 public DateTime TimeOfLastDirty {
1370 get { return timeOfLastDirty; }
1373 public UsingTaskCollection UsingTasks {
1374 get { return usingTasks; }
1379 get { return xmlDocument.InnerXml; }
1382 // corresponds to the xml attribute
1383 public string DefaultToolsVersion {
1385 if (xmlDocument != null)
1386 return xmlDocument.DocumentElement.GetAttribute ("ToolsVersion");
1390 if (xmlDocument != null)
1391 xmlDocument.DocumentElement.SetAttribute ("ToolsVersion", value);
1395 public bool HasToolsVersionAttribute {
1397 return xmlDocument != null && xmlDocument.DocumentElement.HasAttribute ("ToolsVersion");
1401 public string ToolsVersion {
1405 internal Dictionary <string, BuildItemGroup> LastItemGroupContaining {
1406 get { return last_item_group_containing; }
1409 internal static XmlNamespaceManager XmlNamespaceManager {
1411 if (manager == null) {
1412 manager = new XmlNamespaceManager (new NameTable ());
1413 manager.AddNamespace ("tns", ns);
1420 internal TaskDatabase TaskDatabase {
1421 get { return taskDatabase; }
1424 internal XmlDocument XmlDocument {
1425 get { return xmlDocument; }
1428 internal static string XmlNamespace {
1434 PlatformID pid = Environment.OSVersion.Platform;
1442 return "Windows_NT";