[xbuild] Implement FileLogger . Fix #676650 .
[mono.git] / mcs / tools / xbuild / Parameters.cs
1 //
2 // Parameters.cs: Class that contains information about command line parameters
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.IO;
32 using System.Collections;
33 using System.Collections.Generic;
34 using System.Linq;
35 using System.Text;
36 using System.Reflection;
37 using Microsoft.Build.BuildEngine;
38 using Microsoft.Build.Framework;
39 using Microsoft.Build.Utilities;
40
41 namespace Mono.XBuild.CommandLine {
42         public class Parameters {
43         
44                 string                  consoleLoggerParameters;
45                 bool                    displayHelp;
46                 IList                   flatArguments;
47                 IList                   loggers;
48                 LoggerVerbosity         loggerVerbosity;
49                 bool                    noConsoleLogger;
50                 bool                    noLogo;
51                 string                  projectFile;
52                 BuildPropertyGroup      properties;
53                 IList                   remainingArguments;
54                 Hashtable               responseFiles;
55                 string[]                targets;
56                 bool                    validate;
57                 string                  validationSchema;
58                 string                  toolsVersion;
59                 
60                 string                  responseFile;
61         
62                 public Parameters ()
63                 {
64                         consoleLoggerParameters = "";
65                         displayHelp = false;
66                         loggers = new ArrayList ();
67                         loggerVerbosity = LoggerVerbosity.Normal;
68                         noConsoleLogger = false;
69                         noLogo = false;
70                         properties = new BuildPropertyGroup ();
71                         targets = new string [0];
72                         
73                         responseFile = Path.Combine (
74                                         Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location),
75                                         "xbuild.rsp");
76                 }
77                 
78                 public void ParseArguments (string[] args)
79                 {
80                         bool autoResponse = true;
81                         flatArguments = new ArrayList ();
82                         remainingArguments = new ArrayList ();
83                         responseFiles = new Hashtable ();
84                         FileLoggerParameters = new string[10];
85                         foreach (string s in args) {
86                                 if (s.StartsWith ("/noautoresponse") || s.StartsWith ("/noautorsp")) {
87                                         autoResponse = false;
88                                         continue;
89                                 }
90                                 if (s [0] != '@') {
91                                         flatArguments.Add (s);
92                                         continue;
93                                 }
94                                 string responseFilename = Path.GetFullPath (UnquoteIfNeeded (s.Substring (1)));
95                                 if (responseFiles.ContainsKey (responseFilename))
96                                         ReportError (1, String.Format ("We already have {0} file.", responseFilename));
97                                 responseFiles [responseFilename] = responseFilename;
98                                 LoadResponseFile (responseFilename);
99                         }
100                         if (autoResponse == true) {
101                                 // FIXME: we do not allow nested auto response file
102                                 LoadResponseFile (responseFile);
103                         }
104                         foreach (string s in flatArguments) {
105                                 if (s [0] != '/' || !ParseFlatArgument (s))
106                                         remainingArguments.Add (s);
107                         }
108                         if (remainingArguments.Count == 0) {
109                                 string[] sln_files = Directory.GetFiles (Directory.GetCurrentDirectory (), "*.sln");
110                                 string[] proj_files = Directory.GetFiles (Directory.GetCurrentDirectory (), "*proj");
111
112                                 if (sln_files.Length == 0 && proj_files.Length == 0)
113                                         ReportError (3, "Please specify the project or solution file " +
114                                                         "to build, as none was found in the current directory.");
115
116                                 if (sln_files.Length == 1 && proj_files.Length > 0) {
117                                         var projects_table = new Dictionary<string, string> ();
118                                         foreach (string pfile in SolutionParser.GetAllProjectFileNames (sln_files [0])) {
119                                                 string full_path = Path.GetFullPath (pfile);
120                                                 projects_table [full_path] = full_path;
121                                         }
122
123                                         if (!proj_files.Any (p => !projects_table.ContainsKey (Path.GetFullPath (p))))
124                                                 // if all the project files in the cur dir, are referenced
125                                                 // from the single .sln in the cur dir, then pick the sln
126                                                 proj_files = new string [0];
127                                 }
128
129                                 if (sln_files.Length + proj_files.Length > 1)
130                                         ReportError (5, "Please specify the project or solution file " +
131                                                         "to build, as more than one solution or project file was found " +
132                                                         "in the current directory");
133
134                                 if (sln_files.Length == 1)
135                                         projectFile = sln_files [0];
136                                 else
137                                         projectFile = proj_files [0];
138                         } else if (remainingArguments.Count == 1) {
139                                 projectFile = (string) remainingArguments [0];
140                         } else {
141                                 ReportError (4, "Too many project files specified");
142                         }
143                 }
144
145                 private string UnquoteIfNeeded(string arg)
146                 {
147                         if (arg.StartsWith("\""))
148                                 return arg.Substring(1, arg.Length - 2);
149                         return arg;
150                 }
151
152                 void LoadResponseFile (string filename)
153                 {
154                         StreamReader sr = null;
155                         string line;
156                         try {
157                                 sr = new StreamReader (filename);
158                                 StringBuilder sb = new StringBuilder ();
159
160                                 while ((line = sr.ReadLine ()) != null) {
161                                         int t = line.Length;
162
163                                         for (int i = 0; i < t; i++) {
164                                                 char c = line [i];
165
166                                                 if (c == '#')
167                                                         // comment, ignore rest of the line
168                                                         break;
169
170                                                 if (c == '"' || c == '\'') {
171                                                         char end = c;
172
173                                                         for (i++; i < t; i++) {
174                                                                 c = line [i];
175
176                                                                 if (c == end)
177                                                                         break;
178                                                                 sb.Append (c);
179                                                         }
180                                                 } else if (c == ' ') {
181                                                         if (sb.Length > 0) {
182                                                                 flatArguments.Add (sb.ToString ());
183                                                                 sb.Length = 0;
184                                                         }
185                                                 } else
186                                                         sb.Append (c);
187                                         }
188                                         if (sb.Length > 0){
189                                                 flatArguments.Add (sb.ToString ());
190                                                 sb.Length = 0;
191                                         }
192                                 }
193                         } catch (IOException x) {
194                                 ErrorUtilities.ReportWarning (2, String.Format (
195                                                         "Error loading response file. (Exception: {0}). Ignoring.",
196                                                         x.Message));
197                         } finally {
198                                 if (sr != null)
199                                         sr.Close ();
200                         }
201                 }
202                 
203                 private bool ParseFlatArgument (string s)
204                 {
205                         switch (s) {
206                         case "/help":
207                         case "/h":
208                         case "/?":
209                                 ErrorUtilities.ShowUsage ();
210                                 break;
211                         case "/nologo":
212                                 noLogo = true;
213                                 break;
214                         case "/version":
215                         case "/ver":
216                                 ErrorUtilities.ShowVersion (true);
217                                 break;
218                         case "/noconsolelogger":
219                         case "/noconlog":
220                                 noConsoleLogger = true;
221                                 break;
222                         case "/validate":
223                         case "/val":
224                                 validate = true;
225                                 break;
226                         case "/fl":
227                         case "/filelogger":
228                                 if (FileLoggerParameters [0] == null)
229                                         FileLoggerParameters [0] = String.Empty;
230                                 break;
231                         default:
232                                 if (s.StartsWith ("/fl") && s.Length == 4 && Char.IsDigit (s[3])) {
233                                         int index = Int32.Parse (s[3].ToString ());
234                                         if (FileLoggerParameters [index] == null)
235                                                 FileLoggerParameters [index] = String.Empty;
236                                 } else if (s.StartsWith ("/fileloggerparameters") || s.StartsWith ("/flp")) {
237                                         ProcessFileLoggerParameters (s);
238                                 } else if (s.StartsWith ("/target:") || s.StartsWith ("/t:")) {
239                                         ProcessTarget (s);
240                                 } else if (s.StartsWith ("/property:") || s.StartsWith ("/p:")) {
241                                         if (!ProcessProperty (s))
242                                                 return false;
243                                 } else  if (s.StartsWith ("/logger:") || s.StartsWith ("/l:")) {
244                                         ProcessLogger (s);
245                                 } else if (s.StartsWith ("/verbosity:") || s.StartsWith ("/v:")) {
246                                         ProcessVerbosity (s);
247                                 } else if (s.StartsWith ("/consoleloggerparameters:") || s.StartsWith ("/clp:")) {
248                                         ProcessConsoleLoggerParameters (s);
249                                 } else if (s.StartsWith ("/validate:") || s.StartsWith ("/val:")) {
250                                         ProcessValidate (s);
251                                 } else if (s.StartsWith ("/toolsversion:") || s.StartsWith ("/tv:")) {
252                                         ToolsVersion = s.Split (':') [1];
253                                 } else
254                                         return false;
255                                 break;
256                         }
257
258                         return true;
259                 }
260                 
261                 internal void ProcessTarget (string s)
262                 {
263                         TryProcessMultiOption (s, "Target names must be specified as /t:Target1;Target2",
264                                                 out targets);
265                 }
266                 
267                 internal bool ProcessProperty (string s)
268                 {
269                         string[] splitProperties;
270                         if (!TryProcessMultiOption (s, "Property name and value expected as /p:<prop name>=<prop value>",
271                                                 out splitProperties))
272                                 return false;
273
274                         foreach (string st in splitProperties) {
275                                 if (st.IndexOf ('=') < 0) {
276                                         ReportError (5,
277                                                         "Invalid syntax. Property name and value expected as " +
278                                                         "<prop name>=[<prop value>]");
279                                         return false;
280                                 }
281                                 string [] property = st.Split ('=');
282                                 properties.SetProperty (property [0], property.Length == 2 ? property [1] : "");
283                         }
284
285                         return true;
286                 }
287
288                 bool TryProcessMultiOption (string s, string error_message, out string[] values)
289                 {
290                         values = null;
291                         int colon = s.IndexOf (':');
292                         if (colon + 1 == s.Length) {
293                                 ReportError (5, error_message);
294                                 return false;
295                         }
296
297                         values = s.Substring (colon + 1).Split (';');
298                         return true;
299                 }
300
301                 private void ReportError (int errorCode, string message)
302                 {
303                         throw new CommandLineException (message, errorCode);
304                 }
305
306                 private void ReportError (int errorCode, string message, Exception cause)
307                 {
308                         throw new CommandLineException (message, cause, errorCode);
309                 }
310
311                 internal void ProcessLogger (string s)
312                 {
313                         loggers.Add (new LoggerInfo (s));
314                 }
315                 
316                 internal void ProcessVerbosity (string s)
317                 {
318                         string[] temp = s.Split (':');
319                         switch (temp [1]) {
320                         case "q":
321                         case "quiet":
322                                 loggerVerbosity = LoggerVerbosity.Quiet;
323                                 break;
324                         case "m":
325                         case "minimal":
326                                 loggerVerbosity = LoggerVerbosity.Minimal;
327                                 break;
328                         case "n":
329                         case "normal":
330                                 loggerVerbosity = LoggerVerbosity.Normal;
331                                 break;
332                         case "d":
333                         case "detailed":
334                                 loggerVerbosity = LoggerVerbosity.Detailed;
335                                 break;
336                         case "diag":
337                         case "diagnostic":
338                                 loggerVerbosity = LoggerVerbosity.Diagnostic;
339                                 break;
340                         }
341                 }
342
343                 void ProcessFileLoggerParameters (string s)
344                 {
345                         int colon = s.IndexOf (':');
346                         if (colon + 1 == s.Length)
347                                 ReportError (5, "Invalid syntax, specify parameters as /fileloggerparameters[n]:parameters");
348
349                         int index = 0;
350                         string key = s.Substring (0, colon);
351                         if (Char.IsDigit (key [key.Length - 1]))
352                         //if (key.Length == 22 && Char.IsDigit (key [21]))
353                                 index = Int32.Parse (key [key.Length - 1].ToString ());
354
355                         FileLoggerParameters [index] = s.Substring (colon + 1);
356                 }
357
358                 internal void ProcessConsoleLoggerParameters (string s)
359                 {
360                         int colon = s.IndexOf (':');
361                         if (colon + 1 == s.Length)
362                                 ReportError (5, "Invalid syntax, specify parameters as /clp:parameters");
363
364                         consoleLoggerParameters = s.Substring (colon + 1);
365                 }
366                 
367                 internal void ProcessValidate (string s)
368                 {
369                         string[] temp;
370                         validate = true;
371                         temp = s.Split (':');
372                         validationSchema = temp [1];
373                 }
374                 public bool DisplayHelp {
375                         get { return displayHelp; }
376                 }
377                 
378                 public bool NoLogo {
379                         get { return noLogo; }
380                 }
381                 
382                 public string ProjectFile {
383                         get { return projectFile; }
384                 }
385                 
386                 public string[] Targets {
387                         get { return targets; }
388                 }
389                 
390                 public BuildPropertyGroup Properties {
391                         get { return properties; }
392                 }
393                 
394                 public IList Loggers {
395                         get { return loggers; }
396                 }
397                 
398                 public LoggerVerbosity LoggerVerbosity {
399                         get { return loggerVerbosity; }
400                 }
401                 
402                 public string ConsoleLoggerParameters {
403                         get { return consoleLoggerParameters; }
404                 }
405                 
406                 public bool NoConsoleLogger {
407                         get { return noConsoleLogger; }
408                 }
409
410                 public string[] FileLoggerParameters { get; set; }
411                 
412                 public bool Validate {
413                         get { return validate; }
414                 }
415                 
416                 public string ValidationSchema {
417                         get { return validationSchema; }
418                 }
419
420                 public string ToolsVersion {
421                         get { return toolsVersion; }
422                         private set { toolsVersion = value; }
423                 }
424                 
425         }
426 }
427
428 #endif