Ghost/core/server/utils/packages/parse-package-json.js
Hannah Wolfe c70fbc2c7e 🎨 Collect & simplify package utils (#8080)
closes #8056

🎨 Collect together the package-related utils
- read directory actually reads a directory of packages
- parse package json is very tighly related to this

🎨 Move filterPaths -> packages.filterPackages
- this function is related to packages, not settings
- move the function to the new utils/packages
- add 100% test coverage

🎨 Simplify filterPackages code
🎨 Simplify reading of packages & themes
- This massively reduces all the complex code in the read packages & themes utils
- Added full test coverage

🎨 Improve & clarify active prop in filterPackages
- active is returned from API endpoints to combine data from multiple sources
- see https://github.com/TryGhost/Ghost/pull/8064#discussion_r103514810

🎨 Better error handling
🔥 Temporarily remove custom error templates
- we will reimplement this later when we have got a better concept of loading the active theme in place
- refs #8079
2017-03-01 14:09:31 +01:00

56 lines
1.5 KiB
JavaScript

/**
* Dependencies
*/
var Promise = require('bluebird'),
fs = require('fs'),
i18n = require('../../i18n'),
readFile = Promise.promisify(fs.readFile);
/**
* Parse package.json and validate it has
* all the required fields
*/
function parsePackageJson(path) {
return readFile(path)
.catch(function () {
var err = new Error(i18n.t('errors.utils.parsepackagejson.couldNotReadPackage'));
err.context = path;
return Promise.reject(err);
})
.then(function (source) {
var hasRequiredKeys, json, err;
try {
json = JSON.parse(source);
hasRequiredKeys = json.name && json.version;
if (!hasRequiredKeys) {
err = new Error(i18n.t('errors.utils.parsepackagejson.nameOrVersionMissing'));
err.context = path;
err.help = i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'http://docs.ghost.org/themes/'});
return Promise.reject(err);
}
return json;
} catch (parseError) {
err = new Error(i18n.t('errors.utils.parsepackagejson.themeFileIsMalformed'));
err.context = path;
err.help = i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'http://docs.ghost.org/themes/'});
return Promise.reject(err);
}
});
}
/**
* Expose `parsePackageJson`
*/
module.exports = parsePackageJson;