Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MakefileProjectServiceExtension.cs « MonoDevelop.Autotools « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1ca531fbaa9933858a2d7281decb442bb733c9e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//
// MakefileProjectServiceExtension.cs
//
// Author:
//   Ankit Jain <jankit@novell.com>
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core.ProgressMonitoring;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Projects;

using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.Threading.Tasks;

namespace MonoDevelop.Autotools
{
	public class MakefileProjectServiceExtension : ProjectServiceExtension
	{
		public async override Task<WorkspaceItem> LoadWorkspaceItem (ProgressMonitor monitor, string fileName)
		{
			WorkspaceItem item = await base.LoadWorkspaceItem (monitor, fileName);

			Solution sol = item as Solution;
			if (sol != null) {
				//Resolve project references
				try {
					MakefileData.ResolveProjectReferences (sol.RootFolder, monitor);
				} catch (Exception e) {
					LoggingService.LogError (GettextCatalog.GetString (
						"Error resolving Makefile based project references for solution {0}", sol.Name), e);
					monitor.ReportError (GettextCatalog.GetString (
						"Error resolving Makefile based project references for solution {0}", sol.Name), e);
				}
			}

			return item;
		}
	}

	[RegisterProjectModelExtension]
	public class MakefileProjectExtension: ProjectExtension
	{
		MakefileData data;

		protected override void OnReadProject (ProgressMonitor monitor, MonoDevelop.Projects.Formats.MSBuild.MSBuildProject msproject)
		{
			base.OnReadProject (monitor, msproject);
			var ext = msproject.GetMonoDevelopProjectExtension ("MonoDevelop.Autotools.MakefileInfo");
			if (ext == null)
				return;

			data = MakefileData.Read (ext);
			if (data == null)
				return;

			monitor.BeginTask (GettextCatalog.GetString ("Updating project from Makefile"), 1);
			try { 
				data.OwnerProject = Project;
				if (data.SupportsIntegration)
					data.UpdateProject (monitor, false);
				monitor.Step (1);
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString (
					"\tError loading Makefile for project {0}", Project.Name), e);
			} finally {
				monitor.EndTask ();
			}
		}

		protected override void OnWriteProject (ProgressMonitor monitor, MonoDevelop.Projects.Formats.MSBuild.MSBuildProject msproject)
		{
			base.OnWriteProject (monitor, msproject);

			if (data == null || !data.SupportsIntegration)
				return;

			msproject.SetProjectExtension ("MonoDevelop.Autotools.MakefileInfo", data.Write ());

			try {
				data.UpdateMakefile (monitor);
			} catch (Exception e) {
				LoggingService.LogError (GettextCatalog.GetString ("Error saving to Makefile ({0}) for project {1}",
					data.AbsoluteMakefileName, Project.Name, e));
				monitor.ReportError (GettextCatalog.GetString (
					"Error saving to Makefile ({0}) for project {1}", data.AbsoluteMakefileName, Project.Name), e);
			}
		}

		protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles)
		{
			List<FilePath> col = base.OnGetItemFiles (includeReferencedFiles).ToList ();
			
			MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
			if (data == null || !data.SupportsIntegration || string.IsNullOrEmpty (data.AbsoluteMakefileName))
				return col;
			
			col.Add (data.AbsoluteMakefileName);
			if (!string.IsNullOrEmpty (data.RelativeConfigureInPath)) {
				string file = Path.Combine (data.AbsoluteConfigureInPath, "configure.in");
				if (!File.Exists (file))
					file = Path.Combine (data.AbsoluteConfigureInPath, "configure.ac");
				if (File.Exists (file))
					col.Add (file);
			}
			return col;
		}


		//FIXME: Check whether autogen.sh is required or not
		protected async override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration)
		{
			MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
			if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.BuildTargetName))
				return await base.OnBuild (monitor, configuration);

			//FIXME: Gen autofoo ? autoreconf?

			string output = String.Empty;
			int exitCode = 0;
			monitor.BeginTask (GettextCatalog.GetString ("Building {0}", Project.Name), 1);
			try
			{
				string baseDir = Project.BaseDirectory;
				string args = string.Format ("-j {0} {1}", data.ParallelProcesses, data.BuildTargetName);
	
				using (var swOutput = new StringWriter ()) {
					using (var chainedOutput = new LogTextWriter ()) {
						chainedOutput.ChainWriter (monitor.Log);
						chainedOutput.ChainWriter (swOutput);

						using (ProcessWrapper process = Runtime.ProcessService.StartProcess ("make",
								args,
								baseDir, 
								chainedOutput, 
								chainedOutput,
							null)) {

							await process.Task;

							chainedOutput.UnchainWriter (monitor.Log);
							chainedOutput.UnchainWriter (swOutput);

							exitCode = process.ExitCode;
							output = swOutput.ToString ();
							monitor.Step ( 1 );
						}
					}
				}
			}
			catch ( Exception e )
			{
				monitor.ReportError ( GettextCatalog.GetString ("Project could not be built: "), e );
				return null;
			}
			finally 
			{
				monitor.EndTask ();
			}

			TempFileCollection tf = new TempFileCollection ();
			Regex regexError = data.GetErrorRegex (false);
			Regex regexWarning = data.GetWarningRegex (false);

			BuildResult cr = ParseOutput (tf, output, Project.BaseDirectory, regexError, regexWarning);
			if (exitCode != 0 && cr.FailedBuildCount == 0)
				cr.AddError (GettextCatalog.GetString ("Build failed. See Build Output panel."));

			return cr;
		}

		BuildResult ParseOutput (TempFileCollection tf, string output, string baseDir, Regex regexError, Regex regexWarning)
		{
			StringBuilder compilerOutput = new StringBuilder();

			CompilerResults cr = new CompilerResults(tf);
			
			// we have 2 formats for the error output the csc gives :
			//Regex normalError  = new Regex(@"(?<file>.*)\((?<line>\d+),(?<column>\d+)\):\s+(?<error>\w+)\s+(?<number>[\d\w]+):\s+(?<message>.*)", RegexOptions.Compiled);
			//Regex generalError = new Regex(@"(?<error>.+)\s+(?<number>[\d\w]+):\s+(?<message>.*)", RegexOptions.Compiled);
			
			Stack<string> dirs = new Stack<string> ();
			dirs.Push (baseDir);
			StringReader sr = new StringReader (output);
			while (true) {

				string curLine = sr.ReadLine();
				compilerOutput.Append(curLine);
				compilerOutput.Append('\n');
				if (curLine == null) {
					break;
				}
				curLine = curLine.Trim();
				if (curLine.Length == 0) {
					continue;
				}
			
				CompilerError error = null;
				
				if (regexError != null) {
					error = CreateCompilerErrorFromString (curLine, dirs, regexError);

					if (error != null)
						cr.Errors.Add (error);
				}

				if (regexWarning != null) {
					error = CreateCompilerErrorFromString (curLine, dirs, regexWarning);
					if (error != null) {
						cr.Errors.Add (error);
						error.IsWarning = true;
					}
				}
			}
			sr.Close();

			return new BuildResult(cr, compilerOutput.ToString());
		}

		// Snatched from our codedom code :-).
		//FIXME: Get this from the language binding.. if a known lang

		static Regex regexEnterDir = new Regex (@"make\[[0-9]*\]: ([a-zA-Z]*) directory `(.*)'");
		
		private static CompilerError CreateCompilerErrorFromString (string error_string, Stack<string> dirs, Regex regex)
		{
			// When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
			// FIXME: This should be generic
			if (error_string.StartsWith ("WROTE SYMFILE") ||
			    error_string.StartsWith ("OffsetTable") ||
			    error_string.StartsWith ("Compilation succeeded") ||
			    error_string.StartsWith ("Compilation failed"))
				return null;

			CompilerError error = new CompilerError();

			Match match = regexEnterDir.Match (error_string);
			if (match.Success) {
				//FIXME: Not always available, make -w is required or how?
				//what to use then?
				if (match.Groups [1].Value == "Entering")
					dirs.Push (match.Groups [2].Value);
				else if (match.Groups [1].Value == "Leaving")
					dirs.Pop ();

				return null;
			}

			if (error_string.StartsWith ("make"))
				return null;

			match = regex.Match (error_string);
			if (!match.Success)
				return null;

			string str = GetValue (match, "${file}");
			if (str != null) {
				error.FileName = str;
				if (! Path.IsPathRooted (error.FileName) && dirs.Count > 0)
					error.FileName = Path.Combine (dirs.Peek (), error.FileName);
			}

			str = GetValue (match, "${line}");
			if (str != null)
				error.Line = Int32.Parse (str);

			str = GetValue (match, "${column}");
			if (str != null) {
				if (str == "255+")
					error.Column = -1;
				else
					error.Column = Int32.Parse (str);
			}

			str = GetValue (match, "${number}");
			if (str != null)
				error.ErrorNumber = match.Result("${number}");

			str = GetValue (match, "${message}");
			if (str != null)
				error.ErrorText = match.Result("${message}");

			return error;
		}

		static string GetValue (Match match, string var)
		{
			string str = match.Result (var);
			if (str != var && !String.IsNullOrEmpty (str))
				return str;
			else
				return null;
		}

		protected async override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration)
		{
			MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
			if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.CleanTargetName)) {
				return await base.OnClean (monitor, configuration); 
			}

			monitor.BeginTask ( GettextCatalog.GetString( "Cleaning project"), 1);
			try
			{
				string baseDir = Project.BaseDirectory;
	
				ProcessWrapper process = Runtime.ProcessService.StartProcess ( "make", 
						data.CleanTargetName,
						baseDir, 
						monitor.Log, 
						monitor.Log, 
						null );

				await process.Task;

				if ( process.ExitCode > 0 )
					throw new Exception ( GettextCatalog.GetString ("An unspecified error occurred while running '{0}'", "make " + data.CleanTargetName) );

				monitor.Step ( 1 );
			}
			catch ( Exception e )
			{
				monitor.ReportError ( GettextCatalog.GetString ("Project could not be cleaned: "), e );
				var res = new BuildResult ();
				res.AddError (GettextCatalog.GetString ("Project could not be cleaned: ") + e.Message);
				return res;
			}
			finally 
			{
				monitor.EndTask ();
			}
			monitor.ReportSuccess ( GettextCatalog.GetString ( "Project successfully cleaned"));
			return BuildResult.Success;
		}

		protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration)
		{
			MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
			if (data != null && data.SupportsIntegration && !String.IsNullOrEmpty (data.ExecuteTargetName))
				return true;
			return base.OnGetCanExecute (context, configuration);
		}


		protected async override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
		{
			MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
			if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.ExecuteTargetName)) {
				base.OnExecute (monitor, context, configuration);
				return;
			}

			IConsole console = context.ConsoleFactory.CreateConsole (true);
			monitor.BeginTask (GettextCatalog.GetString ("Executing {0}", Project.Name), 1);
			try
			{
				ProcessWrapper process = Runtime.ProcessService.StartProcess ("make",
					data.ExecuteTargetName,
					Project.BaseDirectory,
					console.Out,
					console.Error,
					null);

				await process.Task;

				monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", process.ExitCode));
				monitor.Step (1);
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Project could not be executed: "), e);
				return;
			} finally {
				monitor.EndTask ();
				console.Dispose ();
			}
		}

	}
}