@adguard/aglint
Version:
Universal adblock filter list linter.
51 lines (48 loc) • 2.08 kB
JavaScript
/*
* AGLint v3.0.0 (build date: Wed, 21 May 2025 13:24:14 GMT)
* (c) 2025 AdGuard Software Ltd.
* Released under the MIT license
* https://github.com/AdguardTeam/AGLint#readme
*/
import { readdir } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import { CONFIG_FILE_NAMES } from './constants.js';
import 'js-yaml';
import 'superstruct';
import '../config.js';
const UPPER_DIR = '..';
/**
* Discovers every AGLint config files in the current working directory and its parent directories.
* It only checks file names, not the contents of the files, so it doesn't validate the config files.
* If you didn't abort the search meanwhile, it will scan until it reaches the root directory.
*
* @param cwd Current working directory
* @param callback Callback function that will be called with the path to the config file
* if it is found
* @throws If multiple config files are found in the same directory
*/
async function configFinder(cwd, callback) {
// Start with the current working directory
let dir = resolve(cwd);
// Keep searching for a config file until we reach the root directory
do {
// Get the list of files in the current directory
const files = await readdir(dir);
// Collect all config files in the current directory
const configFiles = files.filter((file) => CONFIG_FILE_NAMES.has(file));
if (configFiles.length === 1) {
// If there is only one config file, call the callback with the path to the config file
// If the callback returned `true`, stop the search
if (await callback(join(dir, configFiles[0])) === true) {
return;
}
}
else if (configFiles.length > 1) {
// If there are multiple config files, throw an error
throw new Error(`Multiple config files found in ${dir}`);
}
// If there are no config files, go one directory up and try again
dir = join(dir, UPPER_DIR);
} while (dir !== resolve(dir, UPPER_DIR));
}
export { configFinder };