UNPKG

@oxlint/migrate

Version:

Generates a `.oxlintrc.json` from a existing eslint flat config

61 lines (60 loc) 2.1 kB
import { parseSync } from "oxc-parser"; import replaceComments from "./comments/index.mjs"; import partialSourceTextLoader from "./partialSourceTextLoader.mjs"; const getComments = (absoluteFilePath, partialSourceText, options) => { const parserResult = parseSync( absoluteFilePath, partialSourceText.sourceText, { lang: partialSourceText.lang, sourceType: partialSourceText.sourceType } ); if (parserResult.errors.length > 0 && options.reporter) { options.reporter(`${absoluteFilePath}: failed to parse`); } return parserResult.comments; }; function replaceCommentsInSourceText(absoluteFilePath, partialSourceText, options) { const comments = getComments(absoluteFilePath, partialSourceText, options); let sourceText = partialSourceText.sourceText; for (const comment of comments) { try { const replacedStr = replaceComments(comment.value, comment.type, options); if (replacedStr !== comment.value) { const newComment = comment.type === "Line" ? `//${replacedStr}` : `/*${replacedStr}*/`; sourceText = sourceText.slice(0, comment.start) + newComment + sourceText.slice(comment.end); } } catch (error) { if (error instanceof Error && options.reporter) { options.reporter( `${absoluteFilePath}, char offset ${comment.start + partialSourceText.offset}: ${error.message}` ); continue; } throw error; } } return sourceText; } function replaceCommentsInFile(absoluteFilePath, fileContent, options) { for (const partialSourceText of partialSourceTextLoader( absoluteFilePath, fileContent )) { const newSourceText = replaceCommentsInSourceText( absoluteFilePath, partialSourceText, options ); if (newSourceText !== partialSourceText.sourceText) { fileContent = fileContent.slice(0, partialSourceText.offset) + newSourceText + fileContent.slice( partialSourceText.offset + partialSourceText.sourceText.length ); } } return fileContent; } export { replaceCommentsInFile as default };