e81574d27879487030f093450c810ded1a3fb12b
[mono.git] / mcs / tools / xbuild / Main.cs
1 //
2 // Main.cs: Main program file of command line utility.
3 //
4 // Author:
5 //   Marek Sieradzki (marek.sieradzki@gmail.com)
6 //   Miguel de Icaza (miguel@ximian.com)
7 //   Marek Safar (marek.safar@seznam.cz)
8 //
9 // (C) 2005 Marek Sieradzki
10 // Copyright 2009 Novell, Inc (http://www.novell.com)
11 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 //
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 //
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31
32
33 using System;
34 using System.Collections;
35 using System.IO;
36 using System.Reflection;
37 using System.Text;
38 using Microsoft.Build.BuildEngine;
39 using Microsoft.Build.Framework;
40 using Microsoft.Build.Utilities;
41 using Mono.XBuild.Framework;
42
43 namespace Mono.XBuild.CommandLine {
44         public class MainClass {
45                 
46                 Parameters      parameters;
47                 string[]        args;
48                 string          defaultSchema;
49                 
50                 Engine          engine;
51                 Project         project;
52                 ConsoleReportPrinter printer;
53                 
54 #pragma warning disable 169
55                 // this does nothing but adds strong reference to Microsoft.Build.Tasks*.dll that we need to load consistently.
56                 Microsoft.Build.Tasks.Copy dummy;
57 #pragma warning restore
58                 public static void Main (string[] args)
59                 {
60                         MainClass mc = new MainClass ();
61                         mc.args = args;
62                         mc.Execute ();
63                 }
64                 
65                 public MainClass ()
66                 {
67                         string binPath = ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20);
68                         defaultSchema = Path.Combine (binPath, "Microsoft.Build.xsd");
69                         parameters = new Parameters ();
70                 }
71
72                 public void Execute ()
73                 {
74                         bool result = false;
75                         bool show_stacktrace = false;
76                         
77                         try {
78                                 try {
79                                         parameters.ParseArguments (args);
80                                 } catch {
81                                         ShowDeprecationNotice ();
82                                         throw;
83                                 }
84
85                                 ShowDeprecationNotice ();
86                                 show_stacktrace = (parameters.LoggerVerbosity == LoggerVerbosity.Detailed ||
87                                         parameters.LoggerVerbosity == LoggerVerbosity.Diagnostic);
88                                 
89                                 if (!parameters.NoLogo)
90                                         ErrorUtilities.ShowVersion (false);
91                                 
92                                 engine  = Engine.GlobalEngine;
93                                 if (!String.IsNullOrEmpty (parameters.ToolsVersion)) {
94                                         if (engine.Toolsets [parameters.ToolsVersion] == null)
95                                                 ErrorUtilities.ReportError (0, new UnknownToolsVersionException (parameters.ToolsVersion).Message);
96
97                                         engine.DefaultToolsVersion = parameters.ToolsVersion;
98                                 }
99                                 
100                                 engine.GlobalProperties = this.parameters.Properties;
101                                 
102                                 if (!parameters.NoConsoleLogger) {
103                                         printer = new ConsoleReportPrinter ();
104                                         ConsoleLogger cl = new ConsoleLogger (parameters.LoggerVerbosity,
105                                                         printer.Print, printer.SetForeground, printer.ResetColor);
106
107                                         cl.Parameters = parameters.ConsoleLoggerParameters;
108                                         cl.Verbosity = parameters.LoggerVerbosity; 
109                                         engine.RegisterLogger (cl);
110                                 }
111
112                                 if (parameters.FileLoggerParameters != null) {
113                                         for (int i = 0; i < parameters.FileLoggerParameters.Length; i ++) {
114                                                 string fl_params = parameters.FileLoggerParameters [i];
115                                                 if (fl_params == null)
116                                                         continue;
117
118                                                 var fl = new FileLogger ();
119                                                 if (fl_params.Length == 0 && i > 0)
120                                                         fl.Parameters = String.Format ("LogFile=msbuild{0}.log", i);
121                                                 else
122                                                         fl.Parameters = fl_params;
123                                                 engine.RegisterLogger (fl);
124                                         }
125                                 }
126                                 
127                                 foreach (LoggerInfo li in parameters.Loggers) {
128                                         Assembly assembly;
129                                         if (li.InfoType == LoadInfoType.AssemblyFilename)
130                                                 assembly = Assembly.LoadFrom (li.Filename);
131                                         else
132                                                 assembly = Assembly.Load (li.AssemblyName);
133                                         ILogger logger = (ILogger)Activator.CreateInstance (assembly.GetType (li.ClassName));
134                                         logger.Parameters = li.Parameters;
135                                         engine.RegisterLogger (logger); 
136                                 }
137                                 
138                                 project = engine.CreateNewProject ();
139                                 
140                                 if (parameters.Validate) {
141                                         if (parameters.ValidationSchema == null)
142                                                 project.SchemaFile = defaultSchema;
143                                         else
144                                                 project.SchemaFile = parameters.ValidationSchema;
145                                 }
146
147                                 string projectFile = parameters.ProjectFile;
148                                 if (!File.Exists (projectFile)) {
149                                         ErrorUtilities.ReportError (0, String.Format ("Project file '{0}' not found.", projectFile));
150                                         return;
151                                 }
152
153                                 result = engine.BuildProjectFile (projectFile, parameters.Targets, null, null, BuildSettings.None, parameters.ToolsVersion);
154                         }
155                         
156                         catch (InvalidProjectFileException ipfe) {
157                                 ErrorUtilities.ReportError (0, show_stacktrace ? ipfe.ToString () : ipfe.Message);
158                         }
159
160                         catch (InternalLoggerException ile) {
161                                 ErrorUtilities.ReportError (0, show_stacktrace ? ile.ToString () : ile.Message);
162                         }
163
164                         catch (CommandLineException cle) {
165                                 ErrorUtilities.ReportError(cle.ErrorCode, show_stacktrace ? cle.ToString() : cle.Message);
166                         }
167                         finally {
168                                 if (engine != null)
169                                         engine.UnregisterAllLoggers ();
170
171                                 Environment.Exit (result ? 0 : 1);
172                         }
173
174                 }
175
176                 void ShowDeprecationNotice ()
177                 {
178                         if (parameters.LoggerVerbosity != LoggerVerbosity.Minimal && parameters.LoggerVerbosity != LoggerVerbosity.Quiet) {
179                                 Console.ForegroundColor = ConsoleColor.DarkRed;
180                                 Console.WriteLine ();
181                                 Console.WriteLine (">>>> xbuild tool is deprecated and will be removed in future updates, use msbuild instead <<<<");
182                                 Console.WriteLine ();
183                                 Console.ResetColor ();
184                         }
185                 }
186         }
187
188         // code from mcs/report.cs
189         class ConsoleReportPrinter
190         {
191                 string prefix, postfix;
192                 bool color_supported;
193                 TextWriter writer;
194                 string [] colorPrefixes;
195
196                 public ConsoleReportPrinter ()
197                         : this (Console.Out)
198                 {
199                 }
200
201                 public ConsoleReportPrinter (TextWriter writer)
202                 {
203                         this.writer = writer;
204
205                         string term = Environment.GetEnvironmentVariable ("TERM");
206                         bool xterm_colors = false;
207
208                         color_supported = false;
209                         switch (term){
210                         case "xterm":
211                         case "rxvt":
212                         case "rxvt-unicode":
213                                 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
214                                         xterm_colors = true;
215                                 }
216                                 break;
217
218                         case "xterm-color":
219                         case "xterm-256color":
220                                 xterm_colors = true;
221                                 break;
222                         }
223                         if (!xterm_colors)
224                                 return;
225
226                         if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
227                                 return;
228
229                         color_supported = true;
230                         PopulateColorPrefixes ();
231                         postfix = "\x001b[0m";
232                 }
233
234                 void PopulateColorPrefixes ()
235                 {
236                         colorPrefixes = new string [16];
237
238                         colorPrefixes [(int)ConsoleColor.Black] = GetForeground ("black");
239                         colorPrefixes [(int)ConsoleColor.DarkBlue] = GetForeground ("blue");
240                         colorPrefixes [(int)ConsoleColor.DarkGreen] = GetForeground ("green");
241                         colorPrefixes [(int)ConsoleColor.DarkCyan] = GetForeground ("cyan");
242                         colorPrefixes [(int)ConsoleColor.DarkRed] = GetForeground ("red");
243                         colorPrefixes [(int)ConsoleColor.DarkMagenta] = GetForeground ("magenta");
244                         colorPrefixes [(int)ConsoleColor.DarkYellow] = GetForeground ("yellow");
245                         colorPrefixes [(int)ConsoleColor.DarkGray] = GetForeground ("grey");
246
247                         colorPrefixes [(int)ConsoleColor.Gray] = GetForeground ("brightgrey");
248                         colorPrefixes [(int)ConsoleColor.Blue] = GetForeground ("brightblue");
249                         colorPrefixes [(int)ConsoleColor.Green] = GetForeground ("brightgreen");
250                         colorPrefixes [(int)ConsoleColor.Cyan] = GetForeground ("brightcyan");
251                         colorPrefixes [(int)ConsoleColor.Red] = GetForeground ("brightred");
252                         colorPrefixes [(int)ConsoleColor.Magenta] = GetForeground ("brightmagenta");
253                         colorPrefixes [(int)ConsoleColor.Yellow] = GetForeground ("brightyellow");
254
255                         colorPrefixes [(int)ConsoleColor.White] = GetForeground ("brightwhite");
256                 }
257
258                 public void SetForeground (ConsoleColor color)
259                 {
260                         if (color_supported)
261                                 prefix = colorPrefixes [(int)color];
262                 }
263
264                 public void ResetColor ()
265                 {
266                         prefix = "\x001b[0m";
267                 }
268
269                 static int NameToCode (string s)
270                 {
271                         switch (s) {
272                         case "black":
273                                 return 0;
274                         case "red":
275                                 return 1;
276                         case "green":
277                                 return 2;
278                         case "yellow":
279                                 return 3;
280                         case "blue":
281                                 return 4;
282                         case "magenta":
283                                 return 5;
284                         case "cyan":
285                                 return 6;
286                         case "grey":
287                         case "white":
288                                 return 7;
289                         }
290                         return 7;
291                 }
292
293                 //
294                 // maps a color name to its xterm color code
295                 //
296                 static string GetForeground (string s)
297                 {
298                         string highcode;
299
300                         if (s.StartsWith ("bright")) {
301                                 highcode = "1;";
302                                 s = s.Substring (6);
303                         } else
304                                 highcode = "";
305
306                         return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
307                 }
308
309                 static string GetBackground (string s)
310                 {
311                         return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
312                 }
313
314                 string FormatText (string txt)
315                 {
316                         if (prefix != null && color_supported)
317                                 return prefix + txt + postfix;
318
319                         return txt;
320                 }
321
322                 public void Print (string message)
323                 {
324                         writer.WriteLine (FormatText (message));
325                 }
326
327         }
328
329         class UnixUtils {
330                 [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
331                 extern static int _isatty (int fd);
332
333                 public static bool isatty (int fd)
334                 {
335                         try {
336                                 return _isatty (fd) == 1;
337                         } catch {
338                                 return false;
339                         }
340                 }
341         }
342
343 }
344