UNPKG

attranslate

Version:

Semi-automated Text Translator for Websites and Apps

70 lines (69 loc) 2.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.readManagedUtf8 = exports.insertUtf8Cache = exports.writeManagedUtf8 = void 0; const format_cache_1 = require("./format-cache"); const util_1 = require("../../util/util"); const os_1 = require("os"); /** * Divergent line-endings can be painful in IDEs like WebStorm. * Therefore, we remember line-endings that were previously present. */ const utf8Cache = new format_cache_1.FormatCache(); const possibleEndings = ["\n", "\r", os_1.EOL]; function writeManagedUtf8(args) { var _a, _b; const endings = (_b = (_a = utf8Cache.lookupAuxdata({ path: args.path })) === null || _a === void 0 ? void 0 : _a.endings) !== null && _b !== void 0 ? _b : null; const expandedContent = endings !== null ? replaceLineEndings({ str: args.utf8, endings }) : args.utf8; (0, util_1.writeUtf8File)(args.path, expandedContent); return expandedContent; } exports.writeManagedUtf8 = writeManagedUtf8; function insertUtf8Cache(args) { const endings = extractLineEndings(args.utf8); utf8Cache.insertFileCache({ path: args.path, entries: new Map(), auxData: { endings }, }); } exports.insertUtf8Cache = insertUtf8Cache; function readManagedUtf8(path) { const utf8 = (0, util_1.readUtf8File)(path); insertUtf8Cache({ path, utf8 }); return utf8; } exports.readManagedUtf8 = readManagedUtf8; function replaceLineEndings(args) { const beginOfEnd = beginOfEndIndex(args.str); if (beginOfEnd === null) { return `${args.str}${args.endings}`; } const shorterStr = args.str.slice(0, beginOfEnd); return `${shorterStr}${args.endings}`; } function extractLineEndings(str) { const beginOfEnd = beginOfEndIndex(str); if (beginOfEnd !== null) { return str.slice(beginOfEnd); } else { return ""; } } function beginOfEndIndex(str) { if (!str.length) { return null; } let beginOfEnd = null; for (let idx = str.length - 1; idx >= 0; idx--) { if (possibleEndings.includes(str[idx])) { beginOfEnd = idx; } else { break; } } return beginOfEnd; }