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;
76 List<string> builtTargetKeys;
78 BuildSettings current_settings;
80 static string extensions_path;
81 static XmlNamespaceManager manager;
82 static string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
85 : this (Engine.GlobalEngine)
89 public Project (Engine engine)
91 parentEngine = engine;
93 buildEnabled = ParentEngine.BuildEnabled;
94 xmlDocument = new XmlDocument ();
95 xmlDocument.PreserveWhitespace = false;
96 xmlDocument.AppendChild (xmlDocument.CreateElement ("Project", XmlNamespace));
97 xmlDocument.DocumentElement.SetAttribute ("xmlns", ns);
99 fullFileName = String.Empty;
100 timeOfLastDirty = DateTime.Now;
101 current_settings = BuildSettings.None;
103 builtTargetKeys = new List<string> ();
104 initialTargets = new List<string> ();
105 defaultTargets = new string [0];
107 globalProperties = new BuildPropertyGroup (null, this, null, false);
108 foreach (BuildProperty bp in parentEngine.GlobalProperties)
109 GlobalProperties.AddProperty (bp.Clone (true));
114 [MonoTODO ("Not tested")]
115 public void AddNewImport (string importLocation,
116 string importCondition)
118 if (importLocation == null)
119 throw new ArgumentNullException ("importLocation");
121 XmlElement importElement = xmlDocument.CreateElement ("Import", XmlNamespace);
122 xmlDocument.DocumentElement.AppendChild (importElement);
123 importElement.SetAttribute ("Project", importLocation);
124 if (!String.IsNullOrEmpty (importCondition))
125 importElement.SetAttribute ("Condition", importCondition);
127 Import import = new Import (importElement, this, null);
128 imports.Add (import);
129 MarkProjectAsDirty ();
133 public BuildItem AddNewItem (string itemName,
136 return AddNewItem (itemName, itemInclude, false);
139 [MonoTODO ("Adds item not in the same place as MS")]
140 public BuildItem AddNewItem (string itemName,
142 bool treatItemIncludeAsLiteral)
146 if (itemGroups.Count == 0)
147 big = AddNewItemGroup ();
149 if (last_item_group_containing.ContainsKey (itemName)) {
150 big = last_item_group_containing [itemName];
153 BuildItemGroup [] groups = new BuildItemGroup [itemGroups.Count];
154 itemGroups.CopyTo (groups, 0);
159 BuildItem item = big.AddNewItem (itemName, itemInclude, treatItemIncludeAsLiteral);
161 MarkProjectAsDirty ();
167 [MonoTODO ("Not tested")]
168 public BuildItemGroup AddNewItemGroup ()
170 XmlElement element = xmlDocument.CreateElement ("ItemGroup", XmlNamespace);
171 xmlDocument.DocumentElement.AppendChild (element);
173 BuildItemGroup big = new BuildItemGroup (element, this, null, false);
174 itemGroups.Add (big);
175 MarkProjectAsDirty ();
181 [MonoTODO ("Ignores insertAtEndOfProject")]
182 public BuildPropertyGroup AddNewPropertyGroup (bool insertAtEndOfProject)
184 XmlElement element = xmlDocument.CreateElement ("PropertyGroup", XmlNamespace);
185 xmlDocument.DocumentElement.AppendChild (element);
187 BuildPropertyGroup bpg = new BuildPropertyGroup (element, this, null, false);
188 propertyGroups.Add (bpg);
189 MarkProjectAsDirty ();
195 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
196 public void AddNewUsingTaskFromAssemblyFile (string taskName,
199 if (taskName == null)
200 throw new ArgumentNullException ("taskName");
201 if (assemblyFile == null)
202 throw new ArgumentNullException ("assemblyFile");
204 XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
205 xmlDocument.DocumentElement.AppendChild (element);
206 element.SetAttribute ("TaskName", taskName);
207 element.SetAttribute ("AssemblyFile", assemblyFile);
209 UsingTask ut = new UsingTask (element, this, null);
211 MarkProjectAsDirty ();
214 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
215 public void AddNewUsingTaskFromAssemblyName (string taskName,
218 if (taskName == null)
219 throw new ArgumentNullException ("taskName");
220 if (assemblyName == null)
221 throw new ArgumentNullException ("assemblyName");
223 XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
224 xmlDocument.DocumentElement.AppendChild (element);
225 element.SetAttribute ("TaskName", taskName);
226 element.SetAttribute ("AssemblyName", assemblyName);
228 UsingTask ut = new UsingTask (element, this, null);
230 MarkProjectAsDirty ();
233 [MonoTODO ("Not tested")]
236 return Build (new string [0]);
239 [MonoTODO ("Not tested")]
240 public bool Build (string targetName)
242 if (targetName == null)
243 return Build ((string[]) null);
245 return Build (new string [1] { targetName });
248 [MonoTODO ("Not tested")]
249 public bool Build (string [] targetNames)
251 return Build (targetNames, null);
254 [MonoTODO ("Not tested")]
255 public bool Build (string [] targetNames,
256 IDictionary targetOutputs)
258 return Build (targetNames, targetOutputs, BuildSettings.None);
261 [MonoTODO ("Not tested")]
262 public bool Build (string [] targetNames,
263 IDictionary targetOutputs,
264 BuildSettings buildFlags)
268 ParentEngine.StartProjectBuild (this, targetNames);
269 string current_directory = Environment.CurrentDirectory;
271 current_settings = buildFlags;
272 if (!String.IsNullOrEmpty (fullFileName))
273 Directory.SetCurrentDirectory (Path.GetDirectoryName (fullFileName));
275 result = BuildInternal (targetNames, targetOutputs, buildFlags);
277 ParentEngine.EndProjectBuild (this, result);
278 current_settings = BuildSettings.None;
279 Directory.SetCurrentDirectory (current_directory);
286 bool BuildInternal (string [] targetNames,
287 IDictionary targetOutputs,
288 BuildSettings buildFlags)
291 if (buildFlags == BuildSettings.None)
294 if (targetNames == null || targetNames.Length == 0) {
295 if (defaultTargets != null && defaultTargets.Length != 0)
296 targetNames = defaultTargets;
297 else if (firstTargetName != null)
298 targetNames = new string [1] { firstTargetName};
303 if (!initialTargetsBuilt) {
304 foreach (string target in initialTargets) {
305 if (!BuildTarget (target.Trim (), targetOutputs))
308 initialTargetsBuilt = true;
311 foreach (string target in targetNames)
312 if (!BuildTarget (target.Trim (), targetOutputs))
318 bool BuildTarget (string target_name, IDictionary targetOutputs)
320 if (target_name == null)
321 throw new ArgumentException ("targetNames cannot contain null strings");
323 if (!targets.Exists (target_name)) {
325 Console.WriteLine ("Target named '{0}' not found in the project.", target_name);
329 string key = GetKeyForTarget (target_name);
330 if (!targets [target_name].Build (key))
334 if (ParentEngine.BuiltTargetsOutputByName.TryGetValue (key, out outputs)) {
335 if (targetOutputs != null)
336 targetOutputs.Add (target_name, outputs);
341 internal string GetKeyForTarget (string target_name)
343 // target name is case insensitive
344 return fullFileName + ":" + target_name.ToLower () + ":" + GlobalPropertiesToString (GlobalProperties);
347 string GlobalPropertiesToString (BuildPropertyGroup bgp)
349 StringBuilder sb = new StringBuilder ();
350 foreach (BuildProperty bp in bgp)
351 sb.AppendFormat (" {0}:{1}", bp.Name, bp.FinalValue);
352 return sb.ToString ();
356 public string [] GetConditionedPropertyValues (string propertyName)
358 if (conditionedProperties.ContainsKey (propertyName))
359 return conditionedProperties [propertyName].ToArray ();
361 return new string [0];
364 public BuildItemGroup GetEvaluatedItemsByName (string itemName)
366 if (needToReevaluate) {
367 needToReevaluate = false;
371 if (evaluatedItemsByName.ContainsKey (itemName))
372 return evaluatedItemsByName [itemName];
374 return new BuildItemGroup (this);
377 public BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition (string itemName)
379 if (needToReevaluate) {
380 needToReevaluate = false;
384 if (evaluatedItemsByNameIgnoringCondition.ContainsKey (itemName))
385 return evaluatedItemsByNameIgnoringCondition [itemName];
387 return new BuildItemGroup (this);
390 public string GetEvaluatedProperty (string propertyName)
392 if (needToReevaluate) {
393 needToReevaluate = false;
397 if (propertyName == null)
398 throw new ArgumentNullException ("propertyName");
400 BuildProperty bp = evaluatedProperties [propertyName];
402 return bp == null ? null : (string) bp;
405 [MonoTODO ("We should remember that node and not use XPath to get it")]
406 public string GetProjectExtensions (string id)
408 if (id == null || id == String.Empty)
411 XmlNode node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
416 return node.InnerXml;
420 public void Load (string projectFileName)
422 this.fullFileName = Utilities.FromMSBuildPath (Path.GetFullPath (projectFileName));
424 string filename = fullFileName;
425 if (String.Compare (Path.GetExtension (fullFileName), ".sln", true) == 0) {
426 Project tmp_project = ParentEngine.CreateNewProject ();
427 SolutionParser sln_parser = new SolutionParser ();
428 sln_parser.ParseSolution (fullFileName, tmp_project, delegate (int errorNumber, string message) {
429 LogWarning (filename, message);
431 filename = fullFileName + ".proj";
433 tmp_project.Save (filename);
434 ParentEngine.RemoveLoadedProject (tmp_project);
435 DoLoad (new StreamReader (filename));
437 if (Environment.GetEnvironmentVariable ("XBUILD_EMIT_SOLUTION") == null)
438 File.Delete (filename);
441 DoLoad (new StreamReader (filename));
445 [MonoTODO ("Not tested")]
446 public void Load (TextReader textReader)
448 fullFileName = String.Empty;
452 public void LoadXml (string projectXml)
454 fullFileName = String.Empty;
455 DoLoad (new StringReader (projectXml));
456 MarkProjectAsDirty ();
460 public void MarkProjectAsDirty ()
463 timeOfLastDirty = DateTime.Now;
466 [MonoTODO ("Not tested")]
467 public void RemoveAllItemGroups ()
469 int length = ItemGroups.Count;
470 BuildItemGroup [] groups = new BuildItemGroup [length];
471 ItemGroups.CopyTo (groups, 0);
473 for (int i = 0; i < length; i++)
474 RemoveItemGroup (groups [i]);
476 MarkProjectAsDirty ();
480 [MonoTODO ("Not tested")]
481 public void RemoveAllPropertyGroups ()
483 int length = PropertyGroups.Count;
484 BuildPropertyGroup [] groups = new BuildPropertyGroup [length];
485 PropertyGroups.CopyTo (groups, 0);
487 for (int i = 0; i < length; i++)
488 RemovePropertyGroup (groups [i]);
490 MarkProjectAsDirty ();
495 public void RemoveItem (BuildItem itemToRemove)
497 if (itemToRemove == null)
498 throw new ArgumentNullException ("itemToRemove");
500 if (!itemToRemove.FromXml && !itemToRemove.HasParentItem)
501 throw new InvalidOperationException ("The object passed in is not part of the project.");
503 BuildItemGroup big = itemToRemove.ParentItemGroup;
505 if (big.Count == 1) {
506 // ParentItemGroup for items from xml and that have parent is the same
507 groupingCollection.Remove (big);
509 if (big.ParentProject != this)
510 throw new InvalidOperationException ("The object passed in is not part of the project.");
512 if (itemToRemove.FromXml)
513 big.RemoveItem (itemToRemove);
515 big.RemoveItem (itemToRemove.ParentItem);
518 MarkProjectAsDirty ();
522 [MonoTODO ("Not tested")]
523 public void RemoveItemGroup (BuildItemGroup itemGroupToRemove)
525 if (itemGroupToRemove == null)
526 throw new ArgumentNullException ("itemGroupToRemove");
528 groupingCollection.Remove (itemGroupToRemove);
529 MarkProjectAsDirty ();
533 // NOTE: does not modify imported projects
534 public void RemoveItemGroupsWithMatchingCondition (string matchingCondition)
536 throw new NotImplementedException ();
540 public void RemoveItemsByName (string itemName)
542 if (itemName == null)
543 throw new ArgumentNullException ("itemName");
545 throw new NotImplementedException ();
548 [MonoTODO ("Not tested")]
549 public void RemovePropertyGroup (BuildPropertyGroup propertyGroupToRemove)
551 if (propertyGroupToRemove == null)
552 throw new ArgumentNullException ("propertyGroupToRemove");
554 groupingCollection.Remove (propertyGroupToRemove);
555 MarkProjectAsDirty ();
559 // NOTE: does not modify imported projects
560 public void RemovePropertyGroupsWithMatchingCondition (string matchCondition)
562 throw new NotImplementedException ();
566 public void ResetBuildStatus ()
568 // hack to allow built targets to be removed
574 public void Save (string projectFileName)
576 Save (projectFileName, Encoding.Default);
580 [MonoTODO ("Ignores encoding")]
581 public void Save (string projectFileName, Encoding encoding)
583 xmlDocument.Save (projectFileName);
587 public void Save (TextWriter outTextWriter)
589 xmlDocument.Save (outTextWriter);
593 public void SetImportedProperty (string propertyName,
594 string propertyValue,
596 Project importProject)
598 SetImportedProperty (propertyName, propertyValue, condition, importProject,
599 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
602 public void SetImportedProperty (string propertyName,
603 string propertyValue,
605 Project importedProject,
606 PropertyPosition position)
608 SetImportedProperty (propertyName, propertyValue, condition, importedProject,
609 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
613 public void SetImportedProperty (string propertyName,
614 string propertyValue,
616 Project importedProject,
617 PropertyPosition position,
618 bool treatPropertyValueAsLiteral)
620 throw new NotImplementedException ();
623 public void SetProjectExtensions (string id, string xmlText)
626 throw new ArgumentNullException ("id");
628 throw new ArgumentNullException ("xmlText");
630 XmlNode projectExtensions, node;
632 projectExtensions = xmlDocument.SelectSingleNode ("/tns:Project/tns:ProjectExtensions", XmlNamespaceManager);
634 if (projectExtensions == null) {
635 projectExtensions = xmlDocument.CreateElement ("ProjectExtensions", XmlNamespace);
636 xmlDocument.DocumentElement.AppendChild (projectExtensions);
638 node = xmlDocument.CreateElement (id, XmlNamespace);
639 node.InnerXml = xmlText;
640 projectExtensions.AppendChild (node);
642 node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
645 node = xmlDocument.CreateElement (id, XmlNamespace);
646 projectExtensions.AppendChild (node);
649 node.InnerXml = xmlText;
653 MarkProjectAsDirty ();
656 public void SetProperty (string propertyName,
657 string propertyValue)
659 SetProperty (propertyName, propertyValue, "true",
660 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
663 public void SetProperty (string propertyName,
664 string propertyValue,
667 SetProperty (propertyName, propertyValue, condition,
668 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
671 public void SetProperty (string propertyName,
672 string propertyValue,
674 PropertyPosition position)
676 SetProperty (propertyName, propertyValue, condition,
677 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
681 public void SetProperty (string propertyName,
682 string propertyValue,
684 PropertyPosition position,
685 bool treatPropertyValueAsLiteral)
687 throw new NotImplementedException ();
690 internal void Unload ()
695 internal void CheckUnloaded ()
698 throw new InvalidOperationException ("This project object has been unloaded from the MSBuild engine and is no longer valid.");
701 internal void NeedToReevaluate ()
703 needToReevaluate = true;
706 // Does the actual loading.
707 void DoLoad (TextReader textReader)
710 ParentEngine.RemoveLoadedProject (this);
712 xmlDocument.Load (textReader);
714 if (xmlDocument.DocumentElement.Name == "VisualStudioProject")
715 throw new InvalidProjectFileException (String.Format (
716 "Project file '{0}' is a VS2003 project, which is not " +
717 "supported by xbuild. You need to convert it to msbuild " +
718 "format to build with xbuild.", fullFileName));
720 if (SchemaFile != null) {
721 xmlDocument.Schemas.Add (XmlSchema.Read (
722 new StreamReader (SchemaFile), ValidationCallBack));
723 xmlDocument.Validate (ValidationCallBack);
726 if (xmlDocument.DocumentElement.Name != "Project") {
727 throw new InvalidProjectFileException (String.Format (
728 "The element <{0}> is unrecognized, or not supported in this context.", xmlDocument.DocumentElement.Name));
731 if (xmlDocument.DocumentElement.GetAttribute ("xmlns") != ns) {
732 throw new InvalidProjectFileException (
733 @"The default XML namespace of the project must be the MSBuild XML namespace." +
734 " If the project is authored in the MSBuild 2003 format, please add " +
735 "xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" to the <Project> element. " +
736 "If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format. ");
739 ParentEngine.AddLoadedProject (this);
740 } catch (Exception e) {
741 throw new InvalidProjectFileException (String.Format ("{0}: {1}",
742 fullFileName, e.Message), e);
744 if (textReader != null)
756 groupingCollection = new GroupingCollection (this);
757 imports = new ImportCollection (groupingCollection);
758 usingTasks = new UsingTaskCollection (this);
759 itemGroups = new BuildItemGroupCollection (groupingCollection);
760 propertyGroups = new BuildPropertyGroupCollection (groupingCollection);
761 targets = new TargetCollection (this);
762 last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
764 taskDatabase = new TaskDatabase ();
765 if (ParentEngine.DefaultTasksRegistered)
766 taskDatabase.CopyTasks (ParentEngine.DefaultTasks);
768 initialTargets = new List<string> ();
769 defaultTargets = new string [0];
770 PrepareForEvaluate ();
771 ProcessElements (xmlDocument.DocumentElement, null);
777 void ProcessProjectAttributes (XmlAttributeCollection attributes)
779 foreach (XmlAttribute attr in attributes) {
781 case "InitialTargets":
782 initialTargets.AddRange (attr.Value.Split (
783 new char [] {';', ' '},
784 StringSplitOptions.RemoveEmptyEntries));
786 case "DefaultTargets":
787 // first non-empty DefaultTargets found is used
788 if (defaultTargets == null || defaultTargets.Length == 0)
789 defaultTargets = attr.Value.Split (new char [] {';', ' '},
790 StringSplitOptions.RemoveEmptyEntries);
791 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets",
792 DefaultTargets, PropertyType.Reserved));
798 internal void ProcessElements (XmlElement rootElement, ImportedProject ip)
800 ProcessProjectAttributes (rootElement.Attributes);
801 foreach (XmlNode xn in rootElement.ChildNodes) {
802 if (xn is XmlElement) {
803 XmlElement xe = (XmlElement) xn;
805 case "ProjectExtensions":
806 AddProjectExtensions (xe);
817 AddUsingTask (xe, ip);
823 AddItemGroup (xe, ip);
825 case "PropertyGroup":
826 AddPropertyGroup (xe, ip);
832 throw new InvalidProjectFileException ("Invalid element in project file.");
838 void PrepareForEvaluate ()
840 evaluatedItems = new BuildItemGroup (null, this, null, true);
841 evaluatedItemsIgnoringCondition = new BuildItemGroup (null, this, null, true);
842 evaluatedItemsByName = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
843 evaluatedItemsByNameIgnoringCondition = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
844 if (building && current_settings == BuildSettings.None)
845 RemoveBuiltTargets ();
847 InitializeProperties ();
852 groupingCollection.Evaluate ();
854 //FIXME: UsingTasks aren't really evaluated. (shouldn't use expressions or anything)
855 foreach (UsingTask usingTask in UsingTasks)
856 usingTask.Evaluate ();
859 // Removes entries of all earlier built targets for this project
860 void RemoveBuiltTargets ()
862 foreach (string key in builtTargetKeys)
863 ParentEngine.BuiltTargetsOutputByName.Remove (key);
866 void InitializeProperties ()
870 evaluatedProperties = new BuildPropertyGroup (null, null, null, true);
872 foreach (BuildProperty gp in GlobalProperties) {
873 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
874 EvaluatedProperties.AddProperty (bp);
877 foreach (BuildProperty gp in GlobalProperties)
878 ParentEngine.GlobalProperties.AddProperty (gp);
880 // add properties that we dont have from parent engine's
882 foreach (BuildProperty gp in ParentEngine.GlobalProperties) {
883 if (EvaluatedProperties [gp.Name] == null) {
884 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
885 EvaluatedProperties.AddProperty (bp);
889 foreach (DictionaryEntry de in Environment.GetEnvironmentVariables ()) {
890 bp = new BuildProperty ((string) de.Key, (string) de.Value, PropertyType.Environment);
891 EvaluatedProperties.AddProperty (bp);
894 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFile", Path.GetFileName (fullFileName),
895 PropertyType.Reserved));
896 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectName",
897 Path.GetFileNameWithoutExtension (fullFileName),
898 PropertyType.Reserved));
899 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", parentEngine.BinPath, PropertyType.Reserved));
900 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", parentEngine.BinPath, PropertyType.Reserved));
901 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath", ExtensionsPath, PropertyType.Reserved));
902 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets", DefaultTargets, PropertyType.Reserved));
903 EvaluatedProperties.AddProperty (new BuildProperty ("OS", OS, PropertyType.Environment));
905 // FIXME: make some internal method that will work like GetDirectoryName but output String.Empty on null/String.Empty
907 if (FullFileName == String.Empty)
908 projectDir = Environment.CurrentDirectory;
910 projectDir = Path.GetDirectoryName (FullFileName);
912 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDirectory", projectDir, PropertyType.Reserved));
915 void AddProjectExtensions (XmlElement xmlElement)
919 void AddMessage (XmlElement xmlElement)
923 void AddTarget (XmlElement xmlElement, ImportedProject importedProject)
925 Target target = new Target (xmlElement, this, importedProject);
926 targets.AddTarget (target);
928 if (firstTargetName == null)
929 firstTargetName = target.Name;
932 void AddUsingTask (XmlElement xmlElement, ImportedProject importedProject)
936 usingTask = new UsingTask (xmlElement, this, importedProject);
937 UsingTasks.Add (usingTask);
940 void AddImport (XmlElement xmlElement, ImportedProject importingProject)
942 // eval all the properties etc till the import
943 groupingCollection.Evaluate (EvaluationType.Property);
945 Import import = new Import (xmlElement, this, importingProject);
946 if (!ConditionParser.ParseAndEvaluate (import.Condition, this))
949 if (Imports.Contains (import)) {
950 LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
951 "A circular reference was found involving the import of {0}. Only" +
952 " the first import of this file will be used, ignoring others.",
958 if (String.Compare (fullFileName, import.EvaluatedProjectPath) == 0) {
959 LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
960 "The main project file was imported here, which creates a circular " +
961 "reference. Ignoring this import.");
966 Imports.Add (import);
970 void AddItemGroup (XmlElement xmlElement, ImportedProject importedProject)
972 BuildItemGroup big = new BuildItemGroup (xmlElement, this, importedProject, false);
973 ItemGroups.Add (big);
976 void AddPropertyGroup (XmlElement xmlElement, ImportedProject importedProject)
978 BuildPropertyGroup bpg = new BuildPropertyGroup (xmlElement, this, importedProject, false);
979 PropertyGroups.Add (bpg);
982 void AddChoose (XmlElement xmlElement)
984 BuildChoose bc = new BuildChoose (xmlElement, this);
985 groupingCollection.Add (bc);
988 static void ValidationCallBack (object sender, ValidationEventArgs e)
990 Console.WriteLine ("Validation Error: {0}", e.Message);
993 public bool BuildEnabled {
998 buildEnabled = value;
1003 public Encoding Encoding {
1004 get { return encoding; }
1007 public string DefaultTargets {
1009 return String.Join ("; ", defaultTargets);
1012 xmlDocument.DocumentElement.SetAttribute ("DefaultTargets", value);
1014 defaultTargets = value.Split (new char [] {';', ' '},
1015 StringSplitOptions.RemoveEmptyEntries);
1019 public BuildItemGroup EvaluatedItems {
1021 if (needToReevaluate) {
1022 needToReevaluate = false;
1025 return evaluatedItems;
1029 public BuildItemGroup EvaluatedItemsIgnoringCondition {
1031 if (needToReevaluate) {
1032 needToReevaluate = false;
1035 return evaluatedItemsIgnoringCondition;
1039 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByName {
1041 // FIXME: do we need to do this here?
1042 if (needToReevaluate) {
1043 needToReevaluate = false;
1046 return evaluatedItemsByName;
1050 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByNameIgnoringCondition {
1052 // FIXME: do we need to do this here?
1053 if (needToReevaluate) {
1054 needToReevaluate = false;
1057 return evaluatedItemsByNameIgnoringCondition;
1061 // For batching implementation
1062 Dictionary<string, BuildItemGroup> perBatchItemsByName;
1063 Dictionary<string, BuildItemGroup> commonItemsByName;
1065 internal void SetBatchedItems (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1067 this.perBatchItemsByName = perBatchItemsByName;
1068 this.commonItemsByName = commonItemsByName;
1072 internal bool TryGetEvaluatedItemByNameBatched (string itemName, out BuildItemGroup group)
1074 if (perBatchItemsByName == null && commonItemsByName == null)
1075 return EvaluatedItemsByName.TryGetValue (itemName, out group);
1077 if (perBatchItemsByName != null)
1078 return perBatchItemsByName.TryGetValue (itemName, out group);
1080 if (commonItemsByName != null)
1081 return commonItemsByName.TryGetValue (itemName, out group);
1087 internal string GetMetadataBatched (string itemName, string metadataName)
1089 BuildItemGroup group = null;
1090 if (itemName == null) {
1091 //unqualified, all items in a batch(bucket) have the
1092 //same metadata values
1093 group = GetFirst<BuildItemGroup> (perBatchItemsByName.Values);
1095 group = GetFirst<BuildItemGroup> (commonItemsByName.Values);
1098 TryGetEvaluatedItemByNameBatched (itemName, out group);
1101 if (group != null) {
1102 foreach (BuildItem item in group) {
1103 if (item.HasMetadata (metadataName))
1104 return item.GetEvaluatedMetadata (metadataName);
1107 return String.Empty;
1110 internal IEnumerable<BuildItemGroup> GetAllItemGroups ()
1112 if (perBatchItemsByName == null && commonItemsByName == null)
1113 foreach (BuildItemGroup group in EvaluatedItemsByName.Values)
1116 if (perBatchItemsByName != null)
1117 foreach (BuildItemGroup group in perBatchItemsByName.Values)
1120 if (commonItemsByName != null)
1121 foreach (BuildItemGroup group in commonItemsByName.Values)
1125 T GetFirst<T> (ICollection<T> list)
1130 foreach (T t in list)
1136 void LogWarning (string filename, string message, params object[] messageArgs)
1138 BuildWarningEventArgs bwea = new BuildWarningEventArgs (
1139 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1141 ParentEngine.EventSource.FireWarningRaised (this, bwea);
1144 static string ExtensionsPath {
1146 if (extensions_path == null) {
1147 // NOTE: code from mcs/tools/gacutil/driver.cs
1148 PropertyInfo gac = typeof (System.Environment).GetProperty (
1149 "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
1152 MethodInfo get_gac = gac.GetGetMethod (true);
1153 string gac_path = (string) get_gac.Invoke (null, null);
1154 extensions_path = Path.GetFullPath (Path.Combine (
1155 gac_path, Path.Combine ("..", "xbuild")));
1158 return extensions_path;
1162 public BuildPropertyGroup EvaluatedProperties {
1164 if (needToReevaluate) {
1165 needToReevaluate = false;
1168 return evaluatedProperties;
1172 public string FullFileName {
1173 get { return fullFileName; }
1174 set { fullFileName = value; }
1177 public BuildPropertyGroup GlobalProperties {
1178 get { return globalProperties; }
1181 throw new ArgumentNullException ("value");
1184 throw new InvalidOperationException ("GlobalProperties can not be set to persisted property group.");
1186 globalProperties = value;
1187 NeedToReevaluate ();
1191 public bool IsDirty {
1192 get { return isDirty; }
1195 public bool IsValidated {
1196 get { return isValidated; }
1197 set { isValidated = value; }
1200 public BuildItemGroupCollection ItemGroups {
1201 get { return itemGroups; }
1204 public ImportCollection Imports {
1205 get { return imports; }
1208 public string InitialTargets {
1210 return String.Join ("; ", initialTargets.ToArray ());
1213 initialTargets.Clear ();
1214 xmlDocument.DocumentElement.SetAttribute ("InitialTargets", value);
1216 initialTargets.AddRange (value.Split (
1217 new char [] {';', ' '}, StringSplitOptions.RemoveEmptyEntries));
1221 public Engine ParentEngine {
1222 get { return parentEngine; }
1225 public BuildPropertyGroupCollection PropertyGroups {
1226 get { return propertyGroups; }
1229 public string SchemaFile {
1230 get { return schemaFile; }
1231 set { schemaFile = value; }
1234 public TargetCollection Targets {
1235 get { return targets; }
1238 public DateTime TimeOfLastDirty {
1239 get { return timeOfLastDirty; }
1242 public UsingTaskCollection UsingTasks {
1243 get { return usingTasks; }
1248 get { return xmlDocument.InnerXml; }
1251 internal List<string> BuiltTargetKeys {
1252 get { return builtTargetKeys; }
1255 internal Dictionary <string, BuildItemGroup> LastItemGroupContaining {
1256 get { return last_item_group_containing; }
1259 internal static XmlNamespaceManager XmlNamespaceManager {
1261 if (manager == null) {
1262 manager = new XmlNamespaceManager (new NameTable ());
1263 manager.AddNamespace ("tns", ns);
1270 internal TaskDatabase TaskDatabase {
1271 get { return taskDatabase; }
1274 internal XmlDocument XmlDocument {
1275 get { return xmlDocument; }
1278 internal static string XmlNamespace {
1284 PlatformID pid = Environment.OSVersion.Platform;
1292 return "Windows_NT";