/
repository.ts
201 lines (175 loc) · 5.78 KB
/
repository.ts
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
import { spawnSync } from "child_process";
import type { Logger } from "../../utils";
import { BasePath } from "../utils/base-path";
const TEN_MEGABYTES = 1024 * 10000;
function git(...args: string[]) {
return spawnSync("git", args, {
encoding: "utf-8",
windowsHide: true,
maxBuffer: TEN_MEGABYTES,
});
}
let haveGit: boolean;
export function gitIsInstalled() {
haveGit ??= git("--version").status === 0;
return haveGit;
}
export interface Repository {
getURL(fileName: string, line: number): string | undefined;
}
export class AssumedRepository implements Repository {
constructor(
readonly path: string,
readonly gitRevision: string,
readonly sourceLinkTemplate: string,
) {}
getURL(fileName: string, line: number): string | undefined {
const replacements = {
gitRevision: this.gitRevision,
"gitRevision:short": this.gitRevision.substring(0, 8),
path: fileName.substring(this.path.length + 1),
line,
};
return this.sourceLinkTemplate.replace(
/\{(gitRevision|gitRevision:short|path|line)\}/g,
(_, key) => replacements[key as never],
);
}
}
/**
* Stores data of a repository.
*/
export class GitRepository implements Repository {
/**
* The path of this repository on disk.
*/
path: string;
/**
* All files tracked by the repository.
*/
files = new Set<string>();
urlTemplate: string;
gitRevision: string;
/**
* Create a new Repository instance.
*
* @param path The root path of the repository.
*/
constructor(path: string, gitRevision: string, urlTemplate: string) {
this.path = path;
this.gitRevision = gitRevision;
this.urlTemplate = urlTemplate;
const out = git("-C", path, "ls-files");
if (out.status === 0) {
out.stdout.split("\n").forEach((file) => {
if (file !== "") {
this.files.add(BasePath.normalize(path + "/" + file));
}
});
}
}
/**
* Get the URL of the given file on GitHub or Bitbucket.
*
* @param fileName The file whose URL should be determined.
* @returns A URL pointing to the web preview of the given file or undefined.
*/
getURL(fileName: string, line: number): string | undefined {
if (!this.files.has(fileName)) {
return;
}
const replacements = {
gitRevision: this.gitRevision,
"gitRevision:short": this.gitRevision.substring(0, 8),
path: fileName.substring(this.path.length + 1),
line,
};
return this.urlTemplate.replace(
/\{(gitRevision|gitRevision:short|path|line)\}/g,
(_, key) => replacements[key as never],
);
}
/**
* Try to create a new repository instance.
*
* Checks whether the given path is the root of a valid repository and if so
* creates a new instance of {@link GitRepository}.
*
* @param path The potential repository root.
* @returns A new instance of {@link GitRepository} or undefined.
*/
static tryCreateRepository(
path: string,
sourceLinkTemplate: string,
gitRevision: string,
gitRemote: string,
logger: Logger,
): GitRepository | undefined {
const topLevel = git("-C", path, "rev-parse", "--show-toplevel");
if (topLevel.status !== 0) return;
gitRevision ||= git("-C", path, "rev-parse", "HEAD").stdout.trim();
if (!gitRevision) return; // Will only happen in a repo with no commits.
let urlTemplate: string | undefined;
if (sourceLinkTemplate) {
urlTemplate = sourceLinkTemplate;
} else {
const remotesOut = git("-C", path, "remote", "get-url", gitRemote);
if (remotesOut.status === 0) {
urlTemplate = guessSourceUrlTemplate(
remotesOut.stdout.split("\n"),
);
} else {
logger.warn(
`The provided git remote "${gitRemote}" was not valid. Source links will be broken.`,
);
}
}
if (!urlTemplate) return;
return new GitRepository(
BasePath.normalize(topLevel.stdout.replace("\n", "")),
gitRevision,
urlTemplate,
);
}
}
// Should have three capturing groups:
// 1. hostname
// 2. user
// 3. project
const repoExpressions = [
/(github(?!.us)(?:\.[a-z]+)*\.[a-z]{2,})[:/]([^/]+)\/(.*)/,
/(\w+\.githubprivate.com)[:/]([^/]+)\/(.*)/, // GitHub enterprise
/(\w+\.ghe.com)[:/]([^/]+)\/(.*)/, // GitHub enterprise
/(\w+\.github.us)[:/]([^/]+)\/(.*)/, // GitHub enterprise
/(bitbucket.org)[:/]([^/]+)\/(.*)/,
/(gitlab.com)[:/]([^/]+)\/(.*)/,
];
export function guessSourceUrlTemplate(remotes: string[]): string | undefined {
let hostname = "";
let user = "";
let project = "";
outer: for (const repoLink of remotes) {
for (const regex of repoExpressions) {
const match = regex.exec(repoLink);
if (match) {
hostname = match[1];
user = match[2];
project = match[3];
break outer;
}
}
}
if (!hostname) return;
if (project.endsWith(".git")) {
project = project.slice(0, -4);
}
let sourcePath = "blob";
let anchorPrefix = "L";
if (hostname.includes("gitlab")) {
sourcePath = "-/blob";
} else if (hostname.includes("bitbucket")) {
sourcePath = "src";
anchorPrefix = "lines-";
}
return `https://${hostname}/${user}/${project}/${sourcePath}/{gitRevision}/{path}#${anchorPrefix}{line}`;
}