-
Notifications
You must be signed in to change notification settings - Fork 16
/
OpenOnGitHubPackage.cs
340 lines (289 loc) · 12.7 KB
/
OpenOnGitHubPackage.cs
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
using EnvDTE;
using EnvDTE80;
using Microsoft;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
using OpenOnGitHub.Providers;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Process = System.Diagnostics.Process;
using Task = System.Threading.Tasks.Task;
namespace OpenOnGitHub
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[InstalledProductRegistration("#110", "#112", PackageVersion.Version, IconResourceID = 400)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(PackageGuids.GuidOpenOnGitHubPkgString)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideAutoLoad(VSConstants.UICONTEXT.FolderOpened_string, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class OpenOnGitHubPackage : AsyncPackage
{
private DTE2 _dte;
private static readonly IGitUrlProvider AzureDevOpsUrlProvider = new AzureDevOpsUrlProvider();
private static readonly IGitUrlProvider GitHubLabUrlProvider = new GitHubLabUrlProvider();
private static readonly Dictionary<string, IGitUrlProvider> UrlProviders = new()
{
{ "azure.com", AzureDevOpsUrlProvider },
{ "visualstudio.com", AzureDevOpsUrlProvider },
{ "github.com", GitHubLabUrlProvider },
{ "gitlab.com", GitHubLabUrlProvider },
{ "gitea.io", new GiteaUrlProvider() },
{ "gitee.com", new GiteeUrlProvider() },
{ "bitbucket.org", new BitBucketUrlProvider() }
};
private GitRepository _git;
private IGitUrlProvider _provider;
private SolutionExplorerHelper _solutionExplorer;
private SourceLinkProvider _sourceLinkProvider;
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await base.InitializeAsync(cancellationToken, progress);
// Switches to the UI thread in order to consume some services used in command initialization
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
_dte = (DTE2)GetGlobalService(typeof(DTE));
Assumes.NotNull(_dte);
var symbolManager = (IVsDebuggerSymbolSettingsManager120A)GetGlobalService(typeof(SVsShellDebugger));
Assumes.NotNull(symbolManager);
_sourceLinkProvider = new SourceLinkProvider(_dte, symbolManager, GetGitProviderByUrl);
_solutionExplorer = new SolutionExplorerHelper((IVsMonitorSelection)await GetServiceAsync(typeof(IVsMonitorSelection)));
var menuCommandService = (OleMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService));
Assumes.NotNull(menuCommandService);
foreach (var commandContextGuid in PackageGuids.EnumerateCmdSets())
{
foreach (var commandId in PackageCommandIDs.Enumerate())
{
var menuCommandId = new CommandID(commandContextGuid, commandId);
var menuCommand = new OleMenuCommand(ExecuteCommand, null, CheckCommandAvailability, menuCommandId);
menuCommandService.AddCommand(menuCommand);
}
}
}
private void CheckCommandAvailability(object sender, EventArgs e)
{
var jtf = new JoinableTaskFactory(ThreadHelper.JoinableTaskContext);
jtf.Run(async () =>
{
await CheckCommandAvailabilityAsync(sender, e).ConfigureAwait(false);
});
}
private async Task CheckCommandAvailabilityAsync(object sender, EventArgs e)
{
await JoinableTaskFactory.SwitchToMainThreadAsync();
var command = (OleMenuCommand)sender;
try
{
var context = GetCommandContext(command);
var activeFilePath = GetActiveFilePath(context);
if (string.IsNullOrEmpty(activeFilePath))
{
command.Enabled = false;
return;
}
if (_git?.IsInsideRepositoryFolder(activeFilePath) != true)
{
_git?.Dispose();
_git = new GitRepository(activeFilePath);
try
{
await _git.InitializeAsync();
}
catch { }
}
_provider = GetGitProvider();
var type = ToGitHubUrlType(command.CommandID.ID);
if (_git.IsDiscoveredGitRepository)
{
var target = await _git.GetGitHubTargetPathAsync(type);
if (type == GitHubUrlType.CurrentBranch && target == _git.MainBranchName)
{
command.Visible = false;
}
else if (type == GitHubUrlType.Develop && !_git.HasDevelopBranch)
{
command.Visible = false;
}
else
{
command.Enabled = _provider.IsUrlTypeAvailable(type);
command.Text = await _git.GetGitHubTargetDescriptionAsync(type);
command.Visible = true;
}
}
else
{
command.Visible = type != GitHubUrlType.CurrentBranch;
if (!_sourceLinkProvider.IsSourceLink(_dte.ActiveDocument)
|| type != GitHubUrlType.CurrentRevisionFull
|| context == CommandContext.SolutionExplorer)
{
command.Enabled = false;
command.Text = _git.GetInitialGitHubTargetDescription(type);
return;
}
var description = _sourceLinkProvider.GetTargetDescription();
command.Enabled = description != null;
command.Text = description ?? _git.GetInitialGitHubTargetDescription(type);
}
}
catch (Exception ex)
{
Debug.Write(ex);
command.Text = "error:" + ex.GetType().Name;
command.Enabled = false;
}
}
private IGitUrlProvider GetGitProvider()
{
if (!_git.IsDiscoveredGitRepository)
{
return null;
}
var repositoryUri = new Uri(_git.UrlRoot);
return GetGitProviderByUrl(repositoryUri);
}
private static IGitUrlProvider GetGitProviderByUrl(Uri repositoryUri)
{
var host = repositoryUri.Host;
var urlDomainParts = host.Split('.');
var domain = urlDomainParts.Length > 2
? urlDomainParts[urlDomainParts.Length - 2] + "." + urlDomainParts[urlDomainParts.Length - 1]
: host;
if (UrlProviders.TryGetValue(domain, out var provider))
{
return provider;
}
// Private server url such like https://tfs.contoso.com:8080/tfs/Project.
if (repositoryUri.Port == 8080
&& repositoryUri.Segments.Length >= 5
&& string.Equals(repositoryUri.Segments[1], "tfs/", StringComparison.Ordinal))
{
return AzureDevOpsUrlProvider;
}
// Fallback to Git(Hub|Lab) provider as default
// https://gitlab.contoso.com
// https://{Self-Managed}/{org or user}/{repo name}
return GitHubLabUrlProvider;
}
private async void ExecuteCommand(object sender, EventArgs e)
{
var command = (OleMenuCommand)sender;
try
{
ThreadHelper.ThrowIfNotOnUIThread();
var isNotSourceLink = !_sourceLinkProvider.IsSourceLink(_dte.ActiveDocument);
if (!_git.IsDiscoveredGitRepository && isNotSourceLink)
{
command.Enabled = false;
return;
}
var context = GetCommandContext(command);
var urlType = ToGitHubUrlType(command.CommandID.ID);
var activeFilePath = GetActiveFilePath(context);
var textSelection = GetTextSelection(context);
var gitHubUrl = isNotSourceLink
? await _provider.GetUrlAsync(_git, activeFilePath, urlType, textSelection)
: _sourceLinkProvider.GetUrl(textSelection);
Process.Start(gitHubUrl)?.Dispose();
}
catch (Exception ex)
{
Debug.Write(ex);
}
}
private static CommandContext GetCommandContext(MenuCommand command)
{
return command.CommandID.Guid.ToString() switch
{
PackageGuids.GuidDocumentTabOpenOnGitHubCmdSetString => CommandContext.DocumentTab,
PackageGuids.GuidOpenOnGitHubCmdSetString => CommandContext.DocumentEditor,
PackageGuids.GuidSolutionExplorerOpenOnGitHubCmdSetString => CommandContext.SolutionExplorer,
_ => CommandContext.DocumentEditor
};
}
private string GetActiveFilePath(CommandContext context)
{
ThreadHelper.ThrowIfNotOnUIThread();
string fileName;
if (context == CommandContext.SolutionExplorer)
{
var selectedFiles = _solutionExplorer.GetSelectedFiles();
if (selectedFiles.Count != 1)
{
return string.Empty;
}
fileName = selectedFiles[0];
}
else
{
fileName = $"{_dte.ActiveDocument.Path}{_dte.ActiveDocument.Name}";
}
var path = GetExactPathName(fileName);
return path;
}
private static string GetExactPathName(string pathName)
{
if (!(File.Exists(pathName) || Directory.Exists(pathName)))
return pathName;
var directoryInfo = new DirectoryInfo(pathName);
if (directoryInfo.Parent == null)
{
return directoryInfo.Name.ToUpper(CultureInfo.InvariantCulture);
}
var directoryName = GetExactPathName(directoryInfo.Parent.FullName);
var fileSystemInfos = directoryInfo.Parent.GetFileSystemInfos(directoryInfo.Name);
var fileSystemInfo = fileSystemInfos[0];
var fileName = fileSystemInfo.Name;
var exactPathName = Path.Combine(directoryName, fileName);
return exactPathName;
}
private SelectedRange GetTextSelection(CommandContext context)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (context != CommandContext.DocumentEditor ||
_dte.ActiveDocument?.Selection is not TextSelection selection)
{
return SelectedRange.Empty;
}
if (selection.IsEmpty)
{
return new SelectedRange
{
TopLine = selection.CurrentLine,
BottomLine = selection.CurrentLine,
TopColumn = selection.CurrentColumn,
BottomColumn = selection.CurrentColumn
};
}
return new SelectedRange
{
TopLine = selection.TopLine,
BottomLine = selection.BottomLine,
TopColumn = selection.TopPoint.DisplayColumn,
BottomColumn = selection.BottomPoint.DisplayColumn
};
}
private static GitHubUrlType ToGitHubUrlType(int commandId) => commandId switch
{
PackageCommandIDs.OpenMain => GitHubUrlType.Main,
PackageCommandIDs.OpenDevelop => GitHubUrlType.Develop,
PackageCommandIDs.OpenBranch => GitHubUrlType.CurrentBranch,
PackageCommandIDs.OpenRevision => GitHubUrlType.CurrentRevision,
PackageCommandIDs.OpenRevisionFull => GitHubUrlType.CurrentRevisionFull,
_ => GitHubUrlType.Main
};
protected override void Dispose(bool disposing)
{
_git?.Dispose();
base.Dispose(disposing);
}
}
}