From 8554259d9229d0f60454b4ffe43ea7dec8f52705 Mon Sep 17 00:00:00 2001 From: 43081j <43081j@users.noreply.github.com> Date: Sat, 8 Jun 2024 17:08:29 +0100 Subject: [PATCH] feat: drop glob usage Removes `glob` and uses fdir instead with a basic directory traversal (no globs). Reduces the complexity of the file reading logic and the install size (~3MB to 56KB). --- package.json | 2 +- src/read-file.js | 61 +++++++++++++++++++----------------------------- 2 files changed, 25 insertions(+), 38 deletions(-) diff --git a/package.json b/package.json index 66962c55..cfb1b890 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,7 @@ }, "dependencies": { "commenting": "~1.1.0", - "glob": "~7.2.0", + "fdir": "6.1.1", "lodash": "~4.17.21", "magic-string": "~0.30.0", "mkdirp": "~3.0.0", diff --git a/src/read-file.js b/src/read-file.js index 8fd0f214..5852b700 100644 --- a/src/read-file.js +++ b/src/read-file.js @@ -25,8 +25,17 @@ import path from 'path'; import fs from 'fs'; import _ from 'lodash'; -import glob from 'glob'; +import { fdir } from 'fdir'; +const pathsMatch = (target) => { + const targetLower = target.toLowerCase(); + + return (p) => { + const pLower = p.toLowerCase(); + return pLower === targetLower || + pLower.slice(0, pLower.lastIndexOf('.')) === targetLower; + }; +}; /** * Find file and returns its content if file exists. * @@ -37,49 +46,27 @@ import glob from 'glob'; */ export function readFile(dir, cwd, names) { const inputs = _.castArray(names); + // eslint-disable-next-line new-cap + const finder = new fdir(); for (let i = 0; i < inputs.length; ++i) { - const input = generatePattern(inputs[i]); + const input = inputs[i]; const absolutePath = path.join(dir, input); const relativeToCwd = path.relative(cwd, absolutePath); - const findings = glob.sync(relativeToCwd, { cwd }); - for (let j = 0; j < findings.length; ++j) { - const file = path.join(cwd, findings[j]); - if (isFile(file)) { - return fs.readFileSync(file, 'utf-8'); - } - } - } - - return null; -} - -/** - * Check that given file exists, and is a real file. - * - * @param {string} file File path. - * @returns {boolean} `true` if `file` is a file, `false` otherwise. - */ -function isFile(file) { - return !!fs.existsSync(file) && !!fs.lstatSync(file).isFile(); -} + const findings = finder + .withRelativePaths() + .filter(pathsMatch(relativeToCwd)) + .crawl(cwd) + .sync(); -/** - * Generate glob pattern for given input. - * - * @param {string} input Given input. - * @returns {string} Glob pattern. - */ -function generatePattern(input) { - let pattern = ''; + const firstPath = findings[0]; - for (let i = 0; i < input.length; ++i) { - const c = input[i]; - const up = c.toUpperCase(); - const low = c.toLowerCase(); - pattern += up !== low ? `[${low}${up}]` : low; + if (firstPath) { + const file = path.join(cwd, firstPath); + return fs.readFileSync(file, 'utf-8'); + } } - return `${pattern}*`; + return null; }