UNPKG

@lint-todo/utils

Version:

![CI Build](https://github.com/lint-todo/utils/workflows/CI%20Build/badge.svg) [![npm version](https://badge.fury.io/js/%40lint-todo%2Futils.svg)](https://badge.fury.io/js/%40lint-todo%2Futils) [![License](https://img.shields.io/npm/l/@checkup/cli.svg)](h

86 lines 2.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSourceForRange = exports.readSource = exports.buildRange = exports._sourceCache = void 0; const node_fs_1 = require("node:fs"); const LINES_PATTERN = /(.*?(?:\r\n?|\n|$))/gm; exports._sourceCache = new Map(); /** * Converts node positional numbers into a Range object. * * @param line - The source start line. * @param column - The source start column. * @param endLine - The source end line. * @param endColumn - The source end column. * @returns A range object. */ function buildRange(line, column, endLine, endColumn) { return { start: { line: line, column: column, }, end: { line: endLine !== null && endLine !== void 0 ? endLine : line, column: endColumn !== null && endColumn !== void 0 ? endColumn : column, }, }; } exports.buildRange = buildRange; /** * Reads a source file, optionally caching it if it's already been read. * * @param filePath - The path to the source file. * @returns The file contents. */ function readSource(filePath) { if (!filePath) { return ''; } if ((0, node_fs_1.existsSync)(filePath) && !exports._sourceCache.has(filePath)) { const source = (0, node_fs_1.readFileSync)(filePath, { encoding: 'utf8' }); exports._sourceCache.set(filePath, source); } return exports._sourceCache.get(filePath) || ''; } exports.readSource = readSource; /** * Extracts a source fragment from a file's contents based on the provided Range. * * @param source - The file contents. * @param range - A Range object representing the range to extract from the file contents. * @returns The source fragment. */ function getSourceForRange(source, range) { if (!source) { return ''; } const sourceLines = source.match(LINES_PATTERN) || []; const firstLine = range.start.line - 1; const lastLine = range.end.line - 1; let currentLine = firstLine - 1; const firstColumn = range.start.column - 1; const lastColumn = range.end.column - 1; const src = []; let line; while (currentLine < lastLine) { currentLine++; line = sourceLines[currentLine]; if (currentLine === firstLine) { if (firstLine === lastLine) { src.push(line.slice(firstColumn, lastColumn)); } else { src.push(line.slice(firstColumn)); } } else if (currentLine === lastLine) { src.push(line.slice(0, lastColumn)); } else { src.push(line); } } return src.join(''); } exports.getSourceForRange = getSourceForRange; //# sourceMappingURL=source.js.map