[xbuild] Don't report Imports ignored because of false conditions.
[mono.git] / mcs / class / Microsoft.Build.Engine / Microsoft.Build.BuildEngine / Import.cs
1 //
2 // Import.cs: Represents a single Import element in an MSBuild project.
3 //
4 // Author:
5 //   Marek Sieradzki (marek.sieradzki@gmail.com)
6 //   Ankit Jain (jankit@novell.com)
7 // 
8 // (C) 2006 Marek Sieradzki
9 // Copyright 2011 Novell, Inc (http://www.novell.com)
10 //
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:
18 //
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 //
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.
29
30 #if NET_2_0
31
32 using System;
33 using System.Collections.Generic;
34 using System.IO;
35 using System.Linq;
36 using System.Xml;
37
38 using Microsoft.Build.Framework;
39 using Microsoft.Build.Utilities;
40 using Mono.XBuild.Utilities;
41
42 namespace Microsoft.Build.BuildEngine {
43         public class Import {
44                 XmlElement      importElement;
45                 Project         project;
46                 ImportedProject originalProject;
47                 string          evaluatedProjectPath;
48
49                 static string DotConfigExtensionsPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
50                                                                 Path.Combine ("xbuild", "tasks"));
51                 const string MacOSXExternalXBuildDir = "/Library/Frameworks/Mono.framework/External/xbuild";
52                 static string PathSeparatorAsString = Path.PathSeparator.ToString ();
53         
54                 internal Import (XmlElement importElement, Project project, ImportedProject originalProject)
55                         : this (importElement, null, project, originalProject)
56                 {}
57
58                 // if @alternateProjectPath is available then that it used as the EvaluatedProjectPath!
59                 internal Import (XmlElement importElement, string alternateProjectPath, Project project, ImportedProject originalProject)
60                 {
61                         if (importElement == null)
62                                 throw new ArgumentNullException ("importElement");
63                         if (project == null)
64                                 throw new ArgumentNullException ("project");
65                 
66                         this.project = project;
67                         this.importElement = importElement;
68                         this.originalProject = originalProject;
69
70                         if (ProjectPath == String.Empty)
71                                 throw new InvalidProjectFileException ("The required attribute \"Project\" is missing from element <Import>.");
72
73                         if (ConditionParser.ParseAndEvaluate (Condition, project)) {
74                                 evaluatedProjectPath = String.IsNullOrEmpty (alternateProjectPath) ? EvaluateProjectPath (ProjectPath) : alternateProjectPath;
75
76                                 evaluatedProjectPath = GetFullPath ();
77                                 if (EvaluatedProjectPath == String.Empty)
78                                         throw new InvalidProjectFileException ("The required attribute \"Project\" is missing from element <Import>.");
79                         }
80                 }
81
82                 // FIXME: condition
83                 internal void Evaluate (bool ignoreMissingImports)
84                 {
85                         string filename = evaluatedProjectPath;
86                         // NOTE: it's a hack to transform Microsoft.CSharp.Targets to Microsoft.CSharp.targets
87                         if (!File.Exists (filename) && Path.GetFileName (filename) == "Microsoft.CSharp.Targets")
88                                 filename = Path.ChangeExtension (filename, ".targets");
89
90                         if (!File.Exists (filename)) {
91                                 if (ignoreMissingImports) {
92                                         project.LogWarning (project.FullFileName, "Could not find project file {0}, to import. Ignoring.", filename);
93                                         return;
94                                 } else {
95                                         throw new InvalidProjectFileException (String.Format ("Imported project: \"{0}\" does not exist.", filename));
96                                 }
97                         }
98                         
99                         ImportedProject importedProject = new ImportedProject ();
100                         importedProject.Load (filename);
101
102                         project.ProcessElements (importedProject.XmlDocument.DocumentElement, importedProject);
103                 }
104
105                 string EvaluateProjectPath (string file)
106                 {
107                         return Expression.ParseAs<string> (file, ParseOptions.Split, project);
108                 }
109
110                 string GetFullPath ()
111                 {
112                         string file = EvaluatedProjectPath;
113                         if (!Path.IsPathRooted (file) && !String.IsNullOrEmpty (ContainedInProjectFileName))
114                                 file = Path.Combine (Path.GetDirectoryName (ContainedInProjectFileName), file);
115
116                         return MSBuildUtils.FromMSBuildPath (file);
117                 }
118
119                 // For every extension path, in order, finds suitable
120                 // import filename(s) matching the Import, and calls
121                 // @func with them
122                 //
123                 // func: bool func(importPath, from_source_msg)
124                 //
125                 // If for an extension path, atleast one file gets imported,
126                 // then it stops at that.
127                 // So, in case imports like "$(MSBuildExtensionsPath)\foo\*",
128                 // for every extension path, it will try to import the "foo\*",
129                 // and if atleast one file gets successfully imported, then it
130                 // stops at that
131                 internal static void ForEachExtensionPathTillFound (XmlElement xmlElement, Project project, ImportedProject importingProject,
132                                 Func<string, string, bool> func)
133                 {
134                         string project_attribute = xmlElement.GetAttribute ("Project");
135                         string condition_attribute = xmlElement.GetAttribute ("Condition");
136
137                         bool has_extn_ref = project_attribute.IndexOf ("$(MSBuildExtensionsPath)") >= 0 ||
138                                                 project_attribute.IndexOf ("$(MSBuildExtensionsPath32)") >= 0 ||
139                                                 project_attribute.IndexOf ("$(MSBuildExtensionsPath64)") >= 0;
140
141                         string importingFile = importingProject != null ? importingProject.FullFileName : project.FullFileName;
142                         DirectoryInfo base_dir_info = null;
143                         if (!String.IsNullOrEmpty (importingFile))
144                                 base_dir_info = new DirectoryInfo (Path.GetDirectoryName (importingFile));
145                         else
146                                 base_dir_info = new DirectoryInfo (Directory.GetCurrentDirectory ());
147
148                         IEnumerable<string> extn_paths = has_extn_ref ? GetExtensionPaths (project) : new string [] {null};
149                         try {
150                                 foreach (string path in extn_paths) {
151                                         string extn_msg = null;
152                                         if (has_extn_ref) {
153                                                 project.SetExtensionsPathProperties (path);
154                                                 extn_msg = "from extension path " + path;
155                                         }
156
157                                         // do this after setting new Extension properties, as condition might
158                                         // reference it
159                                         if (!ConditionParser.ParseAndEvaluate (condition_attribute, project))
160                                                 continue;
161
162                                         // We stop if atleast one file got imported.
163                                         // Remaining extension paths are *not* tried
164                                         bool atleast_one = false;
165                                         foreach (string importPath in GetImportPathsFromString (project_attribute, project, base_dir_info)) {
166                                                 try {
167                                                         if (func (importPath, extn_msg))
168                                                                 atleast_one = true;
169                                                 } catch (Exception e) {
170                                                         throw new InvalidProjectFileException (String.Format (
171                                                                                 "{0}: Project file could not be imported, it was being imported by " +
172                                                                                 "{1}: {2}", importPath, importingFile, e.Message), e);
173                                                 }
174                                         }
175
176                                         if (atleast_one)
177                                                 return;
178                                 }
179                         } finally {
180                                 if (has_extn_ref)
181                                         project.SetExtensionsPathProperties (Project.DefaultExtensionsPath);
182                         }
183                 }
184
185                 // Parses the Project attribute from an Import,
186                 // and returns the import filenames that match.
187                 // This handles wildcards also
188                 static IEnumerable<string> GetImportPathsFromString (string import_string, Project project, DirectoryInfo base_dir_info)
189                 {
190                         string parsed_import = Expression.ParseAs<string> (import_string, ParseOptions.AllowItemsNoMetadataAndSplit, project);
191                         if (parsed_import != null)
192                                 parsed_import = parsed_import.Trim ();
193
194                         if (String.IsNullOrEmpty (parsed_import))
195                                 throw new InvalidProjectFileException ("The required attribute \"Project\" in Import is empty");
196
197 #if NET_4_0
198                         if (DirectoryScanner.HasWildcard (parsed_import)) {
199                                 var directoryScanner = new DirectoryScanner () {
200                                         Includes = new ITaskItem [] { new TaskItem (parsed_import) },
201                                         BaseDirectory = base_dir_info
202                                 };
203                                 directoryScanner.Scan ();
204
205                                 foreach (ITaskItem matchedItem in directoryScanner.MatchedItems)
206                                         yield return matchedItem.ItemSpec;
207                         } else
208 #endif
209                                 yield return parsed_import;
210                 }
211
212                 // Gives a list of extensions paths to try for $(MSBuildExtensionsPath),
213                 // *in-order*
214                 static IEnumerable<string> GetExtensionPaths (Project project)
215                 {
216                         // This is a *HACK* to support multiple paths for
217                         // MSBuildExtensionsPath property. Normally it would
218                         // get resolved to a single value, but here we special
219                         // case it and try various paths, see the code below
220                         //
221                         // The property itself will resolve to the default
222                         // location though, so you get that in any other part of the
223                         // project.
224
225                         string envvar = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath");
226                         envvar = String.Join (PathSeparatorAsString, new string [] {
227                                                 (envvar ?? String.Empty),
228                                                 // For mac osx, look in the 'External' dir on macosx,
229                                                 // see bug #663180
230                                                 MSBuildUtils.RunningOnMac ? MacOSXExternalXBuildDir : String.Empty,
231                                                 DotConfigExtensionsPath,
232                                                 Project.DefaultExtensionsPath});
233
234                         var pathsTable = new Dictionary<string, string> ();
235                         foreach (string extn_path in envvar.Split (new char [] {Path.PathSeparator}, StringSplitOptions.RemoveEmptyEntries)) {
236                                 if (pathsTable.ContainsKey (extn_path))
237                                         continue;
238
239                                 if (!Directory.Exists (extn_path)) {
240                                         project.ParentEngine.LogMessage (MessageImportance.Low, "Extension path '{0}' not found, ignoring.", extn_path);
241                                         continue;
242                                 }
243
244                                 pathsTable [extn_path] = extn_path;
245                                 yield return extn_path;
246                         }
247                 }
248
249                 public string Condition {
250                         get {
251                                 string s = importElement.GetAttribute ("Condition");
252                                 return s == String.Empty ? null : s;
253                         }
254                 }
255                 
256                 public string EvaluatedProjectPath {
257                         get { return evaluatedProjectPath; }
258                 }
259                 
260                 public bool IsImported {
261                         get { return originalProject != null; }
262                 }
263                 
264                 public string ProjectPath {
265                         get { return importElement.GetAttribute ("Project"); }
266                 }
267
268                 internal string ContainedInProjectFileName {
269                         get { return originalProject != null ? originalProject.FullFileName : project.FullFileName; }
270                 }
271         }
272 }
273
274 #endif