forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate-internal-links.js
More file actions
507 lines (463 loc) · 17.1 KB
/
Copy pathupdate-internal-links.js
File metadata and controls
507 lines (463 loc) · 17.1 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
import fs from 'fs'
import path from 'path'
import { visit } from 'unist-util-visit'
import { fromMarkdown } from 'mdast-util-from-markdown'
import { toMarkdown } from 'mdast-util-to-markdown'
import yaml from 'js-yaml'
import frontmatter from './read-frontmatter.js'
import {
getPathWithLanguage,
getPathWithoutLanguage,
getPathWithoutVersion,
getVersionStringFromPath,
} from './path-utils.js'
import loadRedirects from './redirects/precompile.js'
import patterns from './patterns.js'
import { loadUnversionedTree, loadPages, loadPageMap } from './page-data.js'
import getRedirect, { splitPathByLanguage } from './get-redirect.js'
import nonEnterpriseDefaultVersion from './non-enterprise-default-version.js'
import { deprecated } from './enterprise-server-releases.js'
function objectClone(obj) {
try {
return structuredClone(obj)
} catch {
// Need to polyfill for Node 16 folks
// Using `yaml.load(yaml.dump(...))` is safe enough because this
// data itself came from the Yaml deserializing in frontmatter().
return yaml.load(yaml.dump(obj))
}
}
// That magical string that can be turned into th actual title when
// we, at runtime, render out the links
const AUTOTITLE = 'AUTOTITLE'
const Options = {
setAutotitle: false,
fixHref: false,
verbose: false,
strict: false,
}
export async function updateInternalLinks(files, options = {}) {
const opts = Object.assign({}, Options, options)
const results = []
const unversionedTree = await loadUnversionedTree(['en'])
const pageList = await loadPages(unversionedTree, ['en'])
const pageMap = await loadPageMap(pageList)
const redirects = await loadRedirects(pageList)
const context = {
pages: pageMap,
redirects,
currentLanguage: 'en',
userLanguage: 'en',
}
for (const file of files) {
try {
results.push({
file,
...(await updateFile(file, context, opts)),
})
} catch (err) {
console.warn(`The file it tried to process on exception was: ${file}`)
throw err
}
}
return results
}
async function updateFile(file, context, opts) {
const rawContent = fs.readFileSync(file, 'utf8')
const { data, content } = frontmatter(rawContent)
// Since this function can process both `.md` and `.yml` files,
// when treating a `.md` file, the `data` from `frontmatter(rawContent)`
// is easy. But when dealing a file like `data/learning-tracks/foo.yml`
// then the the `frontmatter(rawContent).data` always becomes `{}`.
// And since the Yaml file might contain arrays of internal linked
// pathnames, we have to re-read it fully.
if (file.endsWith('.yml')) {
Object.assign(data, yaml.load(content))
}
let newContent = content
const ast = fromMarkdown(newContent)
const replacements = []
const warnings = []
// The day we know with confidence that everyone us on Node >=17,
// we can change this to use `structuredClone` without the polyfill
// technique.
const newData = objectClone(data)
const ANY = Symbol('any')
const IS_ARRAY = Symbol('is array')
// This configuration determines which nested things to bother looking
// into.
const HAS_LINKS = {
featuredLinks: ['gettingStarted', 'startHere', 'guideCards', 'popular'],
introLinks: ANY,
includeGuides: IS_ARRAY,
}
if (
file.split(path.sep).includes('data') &&
file.split(path.sep).includes('learning-tracks') &&
file.endsWith('.yml')
) {
// data/learning-tracks/**/*.yml files are different because the keys
// are abitrary but what they might all have in common is a key
// there called `guides`
for (const key of Object.keys(data)) {
HAS_LINKS[key] = ['guides']
}
}
for (const [key, seek] of Object.entries(HAS_LINKS)) {
if (!(key in data)) {
continue
}
try {
if (Array.isArray(data[key])) {
if ((Array.isArray(seek) && seek.includes(key)) || seek === IS_ARRAY || seek === ANY) {
const better = getNewFrontmatterLinkList(data[key], context, opts, file)
if (!equalArray(better, data[key])) {
newData[key] = better
}
}
} else {
for (const [group, thing] of Object.entries(data[key])) {
if (Array.isArray(thing)) {
if (
(Array.isArray(seek) && seek.includes(group)) ||
seek === IS_ARRAY ||
seek === ANY
) {
const better = getNewFrontmatterLinkList(thing, context, opts, file)
if (!equalArray(better, thing)) {
newData[key][group] = better
}
}
}
}
}
} catch (error) {
// When in strict mode, if it throws an error that stacktrace will
// bubble up to the CLI. And the CLI will mention which file it
// was processing when it failed. But we have a valuable piece of
// information here about which frontmatter key it was that failed.
console.warn(`The frontmatter key it processed and failed was '${key}'`)
throw error
}
}
const lineOffset = rawContent.replace(content, '').split(/\n/g).length - 1
visit(ast, matcher, (node) => {
const asMarkdown = toMarkdown(node).trim()
if (content.includes(asMarkdown)) {
// The title part of the link might be more Markdown.
// For example...
//
// [This *is* cool](/articles/link)
//
// In that case, for this link node, the title is the combined
// serialization of `node.children`. But `toMarkdown()` always appends
// `\n` to the serialized output.
// Now the title, of the above-mentioned example becomes 'This *is* cool'
// which is unlikely to attempt to be the documents title, that
// it links to.
const title = node.children.map((child) => toMarkdown(child).slice(0, -1)).join('')
let newTitle = title
let newHref = node.url
const hasQuotesAroundLink = content.includes(`"${asMarkdown}`)
if (opts.setAutotitle) {
if (hasQuotesAroundLink) {
/**
* Note! A lot of internal links are bullet points like:
*
* - [Creating a repository](/articles/create-a-repo)
* - [Forking a repository](/articles/fork-a-repo)
* or
* 1. [Set your username in Git](/github/getting-started-with-github/setting-your-username-in-git).
* 1. [Set your commit email address in Git](/articles/setting-your-commit-email-address).
*
* Perhaps we could recognize them as such an consider them
* matches anyway. In particular if the title is make up
* a leading capital letter any most rest in lower case.
*/
if (title !== AUTOTITLE) {
newTitle = AUTOTITLE
}
} else {
/**
* The Markdown link sometimes is written like this:
*
* ["This is the title](/foo/bar)."
*
* or...
*
* ["This is the title"](/foo/bar).
*/
if (node.children && node.children.length > 0 && node.children[0].value) {
if (singleStartingQuote(node.children[0].value)) {
const column = node.position.start.column
const line = node.position.start.line + lineOffset
warnings.push({
warning: 'Starts with a single " inside the text',
asMarkdown,
line,
column,
})
} else if (isSimpleQuote(node.children[0].value)) {
const column = node.position.start.column
const line = node.position.start.line + lineOffset
warnings.push({
warning: 'Starts and ends with a " inside the text',
asMarkdown,
line,
column,
})
}
}
}
}
if (opts.fixHref) {
const betterHref = getNewHref(node.url, context, opts, file)
// getNewHref() might return a deliberate `undefined` if the
// new href value could not be computed for some reason.
if (betterHref !== undefined) {
newHref = betterHref
}
}
const newAsMarkdown = `[${newTitle}](${newHref})`
if (asMarkdown !== newAsMarkdown) {
// Something can be improved!
const column = node.position.start.column
const line = node.position.start.line + lineOffset
replacements.push({
asMarkdown,
newAsMarkdown,
line,
column,
})
newContent = newContent.replace(asMarkdown, newAsMarkdown)
}
} else if (opts.verbose) {
console.warn(
`Unable to find link as Markdown ('${asMarkdown}') in the source content (${file})`
)
}
})
return {
data,
content,
rawContent,
newContent,
replacements,
warnings,
newData,
}
}
function matcher(node) {
if (node.type === 'link' && node.url) {
const { url } = node
if (url.startsWith('/') || url.startsWith('./')) {
// Sometimes there's a link to view the asset as a separate link.
// Skip these because they ultimately link to an actual Page.
if (url.startsWith('/assets') || url.startsWith('/public/')) {
return false
}
// If a link uses Liquid we can't process it. It would require full
// rendering which this script is not doing.
if (url.includes('{{') || url.includes('{%')) {
return false
}
// Sometimes we link to archived enterprise-server versions. These
// can never be updated because although they appear to be internal,
// they are, in a sense external. For example:
// See "[This old thing](/enterprise-server@3.1/some/page)".
// Skip these
const version = getVersionStringFromPath(url)
if (
version &&
version.startsWith('enterprise-server@') &&
deprecated.includes(version.replace('enterprise-server@', ''))
) {
return false
}
// Really old versions like `/enterprise/2.1` don't need to be
// corrected because they're deliberately pointing to archived
// versions.
if (patterns.getEnterpriseVersionNumber.test(url)) {
return false
}
return true
}
}
return false
}
function getNewFrontmatterLinkList(list, context, opts, file) {
/**
* The `list` is expected to all be strings. Sometimes they're like this:
*
* /search-github/searching-on-github/searching-for-repositories
*
* Sometimes they're like this:
*
* {% ifversion fpt or ghec or ghes > 3.4 %}/pages/getting-started-with-github-pages{% endif %}
*
* In the case of Liquid, we have to temporarily remove it to be able to
* test the path as a URL.
**/
const better = []
for (const entry of list) {
if (/{%\s*else\s*%}/.test(entry)) {
console.warn(`Skipping frontmatter link with {% else %} in it: ${entry}. (file: ${file})`)
better.push(entry)
continue
}
const pure = stripLiquid(entry)
let asURL = '/en'
if (!pure.startsWith('/')) {
asURL += '/'
}
asURL += pure
if (asURL in context.pages) {
better.push(entry)
} else {
const redirected = getRedirect(asURL, context)
if (redirected === undefined) {
if (opts.strict) {
throw new Error(
`Neither redirecting nor findable '${asURL}' in frontmatter link. (file: ${file})`
)
}
console.warn(
'WARNING: A frontmatter link appears to be broken. ' +
`Neither redirect or a findable page: ${pure}. (file: ${file})`
)
better.push(entry)
} else {
// Perhaps it just redirected to a specific version
const redirectedWithoutLanguage = getPathWithoutLanguage(redirected)
const asURLWithoutVersion = getPathWithoutVersion(redirectedWithoutLanguage)
if (asURLWithoutVersion === pure) {
better.push(entry)
} else {
better.push(entry.replace(pure, asURLWithoutVersion))
}
}
}
}
return better
}
const liquidStartRex = /^{%-?\s*ifversion .+?\s*%}/
const liquidEndRex = /{%-?\s*endif\s*-?%}$/
// Return
//
// /foo/bar
//
// if the text input was
//
// {% ifversion ghes%}/foo/bar{%endif %}
//
// And if no liquid, just return as is.
function stripLiquid(text) {
if (liquidStartRex.test(text) && liquidEndRex.test(text)) {
return text.replace(liquidStartRex, '').replace(liquidEndRex, '').trim()
} else if (text.includes('{')) {
throw new Error(`Unsupported Liquid in frontmatter link list (${text})`)
}
return text
}
function equalArray(arr1, arr2) {
return arr1.length === arr2.length && arr1.every((item, i) => item === arr2[i])
}
function getNewHref(href, context, opts, file) {
const { currentLanguage } = context
const parsed = new URL(href, 'https://docs.github.com')
const hash = parsed.hash
const search = parsed.search
const pure = parsed.pathname
let newHref = pure.replace(patterns.trailingSlash, '$1')
// Before testing if it redirects takes it somewhere, we temporarily
// pretend it's already prefixed for English (/en)
const [language, withoutLanguage] = splitPathByLanguage(newHref, currentLanguage)
if (withoutLanguage !== newHref) {
// It means the link already had a language in it
const msg = `Unable to cope with internal links with hardcoded language '${newHref}' (file: ${file})`
if (opts.strict) {
throw new Error(msg)
} else {
console.warn(`WARNING: ${msg}`)
return
}
}
const newHrefWithLanguage = getPathWithLanguage(withoutLanguage, language)
const redirected = getRedirect(newHrefWithLanguage, context)
// If it comes back as `undefined` it means it didn't need to be
// redirected, specifically.
// Optionally, we could skip this whole step of checking for completely
// broken internal links because other tools will later check that.
if (redirected === undefined) {
if (!context.pages[newHrefWithLanguage]) {
// If this happens, it's very possible that it's a broken link
const msg = `A link appears to be broken. Neither redirect or a findable page '${href}' (${file})`
if (opts.strict) {
throw new Error(msg)
} else {
console.warn(`WARNING: ${msg}`)
return
}
}
}
if (redirected) {
// The getRedirect() function will produce a final URL that the user
// can use, but that means it also injects the language in there.
// For updating the content statically, we don't want that.
// Note: It could be an idea to somehow tell getRedirect() to not
// bother but perhaps it adds unnecessarily complexity to a function that
// has to work perfectly for runtime.
const redirectedWithoutLanguage = getPathWithoutLanguage(redirected)
// Some paths can't be viewed in fre-pro-team so the getRedirect()
// function will inject the version that you're supposed to go to.
// For example `/enterprise/admin/guides/installation/configuring-a-hostname`
// redirects to `/enterprise-server@3.7/admin/configuration/configuring-...`
// (at the time of writing) which is good when you're actually clicking
// the link but not good when we're trying to update the source
// content.
// The `getPathWithoutVersion` function doesn't change the input if
// the URL passed doesn't appear to have a valid version in it already.
// I.e. `getPathWithLanguage('/get-started') === '/get-started``
// but `getPathWithLanguage('/enterprise-server@3.8/get-started') === '/get-started``
// But hang on, in some rare cases the content deliberately linked to
// a specific version. If that's the case, leave it like that.
// There's another exception! Some links have the `/free-pro-team@latest/`
// prefix. The `getRedirect()` will always remove that. If that's the case
// we always want respect that and put it back in.
if (withoutLanguage.includes(`/${nonEnterpriseDefaultVersion}/`)) {
newHref = `/${nonEnterpriseDefaultVersion}${redirectedWithoutLanguage}`
} else if (withoutLanguage.startsWith('/enterprise-server/')) {
const msg =
"Old /enterprise-server/ links that don't include a @version is no longer supported. " +
'If you see this, manually fix that link to use enterprise-server@latest.'
if (opts.strict) {
throw new Error(msg)
} else {
console.warn(msg)
return
}
} else if (withoutLanguage.startsWith('/enterprise-server@latest')) {
// getRedirect() will always replace `enterprise-server@latest` with
// whatever the latest number is. E.g. `enterprise-server@3.9`.
// But we have to "undo" that.
newHref = `/enterprise-server@latest${getPathWithoutVersion(redirectedWithoutLanguage)}`
} else if (getPathWithoutVersion(withoutLanguage) !== withoutLanguage) {
newHref = redirectedWithoutLanguage
} else {
newHref = getPathWithoutVersion(redirectedWithoutLanguage)
}
}
if (search) {
newHref += search
}
if (hash) {
newHref += hash
}
return newHref
}
function singleStartingQuote(text) {
return text.startsWith('"') && text.split('"').length === 2
}
function isSimpleQuote(text) {
return text.startsWith('"') && text.endsWith('"') && text.split('"').length === 3
}