Refactor glob.js
Added function `importGlob()` to enclose operations and improve error handling.
This commit is contained in:
@@ -12,6 +12,9 @@
|
||||
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
/**
|
||||
* @type {string[]} A list of packages to attempt import.
|
||||
*/
|
||||
const candidates = [
|
||||
'tiny-glob',
|
||||
'globby',
|
||||
@@ -19,12 +22,24 @@ const candidates = [
|
||||
'glob',
|
||||
];
|
||||
|
||||
var glob, module;
|
||||
export default await importGlob();
|
||||
|
||||
/**
|
||||
* Imports the first available glob function.
|
||||
*
|
||||
* @throws {TypeError} If no glob library was found.
|
||||
* @return {function}
|
||||
*/
|
||||
async function importGlob() {
|
||||
let glob, module;
|
||||
|
||||
for (let name of candidates) {
|
||||
try {
|
||||
module = await import(name);
|
||||
module = module.default;
|
||||
|
||||
if (typeof module.default !== 'function') {
|
||||
throw new TypeError(`Expected ${name} to be a function`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the function to ensure
|
||||
@@ -32,34 +47,26 @@ for (let name of candidates) {
|
||||
*/
|
||||
switch (name) {
|
||||
case 'tiny-glob':
|
||||
glob = createArrayableGlob(module, {
|
||||
return createArrayableGlob(module.default, {
|
||||
filesOnly: true
|
||||
});
|
||||
break;
|
||||
|
||||
case 'glob':
|
||||
glob = promisify(module);
|
||||
break;
|
||||
return promisify(module.default);
|
||||
|
||||
default:
|
||||
glob = module;
|
||||
break;
|
||||
return module.default;
|
||||
}
|
||||
|
||||
break; // loop
|
||||
} catch (err) {
|
||||
// swallow this error; skip to the next candidate.
|
||||
}
|
||||
}
|
||||
|
||||
if (!glob) {
|
||||
throw new TypeError(
|
||||
`No glob library was found, expected one of: ${modules.join(', ')}`
|
||||
);
|
||||
}
|
||||
|
||||
export default glob;
|
||||
|
||||
/**
|
||||
* Creates a wrapper function for the glob function
|
||||
* to provide support for arrays of patterns.
|
||||
|
||||
Reference in New Issue
Block a user