UNPKG

@dozerg/end-of-line

Version:

Determine EOL based on given text and OS.

43 lines (42 loc) 1.6 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.endOfLine = endOfLine; exports.endOfLineForFile = endOfLineForFile; const fs_1 = __importDefault(require("fs")); const os_1 = __importDefault(require("os")); function assertNonNull(value, message) { if (value === undefined || value === null) { throw Error(message !== null && message !== void 0 ? message : `Assert Non-Null failed, value = ${value}`); } } function endOfLine(text) { if (text) { const t = text.slice(0, 4096); const nl = t.match(/\r\n|\n\r|\n|\r/g); if (nl && nl.length > 0) { const s = nl.reduce((r, a) => { const c = r.find(([c]) => c === a); assertNonNull(c); c[1]++; return r; }, [ ['\n', 0], ['\r\n', 0], ['\r', 0], ['\n\r', 0], ]); const r = s.reduce((r, a) => (r.length < 1 || r[0][1] < a[1] ? [a] : r[0][1] === a[1] ? [...r, a] : r), []); if (r.length === 1 || !r.some(([c]) => c === os_1.default.EOL)) return r[0][0]; } } return os_1.default.EOL; } function endOfLineForFile(filePath) { if (!filePath || !fs_1.default.existsSync(filePath) || !fs_1.default.statSync(filePath).isFile()) return endOfLine(); return endOfLine(fs_1.default.readFileSync(filePath).toString()); }