Skip to content

Instantly share code, notes, and snippets.

@stalniy
Created July 15, 2018 14:56
Show Gist options
  • Save stalniy/16ed46f4769a71c2d8cc2394306827fd to your computer and use it in GitHub Desktop.
Save stalniy/16ed46f4769a71c2d8cc2394306827fd to your computer and use it in GitHub Desktop.
Package.json dependency order resolution
const fs = require('fs')
const { promisify } = require('util')
const cache = {}
const readFile = path => cache[path] = cache[path] || JSON.parse(fs.readFileSync(path))
const readDir = promisify(fs.readdir)
const DEPS_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']
function isDependency(path, anotherPath) {
const details = readFile(`${path}/package.json`)
const anotherDetails = readFile(`${anotherPath}/package.json`)
return DEPS_FIELDS.some(field => anotherDetails[field] && anotherDetails[field][details.name])
}
async function resolve(folder) {
const items = await readDir(folder)
const packagesPath = items.filter(path => fs.lstatSync(`${folder}/${path}`).isDirectory())
const copy = packagesPath.slice(0)
const result = []
const insert = (path) => {
packagesPath
.filter((anotherPath) => {
return isDependency(`${folder}/${anotherPath}`, `${folder}/${path}`)
})
.forEach(insert)
if (!result.includes(path)) {
result.push(path)
const index = copy.indexOf(path)
index !== -1 && copy.splice(index, 1)
}
}
let path
while (path = copy.pop()) {
insert(path)
}
return result
}
resolve('../packages')
.then(items => console.log(items))
.catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment