merge -r 61110:61111
[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 //
7 // (C) 2005 Marek Sieradzki
8 //
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:
16 //
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 //
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.
27
28 #if NET_2_0
29
30 using System;
31 using System.Collections;
32 using System.IO;
33 using System.Reflection;
34 using Microsoft.Build.BuildEngine;
35 using Microsoft.Build.Framework;
36 using Microsoft.Build.Utilities;
37 using Mono.XBuild.Framework;
38 using Mono.XBuild.Utilities;
39
40 namespace Mono.XBuild.CommandLine {
41         public class MainClass {
42                 
43                 Parameters      parameters;
44                 string[]        args;
45                 string          binPath;
46                 string          defaultSchema;
47                 
48                 Engine          engine;
49                 Project         project;
50                 
51                 public static void Main (string[] args)
52                 {
53                         MainClass mc = new MainClass ();
54                         mc.args = args;
55                         mc.Execute ();
56                 }
57                 
58                 public MainClass ()
59                 {
60                         binPath = MonoLocationHelper.GetXBuildDir ();
61                         defaultSchema = Path.Combine (binPath, "Microsoft.Build.xsd");
62                         parameters = new Parameters (binPath);
63                 }
64                 
65                 public void Execute ()
66                 {
67                         bool result = false;
68                         
69                         try {
70                                 parameters.ParseArguments (args);
71                                 
72                                 if (parameters.DisplayVersion == true)
73                                         Display (version);
74                                 
75                                 engine  = new Engine (binPath);
76                                 
77                                 engine.GlobalProperties = this.parameters.Properties;
78                                 
79                                 if (parameters.NoConsoleLogger == false ) {
80                                         ConsoleLogger cl = new ConsoleLogger ();
81                                         cl.Parameters = parameters.ConsoleLoggerParameters;
82                                         cl.Verbosity = parameters.LoggerVerbosity; 
83                                         engine.RegisterLogger (cl);
84                                 }
85                                 
86                                 foreach (LoggerInfo li in parameters.Loggers) {
87                                         Assembly assembly;
88                                         if (li.InfoType == LoadInfoType.AssemblyFilename)
89                                                 assembly = Assembly.LoadFrom (li.Filename);
90                                         else
91                                                 assembly = Assembly.Load (li.AssemblyName);
92                                         ILogger logger = (ILogger)Activator.CreateInstance (assembly.GetType (li.ClassName));
93                                         logger.Parameters = li.Parameters;
94                                         engine.RegisterLogger (logger); 
95                                 }
96                                 
97                                 project = engine.CreateNewProject ();
98                                 
99                                 if (parameters.Validate == true) {
100                                         if (parameters.ValidationSchema == null)
101                                                 project.SchemaFile = defaultSchema;
102                                         else
103                                                 project.SchemaFile = parameters.ValidationSchema;
104                                 }
105
106                                 project.Load (parameters.ProjectFile);
107                                 
108                                 result = engine.BuildProject (project, parameters.Targets, new Hashtable ());
109                         }
110                         catch (CommandLineException cex) {
111                                 switch (cex.ErrorCode) {
112                                 case 1:
113                                         ReportErrorFromException (cex);
114                                         break;
115                                 case 2:
116                                         ReportErrorFromException (cex);
117                                         break;
118                                 case 3:
119                                         if (parameters.NoLogo)
120                                                 ReportErrorFromException (cex);
121                                         else {
122                                                 Display (version);
123                                                 Display (usage);
124                                         }
125                                         break;
126                                 case 4:
127                                         ReportErrorFromException (cex);
128                                         break;
129                                 case 5:
130                                         Version ();
131                                         break;
132                                 case 6:
133                                         Usage ();
134                                         break;
135                                 case 7:
136                                         ReportErrorFromException (cex);
137                                         break;
138                                 default:
139                                         throw;
140                                 }
141                         }
142                         catch (InvalidProjectFileException ipfe ) {
143                                 ReportError (0008, ipfe.Message);
144                         }
145                         catch (Exception ex) {
146                                 ReportError (0, String.Format ("{0}\n{1}",ex.Message, ex.StackTrace));
147                         }
148                         finally {
149                                 if (engine != null)
150                                         engine.UnregisterAllLoggers ();
151
152                                 Environment.Exit ((result ? 0 : 1));
153                         }
154
155                 }
156                 
157                 private void Display (string[] array) {
158                         foreach (string s in array)
159                                 Console.WriteLine (s);
160                 }
161                 
162                 private void Version ()
163                 {
164                         Display (version);
165                         Environment.Exit (0);
166                 }
167                 
168                 private void Usage ()
169                 {
170                         Display (version);
171                         Display (usage);
172                         Environment.Exit (0);
173                 }
174                 
175                 private void ReportErrorFromException (CommandLineException cex)
176                 {
177                         ReportError (cex.ErrorCode, cex.Message);
178                 }
179                 
180                 private void ReportError (int errorNum, string msg) {
181                         Console.WriteLine (String.Format ("MSBUILD: error MSBUILD{0:0000}: {1}", errorNum, msg));
182                         Environment.Exit (1);
183                 }
184
185                 private void ReportWarning (int errorNum, string msg) {
186                         Console.WriteLine (String.Format ("MSBUILD: warning MSBUILD{0:0000}: {1}", errorNum, msg));
187                 }
188
189                 private void ReportInvalidArgument (string option, string value) {
190                         ReportError (1012, String.Format ("'{0}' is not a valid setting for option '{1}'", value, option));
191                 }
192
193                 private void ReportMissingArgument (string option) {
194                         ReportError (1003, String.Format ("Compiler option '{0}' must be followed by an argument", option));
195                 }
196
197                 private void ReportNotImplemented (string option) {
198                         ReportError (0, String.Format ("Compiler option '{0}' is not implemented", option));
199                 }
200
201                 private void ReportMissingFileSpec (string option) {
202                         ReportError (1008, String.Format ("Missing file specification for '{0}' command-line option", option));
203                 }
204
205                 private void ReportMissingText (string option) {
206                         ReportError (1010, String.Format ("Missing ':<text>' for '{0}' option", option));
207                 }
208
209                 string[] usage = {
210                         "",
211                         "Syntax:              xbuild.exe [options] [project file]",
212                         "",
213                         "Description:         Builds the specified targets in the project file. If",
214                         "                     a project file is not specified, MSBuild searches the",
215                         "                     current working directory for a file that has a file",
216                         "                     extension that ends in \"proj\" and uses that file.",
217                         "",
218                         "Switches:",
219                         "",
220                         "  /help              Display this usage message. (Short form: /? or /h)",
221                         "",
222                         "  /nologo            Do not display the startup banner and copyright message.",
223                         "",
224                         "  /version           Display version information only. (Short form: /ver)",
225                         "",
226                         "  @<file>            Insert command-line settings from a text file. To specify",
227                         "                     multiple response files, specify each response file",
228                         "                     separately.",
229                         "",
230                         "  /noautoresponse    Do not auto-include the MSBuild.rsp file. (Short form:",
231                         "                     /noautorsp)",
232                         "",
233                         "  /target:<targets>  Build these targets in this project. Use a semicolon or a",
234                         "                     comma to separate multiple targets, or specify each",
235                         "                     target separately. (Short form: /t)",
236                         "                     Example:",
237                         "                       /target:Resources;Compile",
238                         "",
239                         "  /property:<n>=<v>  Set or override these project-level properties. <n> is",
240                         "                     the property name, and <v> is the property value. Use a",
241                         "                     semicolon or a comma to separate multiple properties, or",
242                         "                     specify each property separately. (Short form: /p)",
243                         "                     Example:",
244                         @"                       /property:WarningLevel=2;OutDir=bin\Debug\",
245                         "",
246                         "  /logger:<logger>   Use this logger to log events from MSBuild. To specify",
247                         "                     multiple loggers, specify each logger separately.",
248                         "                     The <logger> syntax is:",
249                         "                        [<logger class>,]<logger assembly>[;<logger parameters>]",
250                         "                     The <logger class> syntax is:",
251                         "                        [<partial or full namespace>.]<logger class name>",
252                         "                     The <logger assembly> syntax is:",
253                         "                        {<assembly name>[,<strong name>] | <assembly file>}",
254                         "                     The <logger parameters> are optional, and are passed",
255                         "                     to the logger exactly as you typed them. (Short form: /l)",
256                         "                     Examples:",
257                         "                       /logger:XMLLogger,MyLogger,Version=1.0.2,Culture=neutral",
258                         @"                       /logger:XMLLogger,C:\Loggers\MyLogger.dll;OutputAsHTML",
259                         "",
260                         "  /verbosity:<level> Display this amount of information in the event log.",
261                         "                     The available verbosity levels are: q[uiet], m[inimal],",
262                         "                     n[ormal], d[etailed], and diag[nostic]. (Short form: /v)",
263                         "                     Example:",
264                         "                       /verbosity:quiet",
265                         "",
266                         "  /consoleloggerparameters:<parameters>",
267                         "                     Parameters to console logger. (Short form: /clp)",
268                         "                     The available parameters are:",
269                         "                        PerformanceSummary--show time spent in tasks, targets",
270                         "                            and projects.",
271                         "                        NoSummary--don't show error and warning summary at the",
272                         "                            end.",
273                         "                     Example:",
274                         "                        /consoleloggerparameters:PerformanceSummary;NoSummary",
275                         "",
276                         "  /noconsolelogger   Disable the default console logger and do not log events",
277                         "                     to the console. (Short form: /noconlog)",
278                         "",
279                         "  /validate          Validate the project against the default schema. (Short",
280                         "                     form: /val)",
281                         "",
282                         "  /validate:<schema> Validate the project against the specified schema. (Short",
283                         "                     form: /val)",
284                         "                     Example:",
285                         "                       /validate:MyExtendedBuildSchema.xsd",
286                         "",
287                         "Examples:",
288                         "",
289                         "        MSBuild MyApp.sln /t:Rebuild /p:Configuration=Release",
290                         "        MSBuild MyApp.csproj /t:Clean /p:Configuration=Debug",
291                 };
292                 
293                 string[] version = {
294                         "XBuild Engine Version 0.1",
295                         String.Format ("Mono, Version {0}", Consts.MonoVersion),
296                         "Copyright (C) Marek Sieradzki 2005. All rights reserved.",
297                 };
298         }
299 }
300
301 #endif