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

CustomToolService.cs « MonoDevelop.Ide.CustomTools « MonoDevelop.Ide « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6c3e3a6d1ecc131ed8d86bbb15084e9e1ba0beaf (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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// 
// CustomToolService.cs
//  
// Author:
//       Michael Hutchinson <mhutchinson@novell.com>
// 
// Copyright (c) 2010 Novell, Inc.
// 
// 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 System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Mono.Addins;
using MonoDevelop.Core;
using MonoDevelop.Core.ProgressMonitoring;
using MonoDevelop.Ide.Extensions;
using MonoDevelop.Ide.Tasks;
using MonoDevelop.Projects;

namespace MonoDevelop.Ide.CustomTools
{
	public static class CustomToolService
	{
		static readonly Dictionary<string,CustomToolExtensionNode> nodes = new Dictionary<string,CustomToolExtensionNode> ();
		
		static readonly Dictionary<string,IAsyncOperation> runningTasks = new Dictionary<string, IAsyncOperation> ();
		
		static CustomToolService ()
		{
			AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Ide/CustomTools", delegate(object sender, ExtensionNodeEventArgs args) {
				var node = (CustomToolExtensionNode)args.ExtensionNode;
				switch (args.Change) {
				case ExtensionChange.Add:
					if (nodes.ContainsKey (node.Name))
						LoggingService.LogError ("Duplicate custom tool name '{0}'", node.Name);
					else
						nodes.Add (node.Name, node);
					break;
				case ExtensionChange.Remove:
					nodes.Remove (node.Name);
					break;
				}
			});
			IdeApp.Workspace.FileChangedInProject += delegate (object sender, ProjectFileEventArgs args) {
				foreach (ProjectFileEventInfo e in args)
					Update (e.ProjectFile, false);
			};
			IdeApp.Workspace.FilePropertyChangedInProject += delegate (object sender, ProjectFileEventArgs args) {
				foreach (ProjectFileEventInfo e in args)
					Update (e.ProjectFile, false);
			};
			//FIXME: handle the rename
			//MonoDevelop.Ide.Gui.IdeApp.Workspace.FileRenamedInProject
		}
		
		internal static void Init ()
		{
			//forces static ctor to run
		}
		
		static ISingleFileCustomTool GetGenerator (string name)
		{
			if (string.IsNullOrEmpty (name))
				return null;

			if (name.StartsWith ("msbuild:", StringComparison.OrdinalIgnoreCase)) {
				string target = name.Substring ("msbuild:".Length).Trim ();
				if (string.IsNullOrEmpty (target))
					return null;
				return new MSBuildCustomTool (target);
			}

			CustomToolExtensionNode node;
			if (nodes.TryGetValue (name, out node)) {
				try {
					return node.Tool;
				} catch (Exception ex) {
					LoggingService.LogError ("Error loading generator '" + name + "'", ex);
					nodes.Remove (name);
				}
			}
			return null;
		}

		public static void Update (IEnumerable<ProjectFile> files, bool force)
		{
			var monitor = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor (false);

			IEnumerator<ProjectFile> fileEnumerator;

			//begin root task
			monitor.BeginTask (GettextCatalog.GetString ("Generate templates"), 1);

			if (files == null || !(fileEnumerator = files.GetEnumerator ()).MoveNext ()) {
				monitor.EndTask ();
				monitor.ReportSuccess (GettextCatalog.GetString ("No templates found"));
				monitor.Dispose ();
			} else {
				Update (monitor, fileEnumerator, force, 0, 0, 0);
			}
		}

		static bool ShouldRunGenerator (ProjectFile file, bool force, out ISingleFileCustomTool tool, out ProjectFile genFile)
		{
			tool = null;
			genFile = null;

			//ignore cloned file from shared project in context of referencing project
			if ((file.Flags & ProjectItemFlags.DontPersist) != 0) {
				return false;
			}

			tool = GetGenerator (file.Generator);
			if (tool == null) {
				return false;
			}

			//ignore MSBuild tool for projects that aren't MSBuild or can't build
			//we could emit a warning but this would get very annoying for Xamarin Forms + SAP
			//in future we could consider running the MSBuild generator in context of every referencing project
			if (tool is MSBuildCustomTool) {
				if (!file.Project.SupportsBuild ()) {
					return false;
				}
				bool byDefault, require;
				MonoDevelop.Projects.Formats.MSBuild.MSBuildProjectService.CheckHandlerUsesMSBuildEngine (file.Project, out byDefault, out require);
				var usesMSBuild = require || (file.Project.UseMSBuildEngine ?? byDefault);
				if (!usesMSBuild) {
					return false;
				}
			}

			if (!string.IsNullOrEmpty (file.LastGenOutput)) {
				genFile = file.Project.Files.GetFile (file.FilePath.ParentDirectory.Combine (file.LastGenOutput));
			}

			return force
				|| genFile == null
				|| !File.Exists (genFile.FilePath)
				|| File.GetLastWriteTime (file.FilePath) > File.GetLastWriteTime (genFile.FilePath);
		}

		static void Update (IProgressMonitor monitor, IEnumerator<ProjectFile> fileEnumerator, bool force, int succeeded, int warnings, int errors)
		{
			ProjectFile file = fileEnumerator.Current;
			ISingleFileCustomTool tool;
			ProjectFile genFile;

			bool shouldRun;
			while (!(shouldRun = ShouldRunGenerator (file, force, out tool, out genFile)) && fileEnumerator.MoveNext ())
				continue;

			//no files which can be generated in remaining elements of the collection, nothing to do
			if (!shouldRun) {
				WriteSummaryResults (monitor, succeeded, warnings, errors);
				return;
			}

			TaskService.Errors.ClearByOwner (file);

			var result = new SingleFileCustomToolResult ();
			monitor.BeginTask (GettextCatalog.GetString ("Running generator '{0}' on file '{1}'...", file.Generator, file.Name), 1);

			try {
				IAsyncOperation op = tool.Generate (monitor, file, result);
				op.Completed += delegate {
					if (result.Success) {
						monitor.Log.WriteLine (GettextCatalog.GetString ("File '{0}' was generated successfully.", result.GeneratedFilePath));
						succeeded++;
					} else if (result.SuccessWithWarnings) {
						monitor.Log.WriteLine (GettextCatalog.GetString ("File '{0}' was generated with warnings.", result.GeneratedFilePath));
						warnings++;
					} else {
						monitor.Log.WriteLine (GettextCatalog.GetString ("Errors in file '{0}' generation.", result.GeneratedFilePath));
						errors++;
					}

					//check that we can process further. If UpdateCompleted returns `true` this means no errors or non-fatal errors occured
					if (UpdateCompleted (monitor, null, file, genFile, result, true) && fileEnumerator.MoveNext ())
						Update (monitor, fileEnumerator, force, succeeded, warnings, errors);
					else
						WriteSummaryResults (monitor, succeeded, warnings, errors);
				};
			} catch (Exception ex) {
				result.UnhandledException = ex;
				UpdateCompleted (monitor, null, file, genFile, result, true);
			}
		}

		static void WriteSummaryResults (IProgressMonitor monitor, int succeeded, int warnings, int errors)
		{
			monitor.Log.WriteLine ();

			int total = succeeded + warnings + errors;

			//this might not be correct for languages where pluralization affects the other arguments
			//but gettext doesn't really have an answer for sentences with multiple plurals
			monitor.Log.WriteLine (
				GettextCatalog.GetPluralString (
					"{0} file processed total. {1} generated successfully, {2} with warnings, {3} with errors",
					"{0} files processed total. {1} generated successfully, {2} with warnings, {3} with errors",
					total,
					total, succeeded, warnings, errors)
			);
			//ends the root task
			monitor.EndTask ();

			if (errors > 0)
				monitor.ReportError (GettextCatalog.GetString ("Errors in file generation."), null);
			else if (warnings > 0)
				monitor.ReportSuccess (GettextCatalog.GetString ("Warnings in file generation."));
			else
				monitor.ReportSuccess (GettextCatalog.GetString ("Generated files successfully."));

			monitor.Dispose ();
		}

		public static void Update (ProjectFile file, bool force)
		{
			ISingleFileCustomTool tool;
			ProjectFile genFile;
			if (!ShouldRunGenerator (file, force, out tool, out genFile)) {
				return;
			}
			
			TaskService.Errors.ClearByOwner (file);
			
			//if this file is already being run, cancel it
			lock (runningTasks) {
				IAsyncOperation runningTask;
				if (runningTasks.TryGetValue (file.FilePath, out runningTask)) {
					runningTask.Cancel ();
					runningTasks.Remove (file.FilePath);
				}
			}
			
			var monitor = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor (false);
			var result = new SingleFileCustomToolResult ();
			var aggOp = new AggregatedOperationMonitor (monitor);
			try {
				monitor.BeginTask (GettextCatalog.GetString ("Running generator '{0}' on file '{1}'...", file.Generator, file.Name), 1);
				IAsyncOperation op = tool.Generate (monitor, file, result);
				runningTasks.Add (file.FilePath, op);
				aggOp.AddOperation (op);
				op.Completed += delegate {
					lock (runningTasks) {
						IAsyncOperation runningTask;
						if (runningTasks.TryGetValue (file.FilePath, out runningTask) && runningTask == op) {
							runningTasks.Remove (file.FilePath);
							UpdateCompleted (monitor, aggOp, file, genFile, result, false);
						} else {
							//it was cancelled because another was run for the same file, so just clean up
							aggOp.Dispose ();
							monitor.EndTask ();
							monitor.ReportWarning (GettextCatalog.GetString ("Cancelled because generator ran again for the same file"));
							monitor.Dispose ();
						}
					}
				};
			} catch (Exception ex) {
				result.UnhandledException = ex;
				UpdateCompleted (monitor, aggOp, file, genFile, result, false);
			}
		}
		
		static bool UpdateCompleted (IProgressMonitor monitor, AggregatedOperationMonitor aggOp,
		                             ProjectFile file, ProjectFile genFile, SingleFileCustomToolResult result,
		                             bool runMultipleFiles)
		{
			monitor.EndTask ();
			if (aggOp != null)
				aggOp.Dispose ();
			
			if (monitor.IsCancelRequested) {
				monitor.ReportError (GettextCatalog.GetString ("Cancelled"), null);
				monitor.Dispose ();
				return false;
			}
			
			string genFileName;
			try {
				
				bool broken = false;
				
				if (result.UnhandledException != null) {
					broken = true;
					string msg = GettextCatalog.GetString ("The '{0}' code generator crashed", file.Generator);
					result.Errors.Add (new CompilerError (file.Name, 0, 0, "", msg + ": " + result.UnhandledException.Message));
					monitor.ReportError (msg, result.UnhandledException);
					LoggingService.LogError (msg, result.UnhandledException);
				}

				genFileName = result.GeneratedFilePath.IsNullOrEmpty?
					null : result.GeneratedFilePath.ToRelative (file.FilePath.ParentDirectory);
				
				if (!string.IsNullOrEmpty (genFileName)) {
					bool validName = genFileName.IndexOfAny (new [] { '/', '\\' }) < 0
						&& FileService.IsValidFileName (genFileName);
					
					if (!broken && !validName) {
						broken = true;
						string msg = GettextCatalog.GetString ("The '{0}' code generator output invalid filename '{1}'",
						                                       file.Generator, result.GeneratedFilePath);
						result.Errors.Add (new CompilerError (file.Name, 0, 0, "", msg));
						monitor.ReportError (msg, null);
					}
				}
				
				if (result.Errors.Count > 0) {
					DispatchService.GuiDispatch (delegate {
						foreach (CompilerError err in result.Errors)
							TaskService.Errors.Add (new Task (file.FilePath, err.ErrorText, err.Column, err.Line,
								err.IsWarning? TaskSeverity.Warning : TaskSeverity.Error,
								TaskPriority.Normal, file.Project.ParentSolution, file));
					});
				}
				
				if (broken)
					return true;

				if (!runMultipleFiles) {
					if (result.Success)
						monitor.ReportSuccess ("Generated file successfully.");
					else if (result.SuccessWithWarnings)
						monitor.ReportSuccess ("Warnings in file generation.");
					else
						monitor.ReportError ("Errors in file generation.", null);
				}
			} finally {
				if (!runMultipleFiles)
					monitor.Dispose ();
			}

			if (result.GeneratedFilePath.IsNullOrEmpty || !File.Exists (result.GeneratedFilePath))
				return true;

			// broadcast a change event so text editors etc reload the file
			FileService.NotifyFileChanged (result.GeneratedFilePath);

			// add file to project, update file properties, etc
			Gtk.Application.Invoke (delegate {
				bool projectChanged = false;
				if (genFile == null) {
					genFile = file.Project.AddFile (result.GeneratedFilePath, result.OverrideBuildAction);
					projectChanged = true;
				} else if (result.GeneratedFilePath != genFile.FilePath) {
					genFile.Name = result.GeneratedFilePath;
					projectChanged = true;
				}

				if (file.LastGenOutput != genFileName) {
					file.LastGenOutput = genFileName;
					projectChanged = true;
				}

				if (genFile.DependsOn != file.FilePath.FileName) {
					genFile.DependsOn = file.FilePath.FileName;
					projectChanged = true;
				}

				if (projectChanged)
					IdeApp.ProjectOperations.Save (file.Project);
			});

			return true;
		}
		
		static void HandleRename (ProjectFileRenamedEventArgs e)
		{
			foreach (ProjectFileEventInfo args in e) {
				var file = args.ProjectFile;
				var tool = GetGenerator (file.Generator);
				if (tool == null)
					continue;
			}
		}

		public static string GetFileNamespace (ProjectFile file, string outputFile)
		{
			string ns = file.CustomToolNamespace;
			if (!string.IsNullOrEmpty (ns) || string.IsNullOrEmpty (outputFile))
				return ns;
			var dnfc = file.Project as IDotNetFileContainer;
			if (dnfc != null)
				return dnfc.GetDefaultNamespace (outputFile);
			return ns;
		}

		public static bool WaitForRunningTools (IProgressMonitor monitor)
		{
			IAsyncOperation[] operations;
			lock (runningTasks) {
				operations = runningTasks.Values.ToArray ();
			}

			if (operations.Length == 0)
				return true;

			monitor.BeginTask ("Waiting for custom tools...", operations.Length);

			var evt = new AutoResetEvent (false);

			monitor.CancelRequested += delegate {
				evt.Set ();
			};

			OperationHandler checkOp = delegate {
				monitor.Step (1);
				if (operations.All (op => op.IsCompleted))
					evt.Set ();
			};

			foreach (var o in operations)
				o.Completed += checkOp;

			evt.WaitOne ();

			monitor.EndTask ();

			//the tool operations display warnings themselves
			return operations.Any (op => !op.SuccessWithWarnings);
		}
	}
}