2018-12-07 10:40:06 +03:00
|
|
|
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)
|
2018-12-07 10:40:06 +03:00
|
|
|
if (pkg) {
|
|
|
|
file[namespace].package = fields ? pluck(pkg, fields) : pkg
|
|
|
|
} else {
|
|
|
|
log('no package.json found relative to', fullPath)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
done()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-07 22:29:17 +03:00
|
|
|
function getPackageRelativeTo(file, root) {
|
|
|
|
let dir = join(root, dirname(file))
|
2018-12-07 10:40:06 +03:00
|
|
|
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() {}
|