-
Notifications
You must be signed in to change notification settings - Fork 0
/
index-clean.js
85 lines (65 loc) · 1.93 KB
/
index-clean.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
const path = require('path')
const fs = require('fs')
const { prettyCapitalize } = require('./pretty-capitalize')
const IGNORE_DIR_PATTERNS = [
'.git/',
'.vscode/',
'node_modules',
/\.md/
]
function shouldIgnore (path) {
for (let i = 0; i < IGNORE_DIR_PATTERNS.length; i++) {
if (path.search(IGNORE_DIR_PATTERNS[i]) !== -1) return true
}
return false
}
function getAllFiles (directory) {
const files = []
const dfs = (directory) => {
fs.readdirSync(directory).forEach(file => {
const absolute = path.join(directory, file)
if (shouldIgnore(absolute)) return
if (fs.statSync(absolute).isDirectory()) {
dfs(absolute)
} else {
files.push(absolute)
}
})
}
dfs(directory)
return files
}
const normalizeString = x => x.replace(/[^a-zA-Z0-9\s]/g, ' ').replace(/\s+/g, ' ').toLowerCase()
function findUniqueFilePath (simplifiedFilename, allFiles) {
let found = null
simplifiedFilename = normalizeString(simplifiedFilename)
for (let i = 0; i < allFiles.length; i++) {
const file = allFiles[i]
if (normalizeString(file).search(simplifiedFilename) !== -1) {
if (found != null) throw new Error(`Multiple matches for "${simplifiedFilename}": "${found}" and "${file}"`)
found = file
}
}
if (found == null) throw new Error(`Not found: ${simplifiedFilename}`)
return found
}
function cleanIndexData (data) {
const allFiles = getAllFiles('./')
return data.map(({ header, items }) => ({
header: prettyCapitalize(header),
items: items.map(({ title, files }) => {
const paths = files.map(f => findUniqueFilePath(f, allFiles))
if (paths.length !== (new Set(files).size)) {
throw new Error(`Files in "${header}" -> "${title}" are not unique`)
}
return {
title: prettyCapitalize(title),
files: paths.toSorted((a, b) => a.localeCompare(b))
}
})
}
))
}
module.exports = {
cleanIndexData
}