-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathVsHelpers.cs
More file actions
561 lines (453 loc) · 18.5 KB
/
VsHelpers.cs
File metadata and controls
561 lines (453 loc) · 18.5 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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Telemetry;
using Microsoft.Web.LibraryManager.Contracts;
using Microsoft.Web.LibraryManager.Vsix.Contracts;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.Web.LibraryManager.Vsix.Shared
{
internal static class VsHelpers
{
private static IComponentModel CompositionService;
public static DTE2 DTE { get; } = GetService<DTE, DTE2>();
public static TReturnType GetService<TServiceType, TReturnType>()
{
return (TReturnType)ServiceProvider.GlobalProvider.GetService(typeof(TServiceType));
}
public static string GetFileInVsix(string relativePath)
{
string folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
return Path.Combine(folder, relativePath);
}
public static bool IsConfigFile(this ProjectItem item)
{
return item.Name.Equals(Constants.ConfigFileName, StringComparison.OrdinalIgnoreCase);
}
public static async Task CheckFileOutOfSourceControlAsync(string file)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!File.Exists(file) || DTE.Solution.FindProjectItem(file) == null)
{
return;
}
if (DTE.SourceControl.IsItemUnderSCC(file) && !DTE.SourceControl.IsItemCheckedOut(file))
{
DTE.SourceControl.CheckOutItem(file);
}
var info = new FileInfo(file)
{
IsReadOnly = false
};
}
internal static async Task OpenFileAsync(string configFilePath)
{
if (!string.IsNullOrEmpty(configFilePath))
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
DTE?.ItemOperations?.OpenFile(configFilePath);
}
}
internal static async Task<ProjectItem> GetSelectedItemAsync()
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
ProjectItem projectItem = null;
if (DTE?.SelectedItems.Count == 1)
{
SelectedItem selectedItem = VsHelpers.DTE.SelectedItems.Item(1);
projectItem = selectedItem?.ProjectItem;
}
return projectItem;
}
public static async Task<Project> GetProjectOfSelectedItemAsync()
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
Project project = null;
if (DTE?.SelectedItems.Count == 1)
{
SelectedItem selectedItem = DTE.SelectedItems.Item(1);
project = selectedItem.Project ?? selectedItem.ProjectItem?.ContainingProject;
}
return project;
}
public static async Task AddFileToProjectAsync(this Project project, string file, string itemType = null)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (IsCapabilityMatch(project, Constants.DotNetCoreWebCapability))
{
return;
}
try
{
if (DTE.Solution.FindProjectItem(file) == null)
{
ProjectItem item = project.ProjectItems.AddFromFile(file);
if (string.IsNullOrEmpty(itemType) || project.IsKind(Constants.WebsiteProject))
{
return;
}
item.Properties.Item("ItemType").Value = "None";
}
}
catch (Exception ex)
{
Logger.LogEvent(ex.ToString(), LogLevel.Error);
Telemetry.TrackException(nameof(AddFilesToProjectAsync), ex);
System.Diagnostics.Debug.Write(ex);
}
}
public static async Task AddFilesToProjectAsync(Project project, IEnumerable<string> files, Action<string, LogLevel> logAction, CancellationToken cancellationToken)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
if (project == null || IsCapabilityMatch(project, Constants.DotNetCoreWebCapability))
{
return;
}
if (project.IsKind(Constants.WebsiteProject))
{
Command command = DTE.Commands.Item("SolutionExplorer.Refresh");
if (command.IsAvailable)
{
DTE.ExecuteCommand(command.Name);
}
return;
}
var solutionService = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
IVsHierarchy hierarchy = null;
if (solutionService != null && !ErrorHandler.Failed(solutionService.GetProjectOfUniqueName(project.UniqueName, out hierarchy)))
{
if (hierarchy == null)
{
return;
}
var vsProject = (IVsProject)hierarchy;
await AddFilesToHierarchyAsync(hierarchy, files, logAction, cancellationToken);
}
}
public static async Task<string> GetRootFolderAsync(this Project project)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (project == null)
{
return null;
}
if (project.IsKind(ProjectKinds.vsProjectKindSolutionFolder))
{
return Path.GetDirectoryName(DTE.Solution.FullName);
}
if (string.IsNullOrEmpty(project.FullName))
{
return null;
}
string fullPath;
try
{
fullPath = project.Properties.Item("FullPath").Value as string;
}
catch (ArgumentException)
{
try
{
// MFC projects don't have FullPath, and there seems to be no way to query existence
fullPath = project.Properties.Item("ProjectDirectory").Value as string;
}
catch (ArgumentException)
{
// Installer projects have a ProjectPath.
fullPath = project.Properties.Item("ProjectPath").Value as string;
}
}
if (string.IsNullOrEmpty(fullPath))
{
return File.Exists(project.FullName) ? Path.GetDirectoryName(project.FullName) : null;
}
if (Directory.Exists(fullPath))
{
return fullPath;
}
if (File.Exists(fullPath))
{
return Path.GetDirectoryName(fullPath);
}
return null;
}
public static bool IsKind(this Project project, params string[] kindGuids)
{
foreach (string guid in kindGuids)
{
if (project.Kind.Equals(guid, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
public static async Task<bool> IsDotNetCoreWebProjectAsync(Project project)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (project == null || IsCapabilityMatch(project, Constants.DotNetCoreWebCapability))
{
return true;
}
return false;
}
public static async Task<bool> DeleteFilesFromProjectAsync(Project project, IEnumerable<string> filePaths, Action<string, LogLevel> logAction, CancellationToken cancellationToken)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
int batchSize = 10;
try
{
IVsHierarchy hierarchy = GetHierarchy(project);
IVsProjectBuildSystem bldSystem = hierarchy as IVsProjectBuildSystem;
List<string> filesToRemove = filePaths.ToList();
while (filesToRemove.Any())
{
List<string> nextBatch = filesToRemove.Take(batchSize).ToList();
bool success = await DeleteProjectItemsInBatchAsync(hierarchy, nextBatch, logAction, cancellationToken);
if (!success)
{
return false;
}
await System.Threading.Tasks.Task.Yield();
int countToDelete = Math.Min(filesToRemove.Count, batchSize);
filesToRemove.RemoveRange(0, countToDelete);
}
return true;
}
catch (Exception ex)
{
Telemetry.TrackException(nameof(DeleteFilesFromProjectAsync), ex);
return false;
}
}
public static void SatisfyImportsOnce(this object o)
{
CompositionService = CompositionService ?? GetService<SComponentModel, IComponentModel>();
if (CompositionService != null)
{
CompositionService.DefaultCompositionService.SatisfyImportsOnce(o);
}
}
public static async Task<bool> ProjectContainsManifestFileAsync(Project project)
{
string rootPath = await GetRootFolderAsync(project);
if (!string.IsNullOrEmpty(rootPath))
{
string configFilePath = Path.Combine(rootPath, Constants.ConfigFileName);
if (File.Exists(configFilePath))
{
Telemetry.TrackUserTask("ProjectContainsLibMan", TelemetryResult.None, new[] { new KeyValuePair<string, object>("ProjectGUID", project.Kind) });
return true;
}
}
return false;
}
public static async Task<bool> SolutionContainsManifestFileAsync(IVsSolution solution)
{
IEnumerable<IVsHierarchy> hierarchies = GetProjectsInSolution(solution, __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION);
foreach (IVsHierarchy hierarchy in hierarchies)
{
Project project = GetDTEProject(hierarchy);
if (project != null && await ProjectContainsManifestFileAsync(project))
{
return true;
}
}
return false;
}
public static IEnumerable<IVsHierarchy> GetProjectsInSolution(IVsSolution solution, __VSENUMPROJFLAGS flags)
{
if (solution == null)
{
yield break;
}
Guid guid = Guid.Empty;
if (ErrorHandler.Failed(solution.GetProjectEnum((uint)flags, ref guid, out IEnumHierarchies enumHierarchies)) || enumHierarchies == null)
{
yield break;
}
IVsHierarchy[] hierarchy = new IVsHierarchy[1];
while (ErrorHandler.Succeeded(enumHierarchies.Next(1, hierarchy, out uint fetched)) && fetched == 1)
{
if (hierarchy.Length > 0 && hierarchy[0] != null)
{
yield return hierarchy[0];
}
}
}
public static Project GetDTEProject(IVsHierarchy hierarchy)
{
if (ErrorHandler.Succeeded(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out object obj)))
{
return obj as Project;
}
return null;
}
public static bool IsCapabilityMatch(Project project, string capability)
{
IVsHierarchy hierarchy = GetHierarchy(project);
if (hierarchy != null)
{
return hierarchy.IsCapabilityMatch(capability);
}
return false;
}
public static IVsHierarchy GetHierarchy(Project project)
{
IVsSolution solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
if (ErrorHandler.Succeeded(solution.GetProjectOfUniqueName(project.FullName, out IVsHierarchy hierarchy)))
{
return hierarchy;
}
return null;
}
public static Project GetDTEProjectFromConfig(string file)
{
try
{
ProjectItem projectItem = DTE.Solution.FindProjectItem(file);
if (projectItem != null)
{
return projectItem.ContainingProject;
}
}
catch (Exception ex)
{
Logger.LogEvent(ex.ToString(), LogLevel.Error);
Telemetry.TrackException(nameof(GetDTEProjectFromConfig), ex);
System.Diagnostics.Debug.Write(ex);
}
return null;
}
private static async Task<bool> AddFilesToHierarchyAsync(IVsHierarchy hierarchy, IEnumerable<string> filePaths, Action<string, LogLevel> logAction, CancellationToken cancellationToken)
{
int batchSize = 10;
List<string> filesToAdd = filePaths.ToList();
while (filesToAdd.Any())
{
List<string> nextBatch = filesToAdd.Take(batchSize).ToList();
bool success = await AddProjectItemsInBatchAsync(hierarchy, nextBatch, logAction, cancellationToken);
if (!success)
{
return false;
}
await System.Threading.Tasks.Task.Yield();
int countToDelete = filesToAdd.Count >= batchSize ? batchSize : filesToAdd.Count;
filesToAdd.RemoveRange(0, countToDelete);
}
return true;
}
private static async Task<bool> AddProjectItemsInBatchAsync(IVsHierarchy vsHierarchy, List<string> filePaths, Action<string, LogLevel> logAction, CancellationToken cancellationToken)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
IVsProjectBuildSystem bldSystem = vsHierarchy as IVsProjectBuildSystem;
try
{
if (bldSystem != null)
{
bldSystem.StartBatchEdit();
}
cancellationToken.ThrowIfCancellationRequested();
var vsProject = (IVsProject)vsHierarchy;
VSADDRESULT[] result = new VSADDRESULT[filePaths.Count];
vsProject.AddItem(VSConstants.VSITEMID_ROOT,
VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE,
string.Empty,
(uint)filePaths.Count,
filePaths.ToArray(),
IntPtr.Zero,
result);
foreach (string filePath in filePaths)
{
logAction.Invoke(string.Format(Resources.Text.LibraryAddedToProject, filePath.Replace('\\', '/')), LogLevel.Operation);
}
}
catch(Exception ex)
{
Telemetry.TrackException(nameof(AddProjectItemsInBatchAsync), ex);
return false;
}
finally
{
if (bldSystem != null)
{
bldSystem.EndBatchEdit();
}
}
return true;
}
private static async Task<bool> DeleteProjectItemsInBatchAsync(IVsHierarchy hierarchy, IEnumerable<string> filePaths, Action<string, LogLevel> logAction, CancellationToken cancellationToken)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
IVsProjectBuildSystem bldSystem = hierarchy as IVsProjectBuildSystem;
HashSet<ProjectItem> folders = new HashSet<ProjectItem>();
try
{
if (bldSystem != null)
{
bldSystem.StartBatchEdit();
}
foreach (string filePath in filePaths)
{
cancellationToken.ThrowIfCancellationRequested();
ProjectItem item = DTE.Solution.FindProjectItem(filePath);
if (item != null)
{
ProjectItem parentFolder = item.Collection.Parent as ProjectItem;
folders.Add(parentFolder);
item.Delete();
logAction.Invoke(string.Format(Resources.Text.LibraryDeletedFromProject, filePath.Replace('\\', '/')), LogLevel.Operation);
}
}
DeleteEmptyFolders(folders);
}
catch(Exception ex)
{
Telemetry.TrackException(nameof(DeleteProjectItemsInBatchAsync), ex);
return false;
}
finally
{
if (bldSystem != null)
{
bldSystem.EndBatchEdit();
}
}
return true;
}
private static void DeleteEmptyFolders(HashSet<ProjectItem> folders)
{
foreach (ProjectItem folder in folders)
{
if (folder.ProjectItems.Count == 0)
{
folder.Delete();
}
}
}
public static Guid GetProjectGuid(Project project)
{
string uniqueName = project.UniqueName;
IVsSolution solution = (IVsSolution)Package.GetGlobalService(typeof(SVsSolution));
solution.GetProjectOfUniqueName(uniqueName, out IVsHierarchy hierarchy);
hierarchy.GetGuidProperty(
(uint)VSConstants.VSITEMID.Root,
(int)__VSHPROPID.VSHPROPID_ProjectIDGuid,
out Guid projectGuid);
return projectGuid;
}
}
}