1
1
mirror of https://github.com/primer/css.git synced 2024-11-23 20:38:58 +03:00
css/lib/add-package-meta.js

45 lines
1.0 KiB
JavaScript
Raw Normal View History

const {existsSync} = require('fs')
const {dirname, join, resolve} = require('path')
const cache = {}
module.exports = function addPackageMeta(options = {}) {
const {fields, namespace = 'data', log = noop} = options
return (files, metal, done) => {
const root = metal.source()
for (const [path, file] of Object.entries(files)) {
2018-12-07 22:29:17 +03:00
const pkg = getPackageRelativeTo(path, root)
if (pkg) {
file[namespace].package = fields ? pluck(pkg, fields) : pkg
} else {
log('no package.json found relative to', path)
}
}
done()
}
}
2018-12-07 22:29:17 +03:00
function getPackageRelativeTo(file, root) {
let dir = join(root, dirname(file))
if (dir in cache) {
return cache[dir]
}
while (dir !== root) {
const pkgPath = join(dir, 'package.json')
if (existsSync(pkgPath)) {
return (cache[dir] = require(pkgPath))
}
dir = resolve(dir, '..')
}
return false
}
function pluck(data, fields) {
return fields.reduce((out, field) => {
out[field] = data[field]
return out
}, {})
}
function noop() {}