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

ProjectService.cs « MonoDevelop.Projects « MonoDevelop.Core « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 12ce44ff8c69686dd2fcc4661cf94ae7154ab172 (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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// 
// ProjectService.cs
//  
// Author:
//       Lluis Sanchez Gual <lluis@novell.com>
// 
// Copyright (c) 2009 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 System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;

using MonoDevelop.Projects;
using MonoDevelop.Core.Serialization;

using MonoDevelop.Core;
using Mono.Addins;
using MonoDevelop.Core.ProgressMonitoring;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core.Assemblies;
using MonoDevelop.Core.Instrumentation;
using MonoDevelop.Projects.Extensions;
using Mono.Unix;
using System.Linq;
using MonoDevelop.Projects.Formats.MSBuild;
using System.Threading.Tasks;

namespace MonoDevelop.Projects
{
	public class ProjectService
	{
		DataContext dataContext = new DataContext ();
		ProjectServiceExtension defaultExtensionChain;
		DefaultProjectServiceExtension extensionChainTerminator = new DefaultProjectServiceExtension ();
		
		TargetFramework defaultTargetFramework;
		
		string defaultPlatformTarget = "x86";
		static readonly TargetFrameworkMoniker DefaultTargetFrameworkId = TargetFrameworkMoniker.NET_4_5;
		
		public const string BuildTarget = "Build";
		public const string CleanTarget = "Clean";
		
		const string SerializableClassesExtensionPath = "/MonoDevelop/ProjectModel/SerializableClasses";
		const string ProjectBindingsExtensionPath = "/MonoDevelop/ProjectModel/ProjectBindings";

		internal const string ProjectModelExtensionsPath = "/MonoDevelop/ProjectModel/ProjectModelExtensions";

		internal event EventHandler DataContextChanged;
		
		internal ProjectService ()
		{
			AddinManager.AddExtensionNodeHandler (SerializableClassesExtensionPath, OnSerializableExtensionChanged);
			AddinManager.ExtensionChanged += OnExtensionChanged;
		}
		
		public DataContext DataContext {
			get { return dataContext; }
		}
		
		internal ProjectServiceExtension GetExtensionChain ()
		{
			if (defaultExtensionChain == null) {
				ProjectServiceExtension[] extensions = AddinManager.GetExtensionObjects<ProjectServiceExtension> ("/MonoDevelop/ProjectModel/ProjectServiceExtensions");
				defaultExtensionChain = CreateExtensionChain (extensions);
			}
			return defaultExtensionChain;
		}
		
		ProjectServiceExtension CreateExtensionChain (ProjectServiceExtension[] extensions)
		{
			if (extensions.Length > 0) {
				for (int n=0; n<extensions.Length - 1; n++)
					extensions [n].Next = extensions [n + 1];
				extensions [extensions.Length - 1].Next = extensionChainTerminator;
				return extensions [0];
			} else {
				return extensionChainTerminator;
			}
		}
		
		public string DefaultPlatformTarget {
			get { return defaultPlatformTarget; }
			set { defaultPlatformTarget = value; }
		}

		public TargetFramework DefaultTargetFramework {
			get {
				if (defaultTargetFramework == null)
					defaultTargetFramework = Runtime.SystemAssemblyService.GetTargetFramework (DefaultTargetFrameworkId); 
				return defaultTargetFramework;
			}
			set {
				defaultTargetFramework = value;
			}
		}

		public async Task<SolutionItem> ReadSolutionItem (ProgressMonitor monitor, string file)
		{
			using (var ctx = new SolutionLoadContext (null))
				return await ReadSolutionItem (monitor, file, null, null, null, ctx);
		}
		
		public Task<SolutionItem> ReadSolutionItem (ProgressMonitor monitor, string file, MSBuildFileFormat format, string typeGuid = null, string itemGuid = null, SolutionLoadContext ctx = null)
		{
			return Runtime.RunInMainThread (async delegate {
				if (!File.Exists (file))
					throw new IOException (GettextCatalog.GetString ("File not found: {0}", file));
				file = Path.GetFullPath (file);
				using (Counters.ReadSolutionItem.BeginTiming ("Read project " + file)) {
					file = GetTargetFile (file);
					SolutionItem loadedItem = await GetExtensionChain ().LoadSolutionItem (monitor, ctx, file, format, typeGuid, itemGuid);
					if (loadedItem != null)
						loadedItem.NeedsReload = false;
					return loadedItem;
				}
			});
		}

		public Task<SolutionFolderItem> ReadSolutionItem (ProgressMonitor monitor, SolutionItemReference reference, params WorkspaceItem[] workspaces)
		{
			return Runtime.RunInMainThread (async delegate {
				if (reference.Id == null) {
					FilePath file = reference.Path.FullPath;
					foreach (WorkspaceItem workspace in workspaces) {
						foreach (SolutionItem eitem in workspace.GetAllItems<Solution>().SelectMany (s => s.GetAllSolutionItems ()))
							if (file == eitem.FileName)
								return eitem;
					}
					return await ReadSolutionItem (monitor, reference.Path);
				} else {
					Solution sol = null;
					if (workspaces.Length > 0) {
						FilePath file = reference.Path.FullPath;
						foreach (WorkspaceItem workspace in workspaces) {
							foreach (Solution item in workspace.GetAllItems<Solution>()) {
								if (item.FileName.FullPath == file) {
									sol = item;
									break;
								}
							}
							if (sol != null)
								break;
						}
					}
					if (sol == null)
						sol = await ReadWorkspaceItem (monitor, reference.Path) as Solution;
					
					if (reference.Id == ":root:")
						return sol.RootFolder;
					else
						return sol.GetSolutionItem (reference.Id);
				}
			});
		}

		public Task<WorkspaceItem> ReadWorkspaceItem (ProgressMonitor monitor, FilePath file)
		{
			return Runtime.RunInMainThread (async delegate {
				if (!File.Exists (file))
					throw new IOException (GettextCatalog.GetString ("File not found: {0}", file));
				string fullpath = file.ResolveLinks ().FullPath;
				using (Counters.ReadWorkspaceItem.BeginTiming ("Read solution " + file)) {
					fullpath = GetTargetFile (fullpath);
					WorkspaceItem item = await GetExtensionChain ().LoadWorkspaceItem (monitor, fullpath) as WorkspaceItem;
					if (item != null)
						item.NeedsReload = false;
					else
						throw new InvalidOperationException ("Invalid file format: " + file);
					return item;
				}
			});
		}
		
		public Task<string> Export (ProgressMonitor monitor, string rootSourceFile, string targetPath, MSBuildFileFormat format)
		{
			rootSourceFile = GetTargetFile (rootSourceFile);
			return Export (monitor, rootSourceFile, null, targetPath, format);
		}
		
		public async Task<string> Export (ProgressMonitor monitor, string rootSourceFile, string[] includedChildIds, string targetPath, MSBuildFileFormat format)
		{
			IMSBuildFileObject obj = null;
			
			if (IsWorkspaceItemFile (rootSourceFile)) {
				obj = (await ReadWorkspaceItem (monitor, rootSourceFile)) as IMSBuildFileObject;
			} else if (IsSolutionItemFile (rootSourceFile)) {
				obj = await ReadSolutionItem (monitor, rootSourceFile);
			}
			if (obj == null)
				throw new InvalidOperationException ("File is not a solution or project.");
			using (obj) {
				return await Export (monitor, obj, includedChildIds, targetPath, format);
			}
		}
		
		async Task<string> Export (ProgressMonitor monitor, IMSBuildFileObject obj, string[] includedChildIds, string targetPath, MSBuildFileFormat format)
		{
			string rootSourceFile = obj.FileName;
			string sourcePath = Path.GetFullPath (Path.GetDirectoryName (rootSourceFile));
			targetPath = Path.GetFullPath (targetPath);
			
			if (sourcePath != targetPath) {
				if (!CopyFiles (monitor, obj, obj.GetItemFiles (true), targetPath, true))
					return null;
				
				string newFile = Path.Combine (targetPath, Path.GetFileName (rootSourceFile));
				if (IsWorkspaceItemFile (rootSourceFile))
					obj = (Solution) await ReadWorkspaceItem (monitor, newFile);
				else
					obj = await ReadSolutionItem (monitor, newFile);
				
				using (obj) {
					var oldFiles = obj.GetItemFiles (true).ToList ();
					ExcludeEntries (obj, includedChildIds);
					if (format != null)
						obj.ConvertToFormat (format);
					await obj.SaveAsync (monitor);
					var newFiles = obj.GetItemFiles (true);
					
					foreach (FilePath f in newFiles) {
						if (!f.IsChildPathOf (targetPath)) {
							if (obj is Solution)
								monitor.ReportError ("The solution '" + obj.Name + "' is referencing the file '" + f.FileName + "' which is located outside the root solution directory.", null);
							else
								monitor.ReportError ("The project '" + obj.Name + "' is referencing the file '" + f.FileName + "' which is located outside the project directory.", null);
						}
						oldFiles.Remove (f);
					}
	
					// Remove old files
					foreach (FilePath file in oldFiles) {
						if (File.Exists (file)) {
							File.Delete (file);
						
							// Exclude empty directories
							FilePath dir = file.ParentDirectory;
							if (Directory.GetFiles (dir).Length == 0 && Directory.GetDirectories (dir).Length == 0) {
								try {
									Directory.Delete (dir);
								} catch (Exception ex) {
									monitor.ReportError (null, ex);
								}
							}
						}
					}
					return obj.FileName;
				}
			}
			else {
				using (obj) {
					ExcludeEntries (obj, includedChildIds);
					if (format != null)
						obj.ConvertToFormat (format);
					await obj.SaveAsync (monitor);
					return obj.FileName;
				}
			}
		}
		
		void ExcludeEntries (IWorkspaceFileObject obj, string[] includedChildIds)
		{
			Solution sol = obj as Solution;
			if (sol != null && includedChildIds != null) {
				// Remove items not to be exported.
				
				Dictionary<string,string> childIds = new Dictionary<string,string> ();
				foreach (string it in includedChildIds)
					childIds [it] = it;
				
				foreach (SolutionFolderItem item in sol.GetAllItems<SolutionFolderItem> ()) {
					if (!childIds.ContainsKey (item.ItemId) && item.ParentFolder != null)
						item.ParentFolder.Items.Remove (item);
				}
			}
		}

		bool CopyFiles (ProgressMonitor monitor, IWorkspaceFileObject obj, IEnumerable<FilePath> files, FilePath targetBasePath, bool ignoreExternalFiles)
		{
			FilePath baseDir = obj.BaseDirectory.FullPath;
			foreach (FilePath file in files) {

				if (!File.Exists (file)) {
					monitor.ReportWarning (GettextCatalog.GetString ("File '{0}' not found.", file));
					continue;
				}
				FilePath fname = file.FullPath;
				
				// Can't export files from outside the root solution directory
				if (!fname.IsChildPathOf (baseDir)) {
					if (ignoreExternalFiles)
						continue;
					if (obj is Solution)
						monitor.ReportError ("The solution '" + obj.Name + "' is referencing the file '" + Path.GetFileName (file) + "' which is located outside the root solution directory.", null);
					else
						monitor.ReportError ("The project '" + obj.Name + "' is referencing the file '" + Path.GetFileName (file) + "' which is located outside the project directory.", null);
					return false;
				}

				FilePath rpath = fname.ToRelative (baseDir);
				rpath = rpath.ToAbsolute (targetBasePath);
				
				if (!Directory.Exists (rpath.ParentDirectory))
					Directory.CreateDirectory (rpath.ParentDirectory);

				File.Copy (file, rpath, true);
			}
			return true;
		}
		
		public DotNetProject CreateDotNetProject (string language, params string[] typeGuids)
		{
			string typeGuid = MSBuildProjectService.GetLanguageGuid (language);
			return (DotNetProject) MSBuildProjectService.CreateProject (typeGuid, typeGuids);
		}

		public Project CreateProject (string typeGuid, params string[] typeGuids)
		{
			return MSBuildProjectService.CreateProject (typeGuid, typeGuids);
		}

		public Project CreateProject (string typeAlias, ProjectCreateInformation info, XmlElement projectOptions)
		{
			return MSBuildProjectService.CreateSolutionItem (typeAlias, info, projectOptions) as Project;
		}

		public bool CanCreateProject (string typeAlias)
		{
			// TODO NPM: review
			return MSBuildProjectService.CanCreateSolutionItem (typeAlias, null, null);
		}

		public bool CanCreateProject (string typeAlias, ProjectCreateInformation info, XmlElement projectOptions)
		{
			return MSBuildProjectService.CanCreateSolutionItem (typeAlias, info, projectOptions);
		}

		//TODO: find solution that contains the project if possible
		public async Task<Solution> GetWrapperSolution (ProgressMonitor monitor, string filename)
		{
			// First of all, check if a solution with the same name already exists
			
			string solFileName = Path.ChangeExtension (filename, ".sln");
			
			if (File.Exists (solFileName)) {
				return (Solution) await Services.ProjectService.ReadWorkspaceItem (monitor, solFileName);
			}
			else {
				// Create a temporary solution and add the project to the solution
				SolutionItem sitem = await Services.ProjectService.ReadSolutionItem (monitor, filename);
				Solution tempSolution = new Solution ();
				tempSolution.FileName = solFileName;
				tempSolution.ConvertToFormat (sitem.FileFormat);
				tempSolution.RootFolder.Items.Add (sitem);
				tempSolution.CreateDefaultConfigurations ();
				await tempSolution.SaveAsync (monitor);
				return tempSolution;
			}
		}

		public bool FileIsObjectOfType (FilePath file, Type type)
		{
			var filename = GetTargetFile (file);
			return GetExtensionChain ().FileIsObjectOfType (filename, type);
		}

		public bool IsSolutionItemFile (FilePath file)
		{
			var filename = GetTargetFile (file);
			return GetExtensionChain ().FileIsObjectOfType (filename, typeof(SolutionItem));
		}

		public bool IsWorkspaceItemFile (FilePath file)
		{
			var filename = GetTargetFile (file);
			return GetExtensionChain ().FileIsObjectOfType (filename, typeof(WorkspaceItem));
		}
		
		internal void InitializeDataContext (DataContext ctx)
		{
			foreach (DataTypeCodon dtc in AddinManager.GetExtensionNodes (SerializableClassesExtensionPath)) {
				ctx.IncludeType (dtc.Addin, dtc.TypeName, dtc.ItemName);
			}
		}

		void OnSerializableExtensionChanged (object s, ExtensionNodeEventArgs args)
		{
			if (args.Change == ExtensionChange.Add) {
				DataTypeCodon t = (DataTypeCodon) args.ExtensionNode;
				DataContext.IncludeType (t.Addin, t.TypeName, t.ItemName);
			}
			// Types can't be excluded from a DataContext, but that's not a big problem anyway
			
			if (DataContextChanged != null)
				DataContextChanged (this, EventArgs.Empty);
		}
		
		void OnExtensionChanged (object s, ExtensionEventArgs args)
		{
			if (args.PathChanged ("/MonoDevelop/ProjectModel/ProjectServiceExtensions"))
				defaultExtensionChain = null;
		}
		
		string GetTargetFile (string file)
		{
			if (!Platform.IsWindows) {
				try {
					UnixSymbolicLinkInfo fi = new UnixSymbolicLinkInfo (file);
					if (fi.IsSymbolicLink)
						return fi.ContentsPath;
				} catch {
				}
			}
			return file;
		}
	}
	
	internal class DefaultProjectServiceExtension: ProjectServiceExtension
	{
		public override bool FileIsObjectOfType (string file, Type type)
		{
			return false;
		}

		public override Task<SolutionItem> LoadSolutionItem (ProgressMonitor monitor, SolutionLoadContext ctx, string fileName, MSBuildFileFormat expectedFormat, string typeGuid, string itemGuid)
		{
			return Task.FromResult ((SolutionItem)null);
		}
		
		public override Task<WorkspaceItem> LoadWorkspaceItem (ProgressMonitor monitor, string fileName)
		{
			return Task.FromResult ((WorkspaceItem)null);
		}
	}	
	
	internal static class Counters
	{
		public static Counter ItemsInMemory = InstrumentationService.CreateCounter ("Projects in memory", "Project Model");
		public static Counter ItemsLoaded = InstrumentationService.CreateCounter ("Projects loaded", "Project Model");
		public static Counter SolutionsInMemory = InstrumentationService.CreateCounter ("Solutions in memory", "Project Model");
		public static Counter SolutionsLoaded = InstrumentationService.CreateCounter ("Solutions loaded", "Project Model");

		public static TimerCounter ReadWorkspaceItem = InstrumentationService.CreateTimerCounter ("Workspace item read", "Project Model", id:"Projects.WorkspaceItemRead");
		public static TimerCounter ReadSolutionItem = InstrumentationService.CreateTimerCounter ("Solution item read", "Project Model", id:"Projects.SolutionItemRead");
		public static TimerCounter ReadMSBuildProject = InstrumentationService.CreateTimerCounter ("MSBuild project read", "Project Model", id:"Projects.MSBuildProjectRead");
		public static TimerCounter WriteMSBuildProject = InstrumentationService.CreateTimerCounter ("MSBuild project written", "Project Model", id:"Projects.MSBuildProjectWritten");

		public static TimerCounter BuildSolutionTimer = InstrumentationService.CreateTimerCounter ("Build solution", "Project Model", id:"Projects.BuildSolution");
		public static TimerCounter BuildProjectAndReferencesTimer = InstrumentationService.CreateTimerCounter ("Build project and references", "Project Model", id:"Projects.BuildProjectAndReferences");
		public static TimerCounter BuildProjectTimer = InstrumentationService.CreateTimerCounter ("Build project", "Project Model", id:"Projects.BuildProject");
		public static TimerCounter CleanProjectTimer = InstrumentationService.CreateTimerCounter ("Clean project", "Project Model", id:"Projects.CleanProject");
		public static TimerCounter BuildWorkspaceItemTimer = InstrumentationService.CreateTimerCounter ("Build workspace item", "Project Model");
		public static TimerCounter NeedsBuildingTimer = InstrumentationService.CreateTimerCounter ("Check needs building", "Project Model");
		
		public static TimerCounter BuildMSBuildProjectTimer = InstrumentationService.CreateTimerCounter ("Build MSBuild project", "Project Model", id:"Projects.BuildMSBuildProject");
		public static TimerCounter CleanMSBuildProjectTimer = InstrumentationService.CreateTimerCounter ("Clean MSBuild project", "Project Model", id:"Projects.CleanMSBuildProject");
		public static TimerCounter RunMSBuildTargetTimer = InstrumentationService.CreateTimerCounter ("Run MSBuild target", "Project Model", id:"Projects.RunMSBuildTarget");
		public static TimerCounter ResolveMSBuildReferencesTimer = InstrumentationService.CreateTimerCounter ("Resolve MSBuild references", "Project Model", id:"Projects.ResolveMSBuildReferences");

		public static TimerCounter HelpServiceInitialization = InstrumentationService.CreateTimerCounter ("Help Service initialization", "IDE");
		public static TimerCounter ParserServiceInitialization = InstrumentationService.CreateTimerCounter ("Parser Service initialization", "IDE");
	}
}