-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlink-handler.ts
More file actions
709 lines (607 loc) · 22.2 KB
/
link-handler.ts
File metadata and controls
709 lines (607 loc) · 22.2 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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
import type { Stats } from 'fs';
import type { Git } from './git';
import type {
HandlerDefinition,
ReverseSelectionSettings,
ReverseServerSettings,
StaticServer
} from './schema';
import type { ParsedTemplate } from './templates';
import type {
FileInfo,
LinkOptions,
LinkType,
Mutable,
RepositoryWithRemote,
SelectedRange,
UrlInfo
} from './types';
import { promises as fs } from 'fs';
import * as path from 'path';
import { URL } from 'url';
import { NoRemoteHeadError } from './no-remote-head-error';
import { RemoteServer } from './remote-server';
import { Settings } from './settings';
import { parseTemplate } from './templates';
import { getErrorMessage, getSshUserSpecification, normalizeUrl } from './utilities';
/**
* Handles the generation of links for a particular type of Git server.
*/
export class LinkHandler {
private readonly server: RemoteServer;
private readonly settingsKeys: string[] | undefined;
private readonly settings: Settings;
private readonly urlTemplate: ParsedTemplate;
private readonly selectionTemplate: ParsedTemplate;
private readonly reverse: ParsedReverseSettings;
private readonly queryModifications: ParsedQueryModification[];
/**
* @constructor
* @param definition The details of the handler.
* @param git The Git service.
*/
public constructor(
private readonly definition: HandlerDefinition,
private readonly git: Git
) {
this.settings = new Settings();
if ('private' in definition) {
this.server = new RemoteServer(() => this.settings.getServers(definition.private));
} else {
this.server = new RemoteServer(definition.server);
}
this.settingsKeys = definition.settingsKeys;
this.urlTemplate = parseTemplate(definition.url);
this.selectionTemplate = parseTemplate(definition.selection);
this.queryModifications =
definition.query?.map((x) => ({
pattern: new RegExp(x.pattern),
key: x.key,
value: x.value
})) ?? [];
this.reverse = {
// The regular expression can be defined as an array of strings.
// This is just a convenience to allow the pattern to be
// split over multiple lines in the JSON definition file.
// Join all of the parts together to create the complete pattern.
pattern: new RegExp(
typeof definition.reverse.pattern === 'string'
? definition.reverse.pattern
: definition.reverse.pattern.join('')
),
file: parseTemplate(definition.reverse.file),
server: {
http: parseTemplate(definition.reverse.server.http),
ssh: parseTemplate(definition.reverse.server.ssh),
web: definition.reverse.server.web
? parseTemplate(definition.reverse.server.web)
: undefined
},
selection: {
startLine: parseTemplate(definition.reverse.selection.startLine),
endLine: parseTemplate(definition.reverse.selection.endLine),
startColumn: parseTemplate(definition.reverse.selection.startColumn),
endColumn: parseTemplate(definition.reverse.selection.endColumn)
}
};
}
/**
* The name of the handler.
*/
public get name(): string {
return this.definition.name;
}
/**
* Determines whether this handler can generate links for the given remote URL.
*
* @param remoteUrl The remote URL to check.
* @returns True if this handler handles the given remote URL; otherwise, false.
*/
public handlesRemoteUrl(remoteUrl: string): boolean {
return this.server.matchRemoteUrl(remoteUrl) !== undefined;
}
/**
* Creates a link for the specified file.
*
* @param repository The repository that the file is in.
* @param remoteUrl The remote URL that was matched to this handler.
* @param file The details of the file.
* @param options The options for creating the link.
* @returns Information about the URL.
*/
public async createUrl(
repository: RepositoryWithRemote,
remoteUrl: string,
file: FileInfo,
options: LinkOptions
): Promise<CreateUrlResult> {
let address: StaticServer;
let type: LinkType;
let ref: string;
let url: string;
let data: UrlData;
let relativePath: string;
let selection: string;
// If a link type wasn't specified, then we'll use
// the default type that's defined in the settings.
if ('preset' in options.target) {
type = options.target.preset ?? this.settings.getDefaultLinkType();
ref = await this.getRef(type, repository);
} else {
if (options.target.type === 'branch') {
type = 'branch';
ref =
this.definition.branchRef === 'abbreviated'
? options.target.ref.abbreviated
: options.target.ref.symbolic;
} else if (options.target.type === 'tag') {
type = 'tag';
ref = options.target.ref.abbreviated;
} else {
type = 'commit';
ref = this.settings.getUseShortHash()
? options.target.ref.abbreviated
: options.target.ref.symbolic;
}
}
address = this.getAddress(remoteUrl);
relativePath = await this.getRelativePath(repository.root.fsPath, file.uri.fsPath);
data = {
base: address.web ?? address.http,
repository: this.getRepositoryPath(remoteUrl, address),
ref,
commit: await this.getRef('commit', repository),
file: relativePath,
type: type === 'commit' ? 'commit' : type === 'tag' ? 'tag' : 'branch',
sshUserSpecification: getSshUserSpecification(remoteUrl),
...file.selection
};
if (this.settingsKeys) {
for (let key of this.settingsKeys) {
data[key] = this.settings.getHandlerSetting(key);
}
}
url = this.urlTemplate.render(data);
if (file.selection) {
selection = this.selectionTemplate.render(data);
url += selection;
} else {
selection = '';
}
url = this.applyModifications(
url,
this.queryModifications.filter((x) => x.pattern.test(file.uri.fsPath))
);
return { url, relativePath, selection };
}
/**
* Applies the given query string modifications to the URL.
*
* @param url The URL to modify.
* @param modifications The modifications to apply.
* @returns The modified URL.
*/
private applyModifications(url: string, modifications: ParsedQueryModification[]): string {
if (modifications.length > 0) {
let u: URL;
u = new URL(url);
for (let modification of modifications) {
u.searchParams.append(modification.key, modification.value);
}
url = u.toString();
}
return url;
}
/**
* Gets the server address for the given remote URL.
*
* @param remote The remote URL.
* @returns The server address.
*/
private getAddress(remote: string): StaticServer {
let address: StaticServer | undefined;
address = this.server.matchRemoteUrl(remote);
if (!address) {
throw new Error('Could not find a matching address.');
}
return this.normalizeServerUrls(address);
}
/**
* Normalizes the server URLs to make them consistent for use in the templates.
*
* @param address The server address to normalize.
* @returns The normalized server URLs.
*/
private normalizeServerUrls(address: StaticServer): StaticServer {
let http: string;
let ssh: string | undefined;
let web: string | undefined;
http = normalizeUrl(address.http);
ssh = address.ssh ? normalizeUrl(address.ssh) : undefined;
web = address.web ? normalizeUrl(address.web) : undefined;
return { http, ssh, web };
}
/**
* Gets the path to the repository at the given server address.
*
* @param remoteUrl The remote URL of the repository.
* @param address The address of the server.
* @returns The path to the repository.
*/
private getRepositoryPath(remoteUrl: string, address: StaticServer): string {
let repositoryPath: string;
remoteUrl = normalizeUrl(remoteUrl);
// Remove the server's address from the start of the URL.
// Note that the remote URL and both URLs in the server
// address have been normalized by this point.
if (remoteUrl.startsWith(address.http)) {
repositoryPath = remoteUrl.substring(address.http.length);
} else {
repositoryPath = address.ssh ? remoteUrl.substring(address.ssh.length) : '';
}
// The server address we matched against may not have ended
// with a slash (for HTTPS paths) or a colon (for SSH paths),
// which means the path might start with that. Trim that off now.
if (repositoryPath.length > 0) {
if (repositoryPath[0] === '/' || repositoryPath[0] === ':') {
repositoryPath = repositoryPath.substring(1);
}
}
if (repositoryPath.endsWith('.git')) {
repositoryPath = repositoryPath.substring(0, repositoryPath.length - 4);
}
return repositoryPath;
}
/**
* Gets the ref to use when creating the link.
*
* @param type The type of ref to get.
* @param repository The repository.
* @returns The ref to use.
*/
public async getRef(type: LinkType, repository: RepositoryWithRemote): Promise<string> {
switch (type) {
case 'branch':
return (
await this.git.exec(
repository.root,
'rev-parse',
this.getRevParseOutputArgument(),
'HEAD'
)
).trim();
case 'commit':
if (this.settings.getUseShortHash()) {
return (
await this.git.exec(repository.root, 'rev-parse', '--short', 'HEAD')
).trim();
} else {
return (await this.git.exec(repository.root, 'rev-parse', 'HEAD')).trim();
}
case 'tag':
return (
await this.git.exec(
repository.root,
'describe',
'--exact-match',
'--tags',
'HEAD'
)
).trim();
default:
// Use the default branch if one is specified in the settings; otherwise find the
// name of the default branch by getting the name of the "remote_name/HEAD" ref.
return (
this.settings.getDefaultBranch() ||
(await this.getDefaultRemoteBranch(repository))
);
}
}
/**
* Gets the name of the default branch in the remote.
*
* @param repository The repository.
* @returns The name of the default branch.
*/
private async getDefaultRemoteBranch(repository: RepositoryWithRemote): Promise<string> {
let branch: string;
try {
branch = (
await this.git.exec(
repository.root,
'rev-parse',
this.getRevParseOutputArgument(),
`${repository.remote.name}/HEAD`
)
).trim();
} catch (ex) {
throw new NoRemoteHeadError(getErrorMessage(ex));
}
switch (this.definition.branchRef) {
case 'abbreviated':
// The branch name will be "remote_name/branch_name",
// but we only want the "branch_name" part.
return branch.slice(repository.remote.name.length + 1);
case 'symbolic':
// The branch name will be "refs/remotes/remote_name/branch_name",
// but we want it to be "refs/heads/branch_name".
return branch.replace(
new RegExp(`^refs\\/remotes\\/${this.escapeRegExp(repository.remote.name)}\\/`),
'refs/heads/'
);
default:
return branch;
}
}
/**
* Escapes a value that can then be used in a Regular Expression.
*
* @param value The value to escape.
* @returns The escaped value.
*/
private escapeRegExp(value: string): string {
return value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
}
/**
* Gets the argument to use with `git rev-parse` to specify the output.
*
* @returns The argument to use.
*/
private getRevParseOutputArgument(): string {
switch (this.definition.branchRef) {
case 'symbolic':
return '--symbolic-full-name';
default:
return '--abbrev-ref';
}
}
/**
* Gets the relative path from the specified directory to the specified file.
*
* @param from The directory to get the relative path from.
* @param to The file to get the relative path to.
* @returns The relative path of the file.
*/
private async getRelativePath(from: string, to: string): Promise<string> {
// If the file is a symbolic link, or is under a directory that's a
// symbolic link, then we want to resolve the path to the real file
// because the symbolic link won't be in the Git repository.
if (await this.isSymbolicLink(to, from)) {
try {
to = await fs.realpath(to);
// Getting the real path of the file resolves all symbolic links,
// which means if the repository is also under a symbolic link,
// then the new file path may no longer be under the root directory.
// We can fix this by also getting the real path of the root directory.
from = await fs.realpath(from);
} catch (ex) {
// Provide a nicer error message that
// explains what we were trying to do.
throw new Error(
`Unable to resolve the symbolic link '${to}' to a real path.\n${getErrorMessage(
ex
)}`
);
}
}
// Get the relative path, then normalize
// the separators to forward slashes.
return path.relative(from, to).replace(/\\/g, '/');
}
/**
* Determines whether the specified file is a symbolic link.
*
* @param filePath The path of the file to check.
* @param rootDirectory The path to the root of the repository.
* @returns True if the specified file is a symbolic link within the repository; otherwise, false.
*/
private async isSymbolicLink(filePath: string, rootDirectory: string): Promise<boolean> {
// Check if the file is a symbolic link. If it isn't, then walk up
// the tree to see if an ancestor directory is a symbolic link. Keep
// stepping up until we reach the root directory of the repository,
// because we only need to resolve symbolic links within the repository.
// If the entire repository is under a symbolic link, then we don't
// want to resolve paths to somewhere outside the repository.
while (filePath !== rootDirectory) {
let stats: Stats;
let parent: string;
try {
stats = await fs.lstat(filePath);
} catch {
// Assume that the path isn't a symbolic link.
return false;
}
if (stats.isSymbolicLink()) {
return true;
}
parent = path.dirname(filePath);
if (parent === filePath) {
// We can't go any higher, so the
// path cannot be a symbolic link.
return false;
}
filePath = parent;
}
return false;
}
/**
* Gets information about the given URL.
*
* @param webUrl The web interface URL to get the information from.
* @param strict Whether to require the URL to match the server address of the handler.
* @returns The URL information, or `undefined` if the information could not be determined.
*/
public getUrlInfo(webUrl: string, strict: boolean): UrlInfo | undefined {
let address: StaticServer | undefined;
let match: RegExpExecArray | null;
// See if the URL matches the server address for the handler.
address = this.server.matchWebUrl(webUrl);
// If we are performing a strict match, then the
// URL must match to this handler's server.
if (strict && !address) {
return undefined;
}
if (address) {
address = this.normalizeServerUrls(address);
}
match = this.reverse.pattern.exec(webUrl);
if (match) {
let data: FileData;
let file: string;
let server: Mutable<StaticServer>;
let selection: Partial<SelectedRange>;
data = {
match,
http: address?.http,
ssh: address?.ssh,
web: address?.web
};
file = this.reverse.file.render(data);
server = {
http: this.reverse.server.http.render(data),
ssh: this.reverse.server.ssh.render(data)
};
if (this.reverse.server.web) {
server.web = this.reverse.server.web.render(data);
}
selection = {
startLine: this.tryParseNumber(this.reverse.selection.startLine.render(data)),
endLine: this.tryParseNumber(this.reverse.selection.endLine?.render(data)),
startColumn: this.tryParseNumber(this.reverse.selection.startColumn?.render(data)),
endColumn: this.tryParseNumber(this.reverse.selection.endColumn?.render(data))
};
return { filePath: file, server, selection };
}
return undefined;
}
/**
* Attempts to parse the given value to a number.
*
* @param value The value to parse.
* @returns The value as a number, or `undefined` if the value could not be parsed.
*/
private tryParseNumber(value: string | undefined): number | undefined {
if (value !== undefined) {
let num: number;
num = parseInt(value, 10);
if (!isNaN(num)) {
return num;
}
}
return undefined;
}
}
/**
* Data that is provided to the templates to generate a link.
*/
interface UrlData {
/**
* The base URL of the server.
*/
readonly base: string;
/**
* The path to the repository on the server.
*/
readonly repository: string;
/**
* The type of link being generated.
*/
readonly type: 'branch' | 'commit' | 'tag';
/**
* The Git ref to generate the link to. This will be a branch name or commit hash depending on the link type.
*/
readonly ref: string;
/**
* The hash of the current commit.
*/
readonly commit: string;
/**
* The file to generate the link for.
*/
readonly file: string;
/**
* The one-based line number of the start of the selection, if a selection is being included in the link.
*/
readonly startLine?: number;
/**
* The one-based column number of the start of the selection, if a selection is being included in the link.
*/
readonly startColumn?: number;
/**
* The one-based line number of the end of the selection, if a selection is being included in the link.
*/
readonly endLine?: number;
/**
* The one-based column number of the end of the selection, if a selection is being included in the link.
*/
readonly endColumn?: number;
/**
* Additional handler-specific settings.
*/
[settingsKey: string]: unknown;
}
interface FileData {
readonly match: RegExpMatchArray;
readonly http?: string;
readonly ssh?: string;
readonly web?: string;
}
/**
* The parsed query modification for making modifications to the URL's query string.
*/
export interface ParsedQueryModification {
/**
* The regular expression to match against the file name.
*/
readonly pattern: RegExp;
/**
* The key to add to the query string when the pattern matches.
*/
readonly key: string;
/**
* The value to add to the query string when the pattern matches.
*/
readonly value: string;
}
/**
* The parsed settings for getting file information from a URL.
*/
interface ParsedReverseSettings {
/**
* The regular expression pattern to match against the URL.
*/
readonly pattern: RegExp;
/**
* The template to produce a file name.
*/
readonly file: ParsedTemplate;
/**
* The templates that provide the base remote URLs.
*/
readonly server: ParsedTemplates<ReverseServerSettings>;
/**
* The templates that provide the selection range.
*/
readonly selection: ParsedTemplates<ReverseSelectionSettings>;
}
/**
* Parsed templates.
*/
type ParsedTemplates<T> = { [K in keyof T]: ParsedTemplate };
/**
* Information about the URL that was created.
*/
export interface CreateUrlResult {
/**
* The full URL.
*/
readonly url: string;
/**
* The path of the file used in the URL, relative to the root of the repository.
*/
readonly relativePath: string;
/**
* The selection that was appended to the URL.
*/
readonly selection: string;
}