UNPKG

@maniascript/mslint

Version:
87 lines (86 loc) 2.62 kB
import { statSync, readdirSync, readFileSync } from 'node:fs'; import { normalize } from 'node:path'; import { MSLintError } from './error.js'; function fileHasValidExtension(path, extensions) { if (Array.isArray(extensions)) { return extensions.some((extension) => { return path.endsWith(extension); }); } else if (extensions instanceof Set) { for (const extension of extensions) { if (path.endsWith(extension)) return true; } return false; } else { return path.endsWith(extensions); } } function addDotToExtension(file) { return file.startsWith('.') ? file : '.' + file; } function* iterateFiles(path) { try { const stat = statSync(path); if (stat.isDirectory()) { const dirEntries = readdirSync(path); for (const dirEntry of dirEntries) { yield* iterateFiles(`${path}/${dirEntry}`); } } else if (stat.isFile()) { yield normalize(path); } } catch { throw new MSLintError(`MSLint failed to access path '${path}'`); } } function shouldFilterExtensions(extensions) { if (extensions instanceof Set) { return extensions.size > 0; } else { return extensions.length > 0; } } function* iteratePaths(paths, settings) { const pathsToIterate = typeof paths === 'string' ? new Set([paths]) : new Set(paths); const filesFound = new Set(); let extensions = settings?.extensions ?? new Set(); if (Array.isArray(extensions)) { extensions = extensions.map(addDotToExtension); } else if (extensions instanceof Set) { const newExtensions = new Set(); for (const extension of extensions) { newExtensions.add(addDotToExtension(extension)); } extensions = newExtensions; } else { extensions = addDotToExtension(extensions); } for (const path of pathsToIterate) { const trimmedPath = path.trim(); if (trimmedPath !== '') { for (const file of iterateFiles(trimmedPath)) { if (!filesFound.has(file) && (!shouldFilterExtensions(extensions) || fileHasValidExtension(file, extensions))) { filesFound.add(file); yield file; } } } } } function readFile(path) { try { return readFileSync(path, 'utf-8'); } catch { throw new MSLintError(`MSLint failed to read file '${path}'`); } } export { iteratePaths, readFile };