1
1
mirror of https://github.com/primer/css.git synced 2024-11-10 16:07:25 +03:00
css/lib/add-bundle-meta.js
2019-02-12 11:30:13 -08:00

39 lines
955 B
JavaScript

const {existsSync} = require('fs')
const {dirname, join, resolve} = require('path')
const cache = {}
module.exports = function addBundleMeta(options = {}) {
const {namespace = 'data', log = noop} = options
return (files, metal, done) => {
const root = metal.source()
for (const [path, file] of Object.entries(files)) {
const bundle = getBundleRelativeTo(path, root)
log(`[meta] ${path} bundle: "${bundle}"`)
file[namespace].bundle = bundle
}
done()
}
}
function getBundleRelativeTo(file, root) {
let dir = join(root, dirname(file))
if (dir in cache) {
return cache[dir]
}
while (dir !== root) {
const indexPath = join(dir, 'index.scss')
if (existsSync(indexPath)) {
return (cache[dir] = getPathName(indexPath.substr(root.length + 1)))
}
dir = resolve(dir, '..')
}
return false
}
function getPathName(path) {
return dirname(path).replace(/\//g, '-')
}
function noop() {}