-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathlint-readme.js
75 lines (58 loc) · 1.94 KB
/
lint-readme.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
var fs = require('fs');
var path = require('path');
var util = require('util');
var MARKDOWN_SECTION_REGEXP = /^(#+) (.+)$/;
var NEWLINE_REGEXP = /\r?\n/;
var README_PATH = path.join(__dirname, '..', 'Readme.md');
var README_CONTENTS = fs.readFileSync(README_PATH, 'utf-8');
var TOC_SECTION_NAME = 'Table of Contents';
var currentSectionLevel = null;
var currentSectionName = null;
var currentToc = [];
var expectedToc = [];
var tocOffset = 0;
README_CONTENTS.split(NEWLINE_REGEXP).forEach(function (line, index) {
var match = MARKDOWN_SECTION_REGEXP.exec(line);
if (match) {
currentSectionLevel = match[1].length;
currentSectionName = match[2];
if (currentSectionName === TOC_SECTION_NAME) {
tocOffset = index;
}
if (currentSectionLevel > 1 && currentSectionName !== TOC_SECTION_NAME) {
expectedToc.push(util.format('%s- [%s](%s)',
repeat(' ', (currentSectionLevel - 2)), currentSectionName, toAnchor(currentSectionName)));
}
} else if (currentSectionName === TOC_SECTION_NAME) {
currentToc.push(line);
}
});
var index = 0;
if (currentToc[index++].length !== 0) {
expect((tocOffset + index), 'blank line', currentToc[index - 1]);
}
expectedToc.forEach(function (expectedLine) {
var currentLine = currentToc[index++] || '';
if (expectedLine !== currentLine) {
var currentIndex = currentToc.indexOf(expectedLine);
expect((tocOffset + index), ('"' + expectedLine + '"'), currentLine);
if (currentIndex !== -1) {
index = currentIndex + 1;
}
}
});
function expect (lineidx, message, line) {
console.log('Expected %s on line %d', message, (lineidx + 1));
console.log(' Got: %s', line);
process.exitCode = 1;
}
function repeat (str, num) {
var s = '';
for (var i = 0; i < num; i++) {
s += str;
}
return s;
}
function toAnchor (section) {
return '#' + section.toLowerCase().replace(/ /g, '-');
}