@sanity-codegen/cli
Version:
CLI for sanity-codegen
50 lines (38 loc) • 1.54 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fileWalker = fileWalker;
var _fs = _interopRequireDefault(require("fs"));
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Note: @babel/register must be hooked prior to this file running because this
// resolving method uses `require.resolve`.
/**
* Given a starting point and a back up filename, this function will first check
* to see if there is a file at the starting point. If so it will return the
* resolved version of that file.
*
* Otherwise it will walk up the file tree looking for the given filename if a
* file was not found at the starting point.
*/
async function fileWalker({
startingPoint,
filenameIfNotFound
}) {
const resolvedRoot = _path.default.resolve(startingPoint);
const stats = await _fs.default.promises.stat(resolvedRoot); // if the resolved root already references a file, don't walk up the tree
// looking for the filename
if (!stats.isDirectory()) return require.resolve(resolvedRoot);
async function find(pathname) {
try {
return require.resolve(`${pathname}/${filenameIfNotFound}`);
} catch {
const currentFolder = _path.default.resolve(pathname, './');
const parentFolder = _path.default.resolve(pathname, '../');
if (currentFolder === parentFolder) return null;
return await find(parentFolder);
}
}
return await find(resolvedRoot);
}