-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathutils.js
More file actions
187 lines (174 loc) · 5.83 KB
/
Copy pathutils.js
File metadata and controls
187 lines (174 loc) · 5.83 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
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const yaml = require('js-yaml');
const toml = require('@iarna/toml');
const { EOL } = require('os');
module.exports = {
forEachPromise,
readDirRecSync,
getFirstExistingFileSync,
parseFileSync,
parseDataByFilePath,
parseMarkdownWithFrontMatter,
createLogger,
prettyUrl
};
/**
* Iterates over array items and invokes callback function for each of them.
* The callback must return a promise and is called with three parameters: array item,
* item index, array itself. Callbacks are invoked serially, such that callback for the
* following item will not be called until the promise returned from the previous callback
* is not fulfilled.
*
* @param {array} array
* @param {function} callback
* @param {object} [thisArg]
* @return {Promise<any>}
*/
function forEachPromise(array, callback, thisArg) {
return new Promise((resolve, reject) => {
let results = [];
function next(index) {
if (index < array.length) {
callback.call(thisArg, array[index], index, array).then(result => {
results[index] = result;
next(index + 1);
}).catch(error => {
reject(error);
});
} else {
resolve(results);
}
}
next(0);
});
}
function readDirRecSync(dir, options) {
let list = [];
const files = fs.readdirSync(dir);
_.forEach(files, file => {
const filePath = path.join(dir, file);
const stats = fs.statSync(filePath);
if (_.has(options, 'filter') && !options.filter(filePath, stats)) {
return;
}
if (stats.isDirectory()) {
list = list.concat(readDirRecSync(filePath, options));
} else if (stats.isFile()) {
list.push(filePath);
}
});
return list;
}
function getFirstExistingFileSync(fileNames, inputDir) {
return _.chain(fileNames)
.map(fileName => path.resolve(inputDir, fileName))
.find(filePath => fs.existsSync(filePath)).value();
}
function parseFileSync(filePath) {
let data = fs.readFileSync(filePath, 'utf8');
return parseDataByFilePath(data, filePath);
}
function parseDataByFilePath(string, filePath) {
const extension = path.extname(filePath).substring(1);
let data;
switch (extension) {
case 'yml':
case 'yaml':
data = yaml.safeLoad(string, {schema: yaml.JSON_SCHEMA});
break;
case 'json':
data = JSON.parse(string);
break;
case 'toml':
data = toml.parse(string);
break;
case 'md':
data = parseMarkdownWithFrontMatter(string);
break;
default:
throw new Error(`parseDataByFilePath error, extension '${extension}' of file ${filePath} is not supported`);
}
return data;
}
function parseMarkdownWithFrontMatter(string) {
let frontmatter = null;
let markdown = string;
let frontMatterTypes = [
{
type: 'yaml',
startDelimiter: `---${EOL}`,
endDelimiter: `${EOL}---`,
parse: (string) => yaml.safeLoad(string, {schema: yaml.JSON_SCHEMA})
},
{
type: 'toml',
startDelimiter: `+++${EOL}`,
endDelimiter: `${EOL}+++`,
parse: (string) => toml.parse(string)
},
{
type: 'json',
startDelimiter: `{${EOL}`,
endDelimiter: `${EOL}}`,
parse: (string) => JSON.parse(string)
}
];
_.forEach(frontMatterTypes, fmType => {
if (string.startsWith(fmType.startDelimiter)) {
let index = string.indexOf(fmType.endDelimiter);
if (index !== -1) {
// The end delimiter must be followed by EOF or by a new line (possibly preceded with spaces)
// For example ("." used for spaces):
// |---
// |title: Title
// |---...
// |
// |Markdown Content
// |
// "index" points to the beginning of the second "---"
// "endDelimEndIndex" points to the end of the second "---"
// "afterEndDelim" is everything after the second "---"
// "afterEndDelimMatch" is the matched "...\n" after the second "---"
// frontmatter will be: {title: "Title"}
// markdown will be "\nMarkdown Content\n" (the first \n after end delimiter is discarded)
let endDelimEndIndex = index + fmType.endDelimiter.length;
let afterEndDelim = string.substring(endDelimEndIndex);
let afterEndDelimMatch = afterEndDelim.match(/^\s*?(\n|$)/);
if (afterEndDelimMatch) {
let data = string.substring(fmType.startDelimiter.length, index);
frontmatter = fmType.parse(data);
markdown = afterEndDelim.substring(afterEndDelimMatch[0].length);
}
}
}
});
return {
frontmatter: frontmatter,
markdown: markdown
};
}
function createLogger(scope, transport) {
const levels = ['log', 'info', 'debug', 'error'];
const logger = transport || console;
const noop = () => {};
const obj = {};
levels.forEach((level) => {
obj[level] = (...args) => {
(logger[level] || noop)(`[${scope}]`, ...args);
}
});
return obj;
}
function prettyUrl(url) {
if (url.match(/(?:^|\/)index\.html?$/)) {
url = url.replace(/\/?index\.html?$/, '');
if (url === '') {
url = '/';
}
} else if (url.match(/\.html?$/)) {
url = url.replace(/\.html?$/, '');
}
return url;
}