@interaktiv/mibuilder-core
Version:
Core libraries to interact with MiBuilder projects.
77 lines (58 loc) • 2.99 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.resolveConfigPath = resolveConfigPath;
var _path = _interopRequireDefault(require("path"));
var _dxl = require("@interaktiv/dxl");
var _mibuilderError = require("../mibuilder-error");
var _constants = require("./constants");
const isFile = async filePath => {
const pathExists = await (0, _dxl.exists)(filePath);
const pathStats = await (0, _dxl.stat)(filePath);
return pathExists && pathStats.isDirectory() === false;
};
async function resolveConfigPathByTraversing(pathToResolve) {
const mibuilderProjectJson = _path.default.resolve(pathToResolve, _constants.MIBUILDER_PROJECT_JSON);
try {
const foundProjectJson = await isFile(mibuilderProjectJson);
if (foundProjectJson) return mibuilderProjectJson;
} catch (err) {
if (err && err.code !== 'ENOENT') throw err;
} // This is the system root.
// We tried everything, config is nowhere to be found ¯\_(ツ)_/¯
if (pathToResolve === _path.default.dirname(pathToResolve)) {
return null;
} // Go up a level and try it again
return resolveConfigPathByTraversing(_path.default.dirname(pathToResolve));
}
async function resolveConfigPath(pathToResolve, cwd) {
if (_path.default.isAbsolute(cwd) === false) {
throw new _mibuilderError.MiBuilderError(`"cwd" must be an absolute path. cwd: ${cwd}`, 'InvalidCwd');
}
const absolutePath = _path.default.isAbsolute(pathToResolve) ? pathToResolve : _path.default.resolve(cwd, pathToResolve);
if (await isFile(absolutePath)) return absolutePath; // This is a guard against passing non existing path as a project/config,
// that will otherwise result in a very confusing situation.
// e.g.
// With a directory structure like this:
// my_project/
// packcage.json
//
// Passing a `my_project/some_directory_that_doesnt_exist` as a project
// name will resolve into a (possibly empty) `my_project/package.json` and
// try to run all tests it finds under `my_project` directory.
if ((await (0, _dxl.exists)(absolutePath)) === false) {
throw new _mibuilderError.MiBuilderError(`Can't find a root directory while resolving a config file path.\n` + `Provided path to resolve: ${pathToResolve}\n` + `cwd: ${cwd}`, 'InvalidRootDir');
}
const configPath = await resolveConfigPathByTraversing(absolutePath); // We tried everything, config is nowhere to be found ¯\_(ツ)_/¯
if (configPath == null) {
throw new _mibuilderError.MiBuilderError(`Could not find a config file based on provided values:
path: "${pathToResolve}"
cwd: "${cwd}"
Config paths must be specified by either a direct path to a config
file, or a path to a directory. If directory is given, MiBuilder will try to
traverse directory tree up, until it finds "${_constants.MIBUILDER_PROJECT_JSON}"\n`, 'InvalidProjectWorkspace');
}
return configPath;
}