Debian Codegraph @

ncjsm/lib/resolve-root.js

raw
1 // Find root, either first upper or topmost
2
3 "use strict";
4
5 const ensureValue = require("type/value/ensure")
6 , deferred = require("deferred")
7 , stat = require("fs2/stat")
8 , { resolve, sep } = require("path")
9 , isPackageRoot = require("../is-package-root");
10
11 module.exports = function (path, searchTopMost) {
12 path = resolve(String(ensureValue(path)));
13 return stat(path)(stats => {
14 if (!stats.isDirectory()) throw new Error("Provided path is not a directory path");
15 const tokens = path.split(sep);
16 tokens.forEach((token, index) => {
17 if (!index) return;
18 tokens[index] = tokens[index - 1] + sep + token;
19 });
20 tokens[0] += sep;
21 if (!searchTopMost) tokens.reverse();
22 return deferred.find(tokens, dirPath => isPackageRoot(dirPath))(rootPath =>
23 rootPath === undefined ? null : rootPath
24 );
25 });
26 };