forked from TypeStrong/typedoc
/
GitHubPlugin.ts
302 lines (267 loc) · 8.92 KB
/
GitHubPlugin.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
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
import * as Path from "path";
import { spawnSync } from "child_process";
import type { SourceReference } from "../../models/sources/file";
import { Component, ConverterComponent } from "../components";
import { BasePath } from "../utils/base-path";
import { Converter } from "../converter";
import type { Context } from "../context";
import { BindOption } from "../../utils";
import { RepositoryType } from "../../models";
const TEN_MEGABYTES: number = 1024 * 10000;
function git(...args: string[]) {
return spawnSync("git", args, {
encoding: "utf-8",
windowsHide: true,
maxBuffer: TEN_MEGABYTES,
});
}
/**
* Stores data of a repository.
*/
export class Repository {
/**
* The root path of this repository.
*/
path: string;
/**
* The name of the branch this repository is on right now.
*/
branch: string;
/**
* A list of all files tracked by the repository.
*/
files: string[] = [];
/**
* The user/organization name of this repository on GitHub.
*/
user?: string;
/**
* The project name of this repository on GitHub.
*/
project?: string;
/**
* The hostname for this GitHub or Bitbucket project.
*
* Defaults to: `github.com` (for normal, public GitHub instance projects)
*
* Or the hostname for an enterprise version of GitHub, e.g. `github.acme.com`
* (if found as a match in the list of git remotes).
*/
hostname = "github.com";
/**
* Whether this is a GitHub or Bitbucket repository.
*/
type: RepositoryType = RepositoryType.GitHub;
/**
* Create a new Repository instance.
*
* @param path The root path of the repository.
*/
constructor(path: string, gitRevision: string, repoLinks: string[]) {
this.path = path;
this.branch = gitRevision || "master";
for (let i = 0, c = repoLinks.length; i < c; i++) {
let match =
/(github(?:\.[a-z]+)*\.[a-z]{2,})[:/]([^/]+)\/(.*)/.exec(
repoLinks[i]
);
if (!match) {
match = /(bitbucket.org)[:/]([^/]+)\/(.*)/.exec(repoLinks[i]);
}
if (match) {
this.hostname = match[1];
this.user = match[2];
this.project = match[3];
if (this.project.substr(-4) === ".git") {
this.project = this.project.substr(
0,
this.project.length - 4
);
}
break;
}
}
if (this.hostname.includes("bitbucket.org"))
this.type = RepositoryType.Bitbucket;
else this.type = RepositoryType.GitHub;
let out = git("-C", path, "ls-files");
if (out.status === 0) {
out.stdout.split("\n").forEach((file) => {
if (file !== "") {
this.files.push(BasePath.normalize(path + "/" + file));
}
});
}
if (!gitRevision) {
out = git("-C", path, "rev-parse", "--short", "HEAD");
if (out.status === 0) {
this.branch = out.stdout.replace("\n", "");
}
}
}
/**
* Check whether the given file is tracked by this repository.
*
* @param fileName The name of the file to test for.
* @returns TRUE when the file is part of the repository, otherwise FALSE.
*/
contains(fileName: string): boolean {
return this.files.includes(fileName);
}
/**
* 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): string | undefined {
if (!this.user || !this.project || !this.contains(fileName)) {
return;
}
return [
`https://${this.hostname}`,
this.user,
this.project,
this.type === "github" ? "blob" : "src",
this.branch,
fileName.substr(this.path.length + 1),
].join("/");
}
/**
* 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 Repository}.
*
* @param path The potential repository root.
* @returns A new instance of {@link Repository} or undefined.
*/
static tryCreateRepository(
path: string,
gitRevision: string,
gitRemote: string
): Repository | undefined {
const out = git("-C", path, "rev-parse", "--show-toplevel");
const remotesOutput = git("-C", path, "remote", "get-url", gitRemote);
if (out.status !== 0 || remotesOutput.status !== 0) {
return;
}
return new Repository(
BasePath.normalize(out.stdout.replace("\n", "")),
gitRevision,
remotesOutput.stdout.split("\n")
);
}
static getLineNumberAnchor(
lineNumber: number,
repositoryType: RepositoryType | undefined
): string {
switch (repositoryType) {
default:
case RepositoryType.GitHub:
return "L" + lineNumber;
case RepositoryType.Bitbucket:
return "lines-" + lineNumber;
}
}
}
/**
* A handler that watches for repositories with GitHub origin and links
* their source files to the related GitHub pages.
*/
@Component({ name: "git-hub" })
export class GitHubPlugin extends ConverterComponent {
/**
* List of known repositories.
*/
private repositories: { [path: string]: Repository } = {};
/**
* List of paths known to be not under git control.
*/
private ignoredPaths: string[] = [];
@BindOption("gitRevision")
readonly gitRevision!: string;
@BindOption("gitRemote")
readonly gitRemote!: string;
/**
* Create a new GitHubHandler instance.
*
* @param converter The converter this plugin should be attached to.
*/
override initialize() {
if (git("--version").status === 0) {
this.listenTo(
this.owner,
Converter.EVENT_RESOLVE_END,
this.onEndResolve
);
}
}
/**
* Check whether the given file is placed inside a repository.
*
* @param fileName The name of the file a repository should be looked for.
* @returns The found repository info or undefined.
*/
private getRepository(fileName: string): Repository | undefined {
// Check for known non-repositories
const dirName = Path.dirname(fileName);
for (let i = 0, c = this.ignoredPaths.length; i < c; i++) {
if (this.ignoredPaths[i] === dirName) {
return;
}
}
// Check for known repositories
for (const path of Object.keys(this.repositories)) {
if (fileName.substr(0, path.length).toLowerCase() === path) {
return this.repositories[path];
}
}
// Try to create a new repository
const repository = Repository.tryCreateRepository(
dirName,
this.gitRevision,
this.gitRemote
);
if (repository) {
this.repositories[repository.path.toLowerCase()] = repository;
return repository;
}
// No repository found, add path to ignored paths
const segments = dirName.split("/");
for (let i = segments.length; i > 0; i--) {
this.ignoredPaths.push(segments.slice(0, i).join("/"));
}
}
/**
* Triggered when the converter has finished resolving a project.
*
* @param context The context object describing the current state the converter is in.
*/
private onEndResolve(context: Context) {
const project = context.project;
project.files.forEach((sourceFile) => {
const repository = this.getRepository(sourceFile.fullFileName);
if (repository) {
sourceFile.url = repository.getURL(sourceFile.fullFileName);
sourceFile.repositoryType = repository.type;
}
});
for (const key in project.reflections) {
const reflection = project.reflections[key];
if (reflection.sources) {
reflection.sources.forEach((source: SourceReference) => {
if (source.file && source.file.url) {
source.url =
source.file.url +
"#" +
Repository.getLineNumberAnchor(
source.line,
source.file.repositoryType
);
}
});
}
}
}
}