forked from remarkjs/remark-github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
403 lines (356 loc) · 9.86 KB
/
index.js
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
/**
* @typedef {import('mdast').Root} Root
*
* @typedef Options
* Configuration.
* @property {boolean} [mentionStrong=true]
* Wrap mentions in `<strong>`, true by default.
* This makes them render more like how GitHub styles them.
* But GitHub itself uses CSS instead of a strong.
* @property {string} [repository]
* Repository to link against.
*/
import {visit} from 'unist-util-visit'
import {toString} from 'mdast-util-to-string'
import {findAndReplace} from 'mdast-util-find-and-replace'
// Previously, GitHub linked `@mention` and `@mentions` to their blog post about
// mentions (<https://github.com/blog/821>).
// Since June 2019, and possibly earlier, they stopped linking those references.
const denyMention = new Set(['mention', 'mentions'])
// Denylist of SHAs that are also valid words.
//
// GitHub allows abbreviating SHAs up to 7 characters.
// These cases are ignored in text because they might just be ment as normal
// words.
// If you’d like these to link to their SHAs, use more than 7 characters.
//
// Generated by:
//
// ```sh
// egrep -i "^[a-f0-9]{7,}$" /usr/share/dict/words
// ```
//
// Added a couple forms of 6 character words in GH-20:
// <https://github.com/remarkjs/remark-github/issues/20>.
const denyHash = new Set([
'acceded',
'deedeed',
'defaced',
'effaced',
'fabaceae'
])
// Constants.
const minShaLength = 7
// Username may only contain alphanumeric characters or single hyphens, and
// cannot begin or end with a hyphen*.
//
// \* That is: until <https://github.com/remarkjs/remark-github/issues/13>.
const userGroup = '[\\da-z][-\\da-z]{0,38}'
const projectGroup = '(?:\\.git[\\w-]|\\.(?!git)|[\\w-])+'
const repoGroup = '(' + userGroup + ')\\/(' + projectGroup + ')'
const linkRegex = new RegExp(
'^https?:\\/\\/github\\.com\\/' +
repoGroup +
'\\/(commit|compare|issues|pull)\\/([a-f\\d]+(?:\\.{3}[a-f\\d]+)?\\/?(?=[#?]|$))',
'i'
)
const repoRegex = new RegExp(
'(?:^|/(?:repos/)?)' + repoGroup + '(?=\\.git|[\\/#@]|$)',
'i'
)
const referenceRegex = new RegExp(
'(' +
userGroup +
')(?:\\/(' +
projectGroup +
'))?(?:#([1-9]\\d*)|@([a-f\\d]{7,40}))',
'gi'
)
const mentionRegex = new RegExp(
'@(' + userGroup + '(?:\\/' + userGroup + ')?)',
'gi'
)
/**
* Plugin to enable, disable, and ignore messages.
*
* @type {import('unified').Plugin<[Options?]|void[], Root>}
*/
export default function remarkGithub(options = {}) {
/**
* @typedef {import('mdast').StaticPhrasingContent} StaticPhrasingContent
* @typedef {import('mdast-util-find-and-replace').ReplaceFunction} ReplaceFunction
* @typedef {import('type-fest').PackageJson} PackageJson
* @typedef {{input: string, index: number}} Match
*/
let repository = options.repository
/** @type {PackageJson|undefined} */
let pkg
// Parse the URL: See the tests for all possible kinds.
const repositoryMatch = repoRegex.exec(repository || '')
if (!repositoryMatch) {
throw new Error('Missing `repository` field in `options`')
}
const repositoryInfo = {user: repositoryMatch[1], project: repositoryMatch[2]}
return (tree) => {
findAndReplace(
tree,
[
[referenceRegex, replaceReference],
[mentionRegex, replaceMention],
[/(?:#|\bgh-)([1-9]\d*)/gi, replaceIssue],
[/\b([a-f\d]{7,40})\.{3}([a-f\d]{7,40})\b/gi, replaceHashRange],
[/\b[a-f\d]{7,40}\b/gi, replaceHash]
],
{ignore: ['link', 'linkReference']}
)
visit(tree, 'link', (node) => {
const link = parse(node)
if (!link) {
return
}
const comment = link.comment ? ' (comment)' : ''
/** @type {string} */
let base
if (
link.project !== repositoryInfo.project ||
// Compare page uses full `user/project` for forks.
(link.page === 'compare' && link.user !== repositoryInfo.user)
) {
base = link.user + '/' + link.project
} else if (link.user === repositoryInfo.user) {
base = ''
} else {
base = link.user
}
/** @type {StaticPhrasingContent[]} */
const children = []
if (link.page === 'issues' || link.page === 'pull') {
base += '#'
children.push({
type: 'text',
value: base + link.reference + comment
})
} else {
if (base) {
children.push({type: 'text', value: base + '@'})
}
children.push({type: 'inlineCode', value: link.reference})
if (link.comment) {
children.push({type: 'text', value: comment})
}
}
node.children = children
})
}
/**
* @type {ReplaceFunction}
* @param {string} value
* @param {string} username
* @param {Match} match
*/
function replaceMention(value, username, match) {
if (
/[\w`]/.test(match.input.charAt(match.index - 1)) ||
/[/\w`]/.test(match.input.charAt(match.index + value.length)) ||
denyMention.has(username)
) {
return false
}
/** @type {StaticPhrasingContent} */
let node = {type: 'text', value}
if (options.mentionStrong !== false) {
node = {type: 'strong', children: [node]}
}
return {
type: 'link',
title: null,
url: 'https://github.com/' + username,
children: [node]
}
}
/**
* @type {ReplaceFunction}
* @param {string} value
* @param {string} no
* @param {Match} match
*/
function replaceIssue(value, no, match) {
if (
/\w/.test(match.input.charAt(match.index - 1)) ||
/\w/.test(match.input.charAt(match.index + value.length))
) {
return false
}
return {
type: 'link',
title: null,
url:
'https://github.com/' +
repositoryInfo.user +
'/' +
repositoryInfo.project +
'/issues/' +
no,
children: [{type: 'text', value}]
}
}
/**
* @type {ReplaceFunction}
* @param {string} value
* @param {string} a
* @param {string} b
* @param {Match} match
*/
function replaceHashRange(value, a, b, match) {
if (
/[^\t\n\r (@[{]/.test(match.input.charAt(match.index - 1)) ||
/\w/.test(match.input.charAt(match.index + value.length)) ||
denyHash.has(value)
) {
return false
}
return {
type: 'link',
title: null,
url:
'https://github.com/' +
repositoryInfo.user +
'/' +
repositoryInfo.project +
'/compare/' +
value,
children: [{type: 'inlineCode', value: abbr(a) + '...' + abbr(b)}]
}
}
/**
* @type {ReplaceFunction}
* @param {string} value
* @param {Match} match
*/
function replaceHash(value, match) {
if (
/[^\t\n\r (@[{.]/.test(match.input.charAt(match.index - 1)) ||
// For some weird reason GH does link two dots, but not one 🤷♂️
(match.input.charAt(match.index - 1) === '.' &&
match.input.charAt(match.index - 2) !== '.') ||
/\w/.test(match.input.charAt(match.index + value.length)) ||
denyHash.has(value)
) {
return false
}
return {
type: 'link',
title: null,
url:
'https://github.com/' +
repositoryInfo.user +
'/' +
repositoryInfo.project +
'/commit/' +
value,
children: [{type: 'inlineCode', value: abbr(value)}]
}
}
/**
* @type {ReplaceFunction}
* @param {string} $0
* @param {string} user
* @param {string} project
* @param {string} no
* @param {string} sha
* @param {Match} match
*/
// eslint-disable-next-line max-params
function replaceReference($0, user, project, no, sha, match) {
let value = ''
if (
/[^\t\n\r (@[{]/.test(match.input.charAt(match.index - 1)) ||
/\w/.test(match.input.charAt(match.index + $0.length))
) {
return false
}
/** @type {StaticPhrasingContent[]} */
const nodes = []
if (user !== repositoryInfo.user) {
value += user
}
if (project && project !== repositoryInfo.project) {
value = user + '/' + project
}
if (no) {
value += '#' + no
} else {
value += '@'
nodes.push({type: 'inlineCode', value: abbr(sha)})
}
nodes.unshift({type: 'text', value})
return {
type: 'link',
title: null,
url:
'https://github.com/' +
user +
'/' +
(project || repositoryInfo.project) +
'/' +
(no ? 'issues' : 'commit') +
'/' +
(no || sha),
children: nodes
}
}
}
/**
* Abbreviate a SHA.
*
* @param {string} sha
* @returns {string}
*/
function abbr(sha) {
return sha.slice(0, minShaLength)
}
/**
* Parse a link and determine whether it links to GitHub.
*
* @param {import('mdast').Link} node
* @returns {{user: string, project: string, page: string, reference: string, comment: boolean}|undefined}
*/
function parse(node) {
const url = node.url || ''
const match = linkRegex.exec(url)
if (
// Not a proper URL.
!match ||
// Looks like formatting.
node.children.length !== 1 ||
node.children[0].type !== 'text' ||
toString(node) !== url ||
// SHAs can be min 4, max 40 characters.
(match[3] === 'commit' && (match[4].length < 4 || match[4].length > 40)) ||
// SHAs can be min 4, max 40 characters.
(match[3] === 'compare' &&
!/^[a-f\d]{4,40}\.{3}[a-f\d]{4,40}$/.test(match[4])) ||
// Issues / PRs are decimal only.
((match[3] === 'issues' || match[3] === 'pull') &&
/[a-f]/i.test(match[4])) ||
// Projects can be at most 99 characters.
match[2].length >= 100
) {
return
}
let reference = match[4]
if (match[3] === 'compare') {
const [base, compare] = reference.split('...')
reference = abbr(base) + '...' + abbr(compare)
} else {
reference = abbr(reference)
}
return {
user: match[1],
project: match[2],
page: match[3],
reference,
comment:
url.charAt(match[0].length) === '#' && match[0].length + 1 < url.length
}
}