forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lint-files.js
1298 lines (1132 loc) · 48 KB
/
lint-files.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
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { fileURLToPath } from 'url'
import path from 'path'
import slash from 'slash'
import walk from 'walk-sync'
import { zip, groupBy } from 'lodash-es'
import yaml from 'js-yaml'
import revalidator from 'revalidator'
import { fromMarkdown } from 'mdast-util-from-markdown'
import { visit } from 'unist-util-visit'
import readFileAsync from '../../lib/readfile-async.js'
import frontmatter from '../../lib/frontmatter.js'
import languages from '../../lib/languages.js'
import { tags } from '../../lib/liquid-tags/extended-markdown.js'
import ghesReleaseNotesSchema from '../helpers/schemas/ghes-release-notes-schema.js'
import ghaeReleaseNotesSchema from '../helpers/schemas/ghae-release-notes-schema.js'
import learningTracksSchema from '../helpers/schemas/learning-tracks-schema.js'
import featureVersionsSchema from '../helpers/schemas/feature-versions-schema.js'
import renderContent from '../../lib/render-content/index.js'
import getApplicableVersions from '../../lib/get-applicable-versions.js'
import { execSync } from 'child_process'
import { allVersions } from '../../lib/all-versions.js'
import { supported, next, nextNext, deprecated } from '../../lib/enterprise-server-releases.js'
import { getLiquidConditionals } from '../../script/helpers/get-liquid-conditionals.js'
import allowedVersionOperators from '../../lib/liquid-tags/ifversion-supported-operators.js'
import semver from 'semver'
import { jest } from '@jest/globals'
import { getDiffFiles } from '../helpers/diff-files.js'
import loadSiteData from '../../lib/site-data.js'
jest.useFakeTimers('legacy')
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const enterpriseServerVersions = Object.keys(allVersions).filter((v) =>
v.startsWith('enterprise-server@')
)
const versionShortNames = Object.values(allVersions).map((v) => v.shortName)
const versionKeywords = versionShortNames.concat(['currentVersion', 'enterpriseServerReleases'])
const rootDir = path.join(__dirname, '../..')
const contentDir = path.join(rootDir, 'content')
const reusablesDir = path.join(rootDir, 'data/reusables')
const variablesDir = path.join(rootDir, 'data/variables')
const glossariesDir = path.join(rootDir, 'data/glossaries')
const ghesReleaseNotesDir = path.join(rootDir, 'data/release-notes/enterprise-server')
const ghaeReleaseNotesDir = path.join(rootDir, 'data/release-notes/github-ae')
const learningTracks = path.join(rootDir, 'data/learning-tracks')
const featureVersionsDir = path.join(rootDir, 'data/features')
const languageCodes = Object.keys(languages)
const versionShortNameExceptions = ['ghae-next', 'ghae-issue-']
// WARNING: Complicated RegExp below!
//
// Things matched by this RegExp:
// - [link text](link-url)
// - [link text] (link-url)
// - [link-definition-ref]: link-url
// - etc.
//
// Things intentionally NOT matched by this RegExp:
// - [link text](#link-url)
// - [link text] (#link-url)
// - [link-definition-ref]: #link-url
// - [link text](/link-url)
// - [link-definition-ref]: /link-url
// - [link text](https://link-url)
// - [link-definition-ref]: https://link-url
// - [link text](mailto:mail-url)
// - [link-definition-ref]: mailto:mail-url
// - [link text](tel:phone-url)
// - [link-definition-ref]: tel:phone-url
// - [link text]({{ site.data.variables.product_url }})
// - [link-definition-ref]: {{ site.data.variables.product_url }}
// - [link text][link-definition-ref]: other text
// - [link text][link-definition-ref] (other text)
// - etc.
//
const relativeArticleLinkRegex =
/(?=^|[^\]]\s*)\[[^\]]+\](?::\n?[ \t]+|\s*\()(?!\/|#|https?:\/\/|tel:|mailto:|\{[%{]\s*)[^)\s]+(?:(?:\s*[%}]\})?\)|\s+|$)/gm
// Things matched by this RegExp:
// - [link text](/en/github/blah)
// - [link text] (https://docs.github.com/ja/github/blah)
// - [link-definition-ref]: http://help.github.com/es/github/blah
// - etc.
//
// Things intentionally NOT matched by this RegExp:
// - [Node.js](https://nodejs.org/en/)
// - etc.
//
const languageLinkRegex = new RegExp(
`(?=^|[^\\]]\\s*)\\[[^\\]]+\\](?::\\n?[ \\t]+|\\s*\\()(?:(?:https?://(?:help|docs|developer)\\.github\\.com)?/(?:${languageCodes.join(
'|'
)})(?:/[^)\\s]*)?)(?:\\)|\\s+|$)`,
'gm'
)
// Things matched by this RegExp:
// - [link text](/enterprise/2.19/admin/blah)
// - [link text] (https://docs.github.com/enterprise/11.10.340/admin/blah)
// - [link-definition-ref]: http://help.github.com/enterprise/2.8/admin/blah
//
// Things intentionally NOT matched by this RegExp:
// - [link text](https://someservice.com/enterprise/1.0/blah)
// - [link text](/github/site-policy/enterprise/2.2/admin/blah)
const versionLinkRegEx =
/(?=^|[^\]]\s*)\[[^\]]+\](?::\n?[ \t]+|\s*\()(?:(?:https?:\/\/(?:help|docs|developer)\.github\.com)?\/enterprise\/\d+(\.\d+)+(?:\/[^)\s]*)?)(?:\)|\s+|$)/gm
// Things matched by this RegExp:
// - [link text](/early-access/github/blah)
// - [link text] (https://docs.github.com/early-access/github/blah)
// - [link-definition-ref]: http://help.github.com/early-access/github/blah
// - etc.
//
// Things intentionally NOT matched by this RegExp:
// - [Node.js](https://nodejs.org/early-access/)
// - etc.
//
const earlyAccessLinkRegex =
/(?=^|[^\]]\s*)\[[^\]]+\](?::\n?[ \t]+|\s*\()(?:(?:https?:\/\/(?:help|docs|developer)\.github\.com)?\/early-access(?:\/[^)\s]*)?)(?:\)|\s+|$)/gm
// - [link text](https://docs.github.com/github/blah)
// - [link text] (https://help.github.com/github/blah)
// - [link-definition-ref]: http://developer.github.com/v3/
// - [link text](//docs.github.com)
// - etc.
//
// Things intentionally NOT matched by this RegExp:
// - [link text](/github/blah)
// - [link text[(https://developer.github.com/changes/2018-02-22-protected-branches-required-signatures/)
// - etc.
//
const domainLinkRegex =
/(?=^|[^\]]\s*)\[[^\]]+\](?::\n?[ \t]+|\s*\()(?:https?:)?\/\/(?:help|docs|developer)\.github\.com(?!\/changes\/)[^)\s]*(?:\)|\s+|$)/gm
// Things matched by this RegExp:
// - ![image text](/assets/images/early-access/github/blah.gif)
// - ![image text] (https://docs.github.com/assets/images/early-access/github/blah.gif)
// - [image-definition-ref]: http://help.github.com/assets/images/early-access/github/blah.gif
// - [link text](/assets/images/early-access/github/blah.gif)
// - etc.
//
// Things intentionally NOT matched by this RegExp:
// - [Node.js](https://nodejs.org/assets/images/early-access/blah.gif)
// - etc.
//
const earlyAccessImageRegex =
/(?=^|[^\]]\s*)\[[^\]]+\](?::\n?[ \t]+|\s*\()(?:(?:https?:\/\/(?:help|docs|developer)\.github\.com)?\/assets\/images\/early-access(?:\/[^)\s]*)?)(?:\)|\s+|$)/gm
// Things matched by this RegExp:
// - ![image text](/assets/early-access/images/github/blah.gif)
// - ![image text] (https://docs.github.com/images/early-access/github/blah.gif)
// - [image-definition-ref]: http://help.github.com/assets/early-access/github/blah.gif
// - [link text](/early-access/assets/images/github/blah.gif)
// - [link text](/early-access/images/github/blah.gif)
// - etc.
//
// Things intentionally NOT matched by this RegExp:
// - [Node.js](https://nodejs.org/assets/early-access/images/blah.gif)
// - etc.
//
const badEarlyAccessImageRegex =
/(?=^|[^\]]\s*)\[[^\]]+\](?::\n?[ \t]+|\s*\()(?:(?:https?:\/\/(?:help|docs|developer)\.github\.com)?\/(?:(?:assets|images)\/early-access|early-access\/(?:assets|images))(?:\/[^)\s]*)?)(?:\)|\s+|$)/gm
// {{ site.data.example.pizza }}
const oldVariableRegex = /{{\s*?site\.data\..*?}}/g
// - {{ octicon-plus }}
// - {{ octicon-plus An example label }}
//
const oldOcticonRegex = /{{\s*?octicon-([a-z-]+)(\s[\w\s\d-]+)?\s*?}}/g
// - {{#note}}
// - {{/note}}
// - {{ #warning }}
// - {{ /pizza }}
//
const oldExtendedMarkdownRegex = /{{\s*?[#/][a-z-]+\s*?}}/g
// GitHub-owned actions (e.g. actions/checkout@v2) should use a reusable in examples.
// list:
// - actions/checkout@v2
// - actions/delete-package-versions@v2
// - actions/download-artifact@v2
// - actions/upload-artifact@v2
// - actions/github-script@v2
// - actions/setup-dotnet@v2
// - actions/setup-go@v2
// - actions/setup-java@v2
// - actions/setup-node@v2
// - actions/setup-python@v2
// - actions/stale@v2
// - actions/cache@v2
// - github/codeql-action/init@v2
// - github/codeql-action/analyze@v2
// - github/codeql-action/autobuild@v2
// - github/codeql-action/upload-sarif@v2
//
const literalActionInsteadOfReusableRegex =
/(actions\/(checkout|delete-package-versions|download-artifact|upload-artifact|github-script|setup-dotnet|setup-go|setup-java|setup-node|setup-python|stale|cache)|github\/codeql-action[/a-zA-Z-]*)@v\d+/g
// Strings in Liquid will always evaluate true _because_ they are strings; instead use unquoted variables, like {% if foo %}.
// - {% if "foo" %}
// - {% unless "bar" %}
const stringInLiquidRegex = /{% (?:if|ifversion|elseif|unless) (?:"|').+?%}/g
const relativeArticleLinkErrorText = 'Found unexpected relative article links:'
const languageLinkErrorText = 'Found article links with hard-coded language codes:'
const versionLinkErrorText = 'Found article links with hard-coded version numbers:'
const domainLinkErrorText = 'Found article links with hard-coded domain names:'
const earlyAccessLinkErrorText = 'Found article links leaking Early Access docs:'
const earlyAccessImageErrorText = 'Found article images/links leaking Early Access images:'
const badEarlyAccessImageErrorText =
'Found article images/links leaking incorrect Early Access images:'
const oldVariableErrorText =
'Found article uses old {{ site.data... }} syntax. Use {% data example.data.string %} instead!'
const oldOcticonErrorText =
'Found octicon variables with the old {{ octicon-name }} syntax. Use {% octicon "name" %} instead!'
const oldExtendedMarkdownErrorText =
'Found extended markdown tags with the old {{#note}} syntax. Use {% note %}/{% endnote %} instead!'
const stringInLiquidErrorText =
'Found Liquid conditionals that evaluate a string instead of a variable. Remove the quotes around the variable!'
const literalActionInsteadOfReusableErrorText =
'Found a literal mention of a GitHub-owned action. Instead, use the reusables for the action. e.g {% data reusables.actions.action-checkout %}'
const mdWalkOptions = {
globs: ['**/*.md'],
ignore: ['**/README.md'],
directories: false,
includeBasePath: true,
}
// Also test the "data/variables/" YAML files
const yamlWalkOptions = {
globs: ['**/*.yml'],
directories: false,
includeBasePath: true,
}
// different lint rules apply to different content types
let mdToLint,
ymlToLint,
ghesReleaseNotesToLint,
ghaeReleaseNotesToLint,
learningTracksToLint,
featureVersionsToLint
if (!process.env.TEST_TRANSLATION) {
// compile lists of all the files we want to lint
const contentMarkdownAbsPaths = walk(contentDir, mdWalkOptions).sort()
const contentMarkdownRelPaths = contentMarkdownAbsPaths.map((p) =>
slash(path.relative(rootDir, p))
)
const contentMarkdownTuples = zip(contentMarkdownRelPaths, contentMarkdownAbsPaths)
const reusableMarkdownAbsPaths = walk(reusablesDir, mdWalkOptions).sort()
const reusableMarkdownRelPaths = reusableMarkdownAbsPaths.map((p) =>
slash(path.relative(rootDir, p))
)
const reusableMarkdownTuples = zip(reusableMarkdownRelPaths, reusableMarkdownAbsPaths)
mdToLint = [...contentMarkdownTuples, ...reusableMarkdownTuples]
// data/variables
const variableYamlAbsPaths = walk(variablesDir, yamlWalkOptions).sort()
const variableYamlRelPaths = variableYamlAbsPaths.map((p) => slash(path.relative(rootDir, p)))
const variableYamlTuples = zip(variableYamlRelPaths, variableYamlAbsPaths)
// data/glossaries
const glossariesYamlAbsPaths = walk(glossariesDir, yamlWalkOptions).sort()
const glossariesYamlRelPaths = glossariesYamlAbsPaths.map((p) => slash(path.relative(rootDir, p)))
const glossariesYamlTuples = zip(glossariesYamlRelPaths, glossariesYamlAbsPaths)
ymlToLint = [...variableYamlTuples, ...glossariesYamlTuples]
// GHES release notes
const ghesReleaseNotesYamlAbsPaths = walk(ghesReleaseNotesDir, yamlWalkOptions).sort()
const ghesReleaseNotesYamlRelPaths = ghesReleaseNotesYamlAbsPaths.map((p) =>
slash(path.relative(rootDir, p))
)
ghesReleaseNotesToLint = zip(ghesReleaseNotesYamlRelPaths, ghesReleaseNotesYamlAbsPaths)
// GHAE release notes
const ghaeReleaseNotesYamlAbsPaths = walk(ghaeReleaseNotesDir, yamlWalkOptions).sort()
const ghaeReleaseNotesYamlRelPaths = ghaeReleaseNotesYamlAbsPaths.map((p) =>
slash(path.relative(rootDir, p))
)
ghaeReleaseNotesToLint = zip(ghaeReleaseNotesYamlRelPaths, ghaeReleaseNotesYamlAbsPaths)
// Learning tracks
const learningTracksYamlAbsPaths = walk(learningTracks, yamlWalkOptions).sort()
const learningTracksYamlRelPaths = learningTracksYamlAbsPaths.map((p) =>
slash(path.relative(rootDir, p))
)
learningTracksToLint = zip(learningTracksYamlRelPaths, learningTracksYamlAbsPaths)
// Feature versions
const featureVersionsYamlAbsPaths = walk(featureVersionsDir, yamlWalkOptions).sort()
const featureVersionsYamlRelPaths = featureVersionsYamlAbsPaths.map((p) =>
slash(path.relative(rootDir, p))
)
featureVersionsToLint = zip(featureVersionsYamlRelPaths, featureVersionsYamlAbsPaths)
} else {
// get all translated markdown or yaml files by comparing files changed to main branch
const changedFilesRelPaths = execSync(
'git -c diff.renameLimit=10000 diff --name-only origin/main',
{ maxBuffer: 1024 * 1024 * 100 }
)
.toString()
.split('\n')
.filter((p) => p.startsWith('translations') && (p.endsWith('.md') || p.endsWith('.yml')))
// If there are no changed files, there's nothing to lint: signal a successful termination.
if (changedFilesRelPaths.length === 0) process.exit(0)
console.log(`Found ${changedFilesRelPaths.length} translated files.`)
const {
mdRelPaths = [],
ymlRelPaths = [],
ghesReleaseNotesRelPaths = [],
ghaeReleaseNotesRelPaths = [],
learningTracksRelPaths = [],
featureVersionsRelPaths = [],
} = groupBy(changedFilesRelPaths, (path) => {
// separate the changed files to different groups
if (path.endsWith('README.md')) {
return 'throwAway'
} else if (path.endsWith('.md')) {
return 'mdRelPaths'
} else if (path.match(/\/data\/(variables|glossaries)\//i)) {
return 'ymlRelPaths'
} else if (path.match(/\/data\/release-notes\/enterprise-server/i)) {
return 'ghesReleaseNotesRelPaths'
} else if (path.match(/\/data\/release-notes\/github-ae/i)) {
return 'ghaeReleaseNotesRelPaths'
} else if (path.match(/\data\/learning-tracks/)) {
return 'learningTracksRelPaths'
} else if (path.match(/\data\/features/)) {
return 'featureVersionsRelPaths'
} else {
// we aren't linting the rest
return 'throwAway'
}
})
const [
mdTuples,
ymlTuples,
ghesReleaseNotesTuples,
ghaeReleaseNotesTuples,
learningTracksTuples,
featureVersionsTuples,
] = [
mdRelPaths,
ymlRelPaths,
ghesReleaseNotesRelPaths,
ghaeReleaseNotesRelPaths,
learningTracksRelPaths,
featureVersionsRelPaths,
].map((relPaths) => {
const absPaths = relPaths.map((p) => path.join(rootDir, p))
return zip(relPaths, absPaths)
})
mdToLint = mdTuples
ymlToLint = ymlTuples
ghesReleaseNotesToLint = ghesReleaseNotesTuples
ghaeReleaseNotesToLint = ghaeReleaseNotesTuples
learningTracksToLint = learningTracksTuples
featureVersionsToLint = featureVersionsTuples
}
function formatLinkError(message, links) {
return `${message}\n - ${links.join('\n - ')}`
}
// Returns `content` if its a string, or `content.description` if it can.
// Used for getting the nested `description` key in glossary files.
function getContent(content) {
if (typeof content === 'string') return content
if (typeof content.description === 'string') return content.description
return null
}
const diffFiles = getDiffFiles()
// If present, and not empty, leverage it because in most cases it's empty.
if (diffFiles.length > 0) {
// It's faster to do this once and then re-use over and over in the
// .filter() later on.
const only = new Set(
// If the environment variable encodes all the names
// with quotation marks, strip them.
// E.g. Turn `"foo" "bar"` into ['foo', 'bar']
// Note, this assumes no possible file contains a space.
diffFiles.map((name) => {
if (/^['"]/.test(name) && /['"]$/.test(name)) {
return name.slice(1, -1)
}
return name
})
)
const filterFiles = (tuples) =>
tuples.filter(
([relativePath, absolutePath]) => only.has(relativePath) || only.has(absolutePath)
)
mdToLint = filterFiles(mdToLint)
ymlToLint = filterFiles(ymlToLint)
ghesReleaseNotesToLint = filterFiles(ghesReleaseNotesToLint)
ghaeReleaseNotesToLint = filterFiles(ghaeReleaseNotesToLint)
learningTracksToLint = filterFiles(learningTracksToLint)
featureVersionsToLint = filterFiles(featureVersionsToLint)
}
if (
mdToLint.length +
ymlToLint.length +
ghesReleaseNotesToLint.length +
ghaeReleaseNotesToLint.length +
learningTracksToLint.length +
featureVersionsToLint.length <
1
) {
// With this in place, at least one `test()` is called and you don't
// get the `Your test suite must contain at least one test.` error
// from `jest`.
describe('deliberately do nothing', () => {
test('void', () => {})
})
}
describe('lint markdown content', () => {
if (mdToLint.length < 1) return
const siteData = loadSiteData()
describe.each(mdToLint)('%s', (markdownRelPath, markdownAbsPath) => {
let content,
ast,
links,
yamlScheduledWorkflows,
isHidden,
isEarlyAccess,
isSitePolicy,
hasExperimentalAlternative,
frontmatterErrors,
frontmatterData,
ifversionConditionals,
ifConditionals
beforeAll(async () => {
const fileContents = await readFileAsync(markdownAbsPath, 'utf8')
const { data, content: bodyContent, errors } = frontmatter(fileContents)
content = bodyContent
frontmatterErrors = errors
frontmatterData = data
ast = fromMarkdown(content)
isHidden = data.hidden === true
isEarlyAccess = markdownRelPath.split('/').includes('early-access')
isSitePolicy = markdownRelPath.split('/').includes('site-policy-deprecated')
hasExperimentalAlternative = data.hasExperimentalAlternative === true
links = []
visit(ast, ['link', 'definition'], (node) => {
links.push(node.url)
})
yamlScheduledWorkflows = []
visit(ast, 'code', (node) => {
if (
/ya?ml/.test(node.lang) &&
node.value.includes('schedule') &&
node.value.includes('cron')
) {
yamlScheduledWorkflows.push(node.value)
}
})
const context = { site: siteData.en.site }
// visit is not async-friendly so we need to do an async map to parse the YML snippets
yamlScheduledWorkflows = (
await Promise.all(
yamlScheduledWorkflows.map(async (snippet) => {
// If we don't parse the Liquid first, yaml loading chokes on {% raw %} tags
const rendered = await renderContent.liquid.parseAndRender(snippet, context)
const parsed = yaml.load(rendered)
return parsed.on.schedule
})
)
)
.flat()
.map((schedule) => schedule.cron)
ifversionConditionals = getLiquidConditionals(data, ['ifversion', 'elsif']).concat(
getLiquidConditionals(bodyContent, ['ifversion', 'elsif'])
)
ifConditionals = getLiquidConditionals(data, 'if').concat(
getLiquidConditionals(bodyContent, 'if')
)
})
// We need to support some non-Early Access hidden docs in Site Policy
test('hidden docs must be Early Access, Site Policy, or Experimental', async () => {
if (isHidden) {
expect(isEarlyAccess || isSitePolicy || hasExperimentalAlternative).toBe(true)
}
})
test('ifversion conditionals are valid in markdown', async () => {
const errors = validateIfversionConditionals(ifversionConditionals)
expect(errors.length, errors.join('\n')).toBe(0)
})
test('ifversion, not if, is used for versioning in markdown', async () => {
const ifsForVersioning = ifConditionals.filter((cond) =>
versionKeywords.some((keyword) => cond.includes(keyword))
)
const errorMessage = `Found ${
ifsForVersioning.length
} "if" conditionals used for versioning! Use "ifversion" instead.
${ifsForVersioning.join('\n')}`
expect(ifsForVersioning.length, errorMessage).toBe(0)
})
test('relative URLs must start with "/"', async () => {
const matches = links.filter((link) => {
if (
link.startsWith('http://') ||
link.startsWith('https://') ||
link.startsWith('tel:') ||
link.startsWith('mailto:') ||
link.startsWith('#') ||
link.startsWith('/')
)
return false
return true
})
const errorMessage = formatLinkError(relativeArticleLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('yaml snippets that include scheduled workflows must not run on the hour', async () => {
const hourlySchedules = yamlScheduledWorkflows.filter((schedule) => {
const hour = schedule.split(' ')[0]
// return any minute cron segments that equal 0, 00, 000, etc.
return !/[^0]/.test(hour)
})
expect(hourlySchedules).toEqual([])
})
// Note this only ensures that scheduled workflow snippets are unique _per Markdown file_
test('yaml snippets that include scheduled workflows run at unique times', () => {
expect(yamlScheduledWorkflows.length).toEqual(new Set(yamlScheduledWorkflows).size)
})
test('must not leak Early Access doc URLs', async () => {
// Only execute for docs that are NOT Early Access
if (!isEarlyAccess) {
const matches = content.match(earlyAccessLinkRegex) || []
const errorMessage = formatLinkError(earlyAccessLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
}
})
test('must not leak Early Access image URLs', async () => {
// Only execute for docs that are NOT Early Access
if (!isEarlyAccess) {
const matches = content.match(earlyAccessImageRegex) || []
const errorMessage = formatLinkError(earlyAccessImageErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
}
})
test('must have correctly formatted Early Access image URLs', async () => {
// Execute for ALL docs (not just Early Access) to ensure non-EA docs
// are not leaking incorrectly formatted EA image URLs
const matches = content.match(badEarlyAccessImageRegex) || []
const errorMessage = formatLinkError(badEarlyAccessImageErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
if (!process.env.TEST_TRANSLATION) {
test('does not use old site.data variable syntax', async () => {
const matches = content.match(oldVariableRegex) || []
const matchesWithExample = matches.map((match) => {
const example = match.replace(
/{{\s*?site\.data\.([a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]+)+)\s*?}}/g,
'{% data $1 %}'
)
return `${match} => ${example}`
})
const errorMessage = formatLinkError(oldVariableErrorText, matchesWithExample)
expect(matches.length, errorMessage).toBe(0)
})
test('does not use old octicon variable syntax', async () => {
const matches = content.match(oldOcticonRegex) || []
const errorMessage = formatLinkError(oldOcticonErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('does not use old extended markdown syntax', async () => {
Object.keys(tags).forEach((tag) => {
const reg = new RegExp(`{{\\s*?[#|/]${tag}`, 'g')
if (reg.test(content)) {
const matches = content.match(oldExtendedMarkdownRegex) || []
const tagMessage = oldExtendedMarkdownErrorText
.replace('{{#note}}', `{{#${tag}}}`)
.replace('{% note %}', `{% ${tag} %}`)
.replace('{% endnote %}', `{% end${tag} %}`)
const errorMessage = formatLinkError(tagMessage, matches)
expect(matches.length, errorMessage).toBe(0)
}
})
})
test('does not contain Liquid that evaluates strings (because they are always true)', async () => {
const matches = content.match(stringInLiquidRegex) || []
const errorMessage = formatLinkError(stringInLiquidErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('URLs must not contain a hard-coded language code', async () => {
const matches = links.filter((link) => {
return /\/(?:${languageCodes.join('|')})\//.test(link)
})
const errorMessage = formatLinkError(languageLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('URLs must not contain a hard-coded version number', async () => {
const initialMatches = content.match(versionLinkRegEx) || []
// Filter out some very specific false positive matches
const matches = initialMatches.filter(() => {
if (
markdownRelPath.endsWith('migrating-from-github-enterprise-1110x-to-2123.md') ||
markdownRelPath.endsWith('all-releases.md')
) {
return false
}
return true
})
const errorMessage = formatLinkError(versionLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('URLs must not contain a hard-coded domain name', async () => {
const initialMatches = content.match(domainLinkRegex) || []
// Filter out some very specific false positive matches
const matches = initialMatches.filter(() => {
if (markdownRelPath === 'content/admin/all-releases.md') {
return false
}
return true
})
const errorMessage = formatLinkError(domainLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
}
test('contains valid Liquid', async () => {
// If Liquid can't parse the file, it'll throw an error.
// For example, the following is invalid and will fail this test:
// {% if currentVersion ! "github-ae@latest" %}
expect(() => renderContent.liquid.parse(content)).not.toThrow()
})
if (!markdownRelPath.includes('data/reusables')) {
test('contains valid frontmatter', () => {
const errorMessage = frontmatterErrors
.map((error) => `- [${error.property}]: ${error.actual}, ${error.message}`)
.join('\n')
expect(frontmatterErrors.length, errorMessage).toBe(0)
})
test('frontmatter contains valid liquid', async () => {
const fmKeysWithLiquid = ['title', 'shortTitle', 'intro', 'product', 'permission'].filter(
(key) => Boolean(frontmatterData[key])
)
for (const key of fmKeysWithLiquid) {
expect(() => renderContent.liquid.parse(frontmatterData[key])).not.toThrow()
}
})
}
if (!markdownRelPath.includes('data/reusables/actions/action-')) {
test('must not contain literal GitHub-owned actions', async () => {
const matches = content.match(literalActionInsteadOfReusableRegex) || []
const errorMessage = formatLinkError(literalActionInsteadOfReusableErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
}
})
})
describe('lint yaml content', () => {
if (ymlToLint.length < 1) return
describe.each(ymlToLint)('%s', (yamlRelPath, yamlAbsPath) => {
let dictionary, isEarlyAccess, ifversionConditionals, ifConditionals
// This variable is used to determine if the file was parsed successfully.
// When `yaml.load()` fails to parse the file, it is overwritten with the error message.
// `false` is intentionally chosen since `null` and `undefined` are valid return values.
let dictionaryError = false
beforeAll(async () => {
const fileContents = await readFileAsync(yamlAbsPath, 'utf8')
try {
dictionary = yaml.load(fileContents, { filename: yamlRelPath })
} catch (error) {
dictionaryError = error
}
isEarlyAccess = yamlRelPath.split('/').includes('early-access')
ifversionConditionals = getLiquidConditionals(fileContents, ['ifversion', 'elsif'])
ifConditionals = getLiquidConditionals(fileContents, 'if')
})
test('it can be parsed as a single yaml document', () => {
expect(dictionaryError).toBe(false)
})
test('ifversion conditionals are valid in yaml', async () => {
const errors = validateIfversionConditionals(ifversionConditionals)
expect(errors.length, errors.join('\n')).toBe(0)
})
test('ifversion, not if, is used for versioning in markdown', async () => {
const ifsForVersioning = ifConditionals.filter((cond) =>
versionKeywords.some((keyword) => cond.includes(keyword))
)
const errorMessage = `Found ${
ifsForVersioning.length
} "if" conditionals used for versioning! Use "ifversion" instead.
${ifsForVersioning.join('\n')}`
expect(ifsForVersioning.length, errorMessage).toBe(0)
})
test('relative URLs must start with "/"', async () => {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(relativeArticleLinkRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(relativeArticleLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('must not leak Early Access doc URLs', async () => {
// Only execute for docs that are NOT Early Access
if (!isEarlyAccess) {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(earlyAccessLinkRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(earlyAccessLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
}
})
test('must not leak Early Access image URLs', async () => {
// Only execute for docs that are NOT Early Access
if (!isEarlyAccess) {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(earlyAccessImageRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(earlyAccessImageErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
}
})
test('must have correctly formatted Early Access image URLs', async () => {
// Execute for ALL docs (not just Early Access) to ensure non-EA docs
// are not leaking incorrectly formatted EA image URLs
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(badEarlyAccessImageRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(badEarlyAccessImageErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
if (!process.env.TEST_TRANSLATION) {
test('URLs must not contain a hard-coded language code', async () => {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(languageLinkRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(languageLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('URLs must not contain a hard-coded version number', async () => {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(versionLinkRegEx) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(versionLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('URLs must not contain a hard-coded domain name', async () => {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(domainLinkRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(domainLinkErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('does not use old site.data variable syntax', async () => {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(oldVariableRegex) || []
if (valMatches.length > 0) {
matches.push(
...valMatches.map((match) => {
const example = match.replace(
/{{\s*?site\.data\.([a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]+)+)\s*?}}/g,
'{% data $1 %}'
)
return `Key "${key}": ${match} => ${example}`
})
)
}
}
const errorMessage = formatLinkError(oldVariableErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('does not use old octicon variable syntax', async () => {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(oldOcticonRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(oldOcticonErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('does not use old extended markdown syntax', async () => {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(oldExtendedMarkdownRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(oldExtendedMarkdownErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
test('does not contain Liquid that evaluates strings (because they are always true)', async () => {
const matches = []
for (const [key, content] of Object.entries(dictionary)) {
const contentStr = getContent(content)
if (!contentStr) continue
const valMatches = contentStr.match(stringInLiquidRegex) || []
if (valMatches.length > 0) {
matches.push(...valMatches.map((match) => `Key "${key}": ${match}`))
}
}
const errorMessage = formatLinkError(stringInLiquidErrorText, matches)
expect(matches.length, errorMessage).toBe(0)
})
}
})
})
describe('lint GHES release notes', () => {
if (ghesReleaseNotesToLint.length < 1) return
describe.each(ghesReleaseNotesToLint)('%s', (yamlRelPath, yamlAbsPath) => {
let dictionary
let dictionaryError = false
beforeAll(async () => {
const fileContents = await readFileAsync(yamlAbsPath, 'utf8')
try {
dictionary = yaml.load(fileContents, { filename: yamlRelPath })
} catch (error) {
dictionaryError = error
}
})
it('can be parsed as a single yaml document', () => {
expect(dictionaryError).toBe(false)
})
it('matches the schema', () => {
const { errors } = revalidator.validate(dictionary, ghesReleaseNotesSchema)
const errorMessage = errors
.map((error) => `- [${error.property}]: ${error.actual}, ${error.message}`)
.join('\n')
expect(errors.length, errorMessage).toBe(0)
})
it('contains valid liquid', () => {
const { intro, sections } = dictionary
let toLint = { intro }
for (const key in sections) {
const section = sections[key]
const label = `sections.${key}`
section.forEach((part) => {
if (Array.isArray(part)) {
toLint = { ...toLint, ...{ [label]: section.join('\n') } }
} else {
for (const prop in section) {
toLint = { ...toLint, ...{ [`${label}.${prop}`]: section[prop] } }
}
}
})
}
for (const key in toLint) {
if (!toLint[key]) continue
expect(
() => renderContent.liquid.parse(toLint[key]),
`${key} contains invalid liquid`
).not.toThrow()