UNPKG

1.82 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const fs_1 = require("fs");
4const path_1 = require("path");
5let caches = Object.create(null);
6function closestFileData(relPath, oneOrMoreReader) {
7 const paths = [];
8 const readers = Array.isArray(oneOrMoreReader) ? oneOrMoreReader : [oneOrMoreReader];
9 if (readers.length < 1) {
10 throw new RangeError(`At least one reader must be given.`);
11 }
12 // cache key is based on the ordered list of basenames
13 const cacheKey = readers.map(r => r.basename).join('::');
14 if (!(cacheKey in caches)) {
15 caches[cacheKey] = Object.create(null);
16 }
17 const cache = caches[cacheKey];
18 let result;
19 let directory = relPath;
20 do {
21 if (directory in cache) {
22 result = cache[directory];
23 break;
24 }
25 paths.push(directory);
26 // look for a config using readers (config file must exists and reader must not return null)
27 readers.find(({ basename, read }) => {
28 const path = path_1.join(directory, basename);
29 if (fs_1.existsSync(path)) {
30 const config = read(path);
31 if (typeof config !== 'undefined') {
32 result = Object.freeze({ path, data: config });
33 return true;
34 }
35 }
36 return false;
37 });
38 // continue while we don't have a config and there is a parent directory
39 } while (!result && directory !== (directory = path_1.dirname(directory))); // tslint:disable-line
40 // each directory will resolve to the same config
41 paths.forEach(d => (cache[d] = result));
42 return result;
43}
44exports.default = Object.assign(closestFileData, {
45 cache: {
46 clear: () => (caches = Object.create(null)),
47 },
48});