forked from javascript-tutorial/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpugResolve.js
More file actions
62 lines (53 loc) · 1.53 KB
/
pugResolve.js
File metadata and controls
62 lines (53 loc) · 1.53 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
const fs = require('fs');
const path = require('path');
const lang = require('config').lang;
const config = require('config');
function tryPaths(roots, filename) {
let paths = [
`${filename}.${lang}.pug`,
`${filename}.pug`,
`${filename}/index.${lang}.pug`,
`${filename}/index.pug`,
];
for(let root of roots) {
for (let tryPath of paths) {
if (fs.existsSync(path.join(root, tryPath))) {
return path.join(root, tryPath);
}
}
}
return null;
}
function pugResolve(filename, source, loadOptions) {
filename = filename.replace(/\.pug$/, '');
// console.log("RESOLVE", filename, source);
if (filename[0] === '~') {
filename = filename.slice(1);
let paths = require.resolve.paths(filename);
let resolved = tryPaths(paths, filename);
if (!resolved) {
throw new Error(`Pug file ${filename} from ${source} not resolved`);
}
return resolved;
}
if (filename[0] === '/') {
let result = tryPaths([loadOptions.useAbsoluteTemplatePath ? '/' : loadOptions.basedir], filename);
if (!result) {
throw new Error(`Pug file ${filename} not resolved`);
}
return result;
}
let roots = [];
if (source) {
roots.push(path.dirname(source));
} else {
roots.push(config.projectRoot);
}
if (loadOptions && loadOptions.roots) roots.push(...loadOptions.roots);
let result = tryPaths(roots, filename);
if (!result) {
throw new Error(`Pug file ${filename} from ${source || 'code'} not resolved`);
}
return result;
}
module.exports = pugResolve;