Repository navigation
Expand file tree
/
Copy pathVsProjectSystem.cs
More file actions
547 lines (473 loc) · 20.6 KB
/
Copy pathVsProjectSystem.cs
File metadata and controls
547 lines (473 loc) · 20.6 KB
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.VisualStudio.Resources;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
using MsBuildProjectItem = Microsoft.Build.Evaluation.ProjectItem;
using Project = EnvDTE.Project;
namespace NuGet.VisualStudio
{
public class VsProjectSystem : PhysicalFileSystem, IVsProjectSystem, IComparer<IPackageFile>
{
private const string BinDir = "bin";
private FrameworkName _targetFramework;
private readonly IFileSystem _baseFileSystem;
public VsProjectSystem(Project project, IFileSystemProvider fileSystemProvider)
: base(project.GetFullPath())
{
Project = project;
_baseFileSystem = fileSystemProvider.GetFileSystem(project.GetFullPath());
Debug.Assert(_baseFileSystem != null);
}
public Project Project
{
get;
private set;
}
protected IFileSystem BaseFileSystem
{
get
{
return _baseFileSystem;
}
}
public virtual string ProjectName
{
get
{
return Project.Name;
}
}
public string UniqueName
{
get
{
return Project.GetUniqueName();
}
}
public FrameworkName TargetFramework
{
get
{
if (_targetFramework == null)
{
_targetFramework = Project.GetTargetFrameworkName() ?? VersionUtility.DefaultTargetFramework;
}
return _targetFramework;
}
}
public virtual bool IsBindingRedirectSupported
{
get
{
// Silverlight projects and Windows Phone projects do not support binding redirect.
// They both share the same identifier as "Silverlight"
return !"Silverlight".Equals(TargetFramework.Identifier, StringComparison.OrdinalIgnoreCase);
}
}
public override void AddFile(string path, Stream stream)
{
AddFileCore(path, () => base.AddFile(path, stream));
}
public override void AddFile(string path, Action<Stream> writeToStream)
{
AddFileCore(path, () => base.AddFile(path, writeToStream));
}
private void AddFileCore(string path, Action addFile)
{
bool fileExistsInProject = FileExistsInProject(path);
// If the file exists on disk but not in the project then skip it.
// One exception is the 'packages.config' file, in which case we want to include
// it into the project.
if (base.FileExists(path) && !fileExistsInProject && !path.Equals(Constants.PackageReferenceFile))
{
Logger.Log(MessageLevel.Warning, VsResources.Warning_FileAlreadyExists, path);
}
else
{
EnsureCheckedOutIfExists(path);
addFile();
if (!fileExistsInProject)
{
AddFileToProject(path);
}
}
}
public override Stream CreateFile(string path)
{
EnsureCheckedOutIfExists(path);
return base.CreateFile(path);
}
public override void DeleteDirectory(string path, bool recursive = false)
{
// Only delete this folder if it is empty and we didn't specify that we want to recurse
if (!recursive && (base.GetFiles(path, "*.*", recursive).Any() || base.GetDirectories(path).Any()))
{
Logger.Log(MessageLevel.Warning, VsResources.Warning_DirectoryNotEmpty, path);
return;
}
// Workaround for TFS update issue. If we're bound to TFS, do not try and delete directories.
if (!(_baseFileSystem is ISourceControlFileSystem) && Project.DeleteProjectItem(path))
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFolder, path);
}
}
public override void DeleteFile(string path)
{
if (Project.DeleteProjectItem(path))
{
string folderPath = Path.GetDirectoryName(path);
if (!String.IsNullOrEmpty(folderPath))
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFileFromFolder, Path.GetFileName(path), folderPath);
}
else
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFile, Path.GetFileName(path));
}
}
}
public void AddFrameworkReference(string name)
{
try
{
// Add a reference to the project
AddGacReference(name);
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
}
catch (Exception e)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddGacReference, name), e);
}
}
protected virtual void AddGacReference(string name)
{
Project.GetReferences().Add(name);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")]
public virtual void AddReference(string referencePath)
{
string name = Path.GetFileNameWithoutExtension(referencePath);
try
{
// Get the full path to the reference
string fullPath = PathUtility.GetAbsolutePath(Root, referencePath);
string assemblyPath = fullPath;
bool usedTempFile = false;
// There is a bug in Visual Studio whereby if the fullPath contains a comma,
// then calling Project.Object.References.Add() on it will throw a COM exception.
// To work around it, we copy the assembly into temp folder and add reference to the copied assembly
if (fullPath.Contains(","))
{
string tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileName(fullPath));
File.Copy(fullPath, tempFile, true);
assemblyPath = tempFile;
usedTempFile = true;
}
// Add a reference to the project
dynamic reference = Project.GetReferences().Add(assemblyPath);
// if we copied the assembly to temp folder earlier, delete it now since we no longer need it.
if (usedTempFile)
{
try
{
File.Delete(assemblyPath);
}
catch
{
// don't care if we fail to delete a temp file
}
}
if (reference != null)
{
// This happens if the assembly appears in any of the search paths that VS uses to locate assembly references.
// Most commonly, it happens if this assembly is in the GAC or in the output path.
if (reference.Path != null && !reference.Path.Equals(fullPath, StringComparison.OrdinalIgnoreCase))
{
// Get the msbuild project for this project
MsBuildProject buildProject = Project.AsMSBuildProject();
if (buildProject != null)
{
// Get the assembly name of the reference we are trying to add
AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath);
// Try to find the item for the assembly name
MsBuildProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences()
where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2)
select assemblyReferenceNode.Item1).FirstOrDefault();
if (item != null)
{
// Add the <HintPath> metadata item as a relative path
item.SetMetadataValue("HintPath", referencePath);
// Set <Private> to true
item.SetMetadataValue("Private", "True");
// Save the project after we've modified it.
Project.Save(this);
}
}
}
else
{
TrySetSpecificVersion(reference);
TrySetCopyLocal(reference);
}
}
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
}
catch (Exception e)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddReference, name), e);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")]
public virtual void RemoveReference(string name)
{
try
{
// Get the reference name without extension
string referenceName = Path.GetFileNameWithoutExtension(name);
// Remove the reference from the project
// NOTE:- Project.Object.References.Item requires Reference.Identity
// which is, the Assembly name without path or extension
// But, we pass in the assembly file name. And, this works for
// almost all the assemblies since Assembly Name is the same as the assembly file name
// In case of F#, the input parameter is case-sensitive as well
// Hence, an override to THIS function is added to take care of that
var reference = Project.GetReferences().Item(referenceName);
if (reference != null)
{
reference.Remove();
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemoveReference, name, ProjectName);
}
}
catch (Exception e)
{
Logger.Log(MessageLevel.Warning, e.Message);
}
}
public virtual bool FileExistsInProject(string path)
{
return Project.ContainsFile(path);
}
protected virtual bool ExcludeFile(string path)
{
// Exclude files from the bin directory.
return Path.GetDirectoryName(path).Equals(BinDir, StringComparison.OrdinalIgnoreCase);
}
protected virtual void AddFileToProject(string path)
{
if (ExcludeFile(path))
{
return;
}
// Get the project items for the folder path
string folderPath = Path.GetDirectoryName(path);
string fullPath = GetFullPath(path);
ThreadHelper.Generic.Invoke(() =>
{
ProjectItems container = Project.GetProjectItems(folderPath, createIfNotExists: true);
// Add the file to project or folder
AddFileToContainer(fullPath, folderPath, container);
});
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddedFileToProject, path, ProjectName);
}
protected virtual void AddFileToContainer(string fullPath, string folderPath, ProjectItems container)
{
container.AddFromFileCopy(fullPath);
}
public virtual string ResolvePath(string path)
{
return path;
}
public override IEnumerable<string> GetFiles(string path, string filter, bool recursive)
{
if (recursive)
{
throw new NotSupportedException();
}
else
{
// Get all physical files
return from p in Project.GetChildItems(path, filter, VsConstants.VsProjectItemKindPhysicalFile)
select p.Name;
}
}
public override IEnumerable<string> GetDirectories(string path)
{
// Get all physical folders
return from p in Project.GetChildItems(path, "*.*", VsConstants.VsProjectItemKindPhysicalFolder)
select p.Name;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We never want to fail when checking for existance")]
public virtual bool ReferenceExists(string name)
{
try
{
string referenceName = name;
if (Constants.AssemblyReferencesExtensions.Contains(Path.GetExtension(name), StringComparer.OrdinalIgnoreCase))
{
// Get the reference name without extension
referenceName = Path.GetFileNameWithoutExtension(name);
}
return Project.GetReferences().Item(referenceName) != null;
}
catch
{
}
return false;
}
public virtual dynamic GetPropertyValue(string propertyName)
{
try
{
Property property = Project.Properties.Item(propertyName);
if (property != null)
{
return property.Value;
}
}
catch (ArgumentException)
{
// If the property doesn't exist this will throw an argument exception
}
return null;
}
public virtual void AddImport(string targetPath, ProjectImportLocation location)
{
if (String.IsNullOrEmpty(targetPath))
{
throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath");
}
string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
Project.AddImportStatement(relativeTargetPath, location);
Project.Save(this);
// notify the project system of the change
UpdateImportStamp(Project);
}
public virtual void RemoveImport(string targetPath)
{
if (String.IsNullOrEmpty(targetPath))
{
throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath");
}
string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
Project.RemoveImportStatement(relativeTargetPath);
Project.Save(this);
// notify the project system of the change
UpdateImportStamp(Project);
}
public virtual bool IsSupportedFile(string path)
{
string fileName = Path.GetFileName(path);
// exclude all file names with the pattern as "web.*.config",
// e.g. web.config, web.release.config, web.debug.config
return !(fileName.StartsWith("web.", StringComparison.OrdinalIgnoreCase) &&
fileName.EndsWith(".config", StringComparison.OrdinalIgnoreCase));
}
private void EnsureCheckedOutIfExists(string path)
{
Project.EnsureCheckedOutIfExists(this, path);
}
private static bool AssemblyNamesMatch(AssemblyName name1, AssemblyName name2)
{
return name1.Name.Equals(name2.Name, StringComparison.OrdinalIgnoreCase) &&
EqualsIfNotNull(name1.Version, name2.Version) &&
EqualsIfNotNull(name1.CultureInfo, name2.CultureInfo) &&
EqualsIfNotNull(name1.GetPublicKeyToken(), name2.GetPublicKeyToken(), Enumerable.SequenceEqual);
}
private static bool EqualsIfNotNull<T>(T obj1, T obj2)
{
return EqualsIfNotNull(obj1, obj2, (a, b) => a.Equals(b));
}
private static bool EqualsIfNotNull<T>(T obj1, T obj2, Func<T, T, bool> equals)
{
// If both objects are non null do the equals
if (obj1 != null && obj2 != null)
{
return equals(obj1, obj2);
}
// Otherwise consider them equal if either of the values are null
return true;
}
public int Compare(IPackageFile x, IPackageFile y)
{
// BUG 636: We sort files so that they are added in the correct order
// e.g aspx before aspx.cs
if (x.Path.Equals(y.Path, StringComparison.OrdinalIgnoreCase))
{
return 0;
}
// Add files that are prefixes of other files first
if (x.Path.StartsWith(y.Path, StringComparison.OrdinalIgnoreCase))
{
return -1;
}
if (y.Path.StartsWith(x.Path, StringComparison.OrdinalIgnoreCase))
{
return 1;
}
return y.Path.CompareTo(x.Path);
}
/// <summary>
/// Sets NuGetPackageImportStamp to a new random guid. This is a hack to let the project system know it is out of date.
/// The value does not matter, it just needs to change.
/// </summary>
protected static void UpdateImportStamp(Project project)
{
// There is no reason to call this for pre-Dev12 project systems.
if (VsVersionHelper.VsMajorVersion >= 12)
{
IVsBuildPropertyStorage propStore = project.ToVsHierarchy() as IVsBuildPropertyStorage;
if (propStore != null)
{
// <NuGetPackageImportStamp>af617720</NuGetPackageImportStamp>
string stamp = Guid.NewGuid().ToString().Split('-')[0];
ErrorHandler.ThrowOnFailure(propStore.SetPropertyValue("NuGetPackageImportStamp", string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, stamp));
}
}
}
private static void TrySetCopyLocal(dynamic reference)
{
// Always set copy local to true for references that we add
try
{
// In order to properly write this to MSBuild in ALL cases, we have to trigger the Property Change
// notification with a new value of "true". However, "true" is the default value, so in order to
// cause a notification to fire, we have to set it to false and then back to true
reference.CopyLocal = false;
reference.CopyLocal = true;
}
catch (NotSupportedException)
{
}
catch (NotImplementedException)
{
}
}
// Set SpecificVersion to true
private static void TrySetSpecificVersion(dynamic reference)
{
// Always set SpecificVersion to true for references that we add
try
{
reference.SpecificVersion = false;
reference.SpecificVersion = true;
}
catch (NotSupportedException)
{
}
catch (NotImplementedException)
{
}
}
}
}