-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a Pug plugin to allow multiple basedirs.
This will make it possible to cleanly separate Bedrock's templates from the user project templates. This is cherry-picked from usebedrock/bedrock#404.
- Loading branch information
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
/* | ||
* This is a Pug plugin to allow multiple basedirs. This is used to have Pug | ||
* templates in both Bedrock core and in a project that uses Bedrock. | ||
* | ||
* From https://github.com/pugjs/pug/issues/2499 and | ||
* https://github.com/gryphonmyers/pug-multiple-basedirs-plugin | ||
*/ | ||
|
||
const { accessSync, constants: {R_OK} } = require('fs'); | ||
const path = require('path'); | ||
|
||
const config = require('../discovery/config'); | ||
|
||
// The multiple basedirs are the user-defined basedir plus Bedrock's. Adding | ||
// bedrockDir allows to refer to Bedrock's core templates with the /core | ||
// prefix. Adding it at the end allows users to override core templates. | ||
const bedrockDir = path.join(__dirname, '../../'); | ||
const basedirs = [config.pug.basedir, bedrockDir]; | ||
|
||
const exists = filename => { | ||
try { | ||
accessSync(filename, R_OK); | ||
return true; | ||
} catch (err) { | ||
return false; | ||
} | ||
}; | ||
|
||
function MultipleBaseDirs() { | ||
return { | ||
name: 'multipleBasedirs', | ||
resolve(filename, source) { | ||
let out; | ||
|
||
if (filename[0] === '/') { | ||
filename = filename.substr(1); | ||
if (!basedirs.some(basedir => exists(out = path.resolve(basedir, filename)))) { | ||
throw new Error(`${filename} cannot be found in any basedir`); | ||
} | ||
} else { | ||
if (!source) { | ||
throw new Error('the "filename" option is required to use includes and extends with "relative" paths'); | ||
} | ||
|
||
out = path.resolve(path.dirname(source), filename); | ||
} | ||
|
||
return out; | ||
} | ||
}; | ||
} | ||
|
||
module.exports = MultipleBaseDirs; |