attranslate
Version:
Text Translator for Websites and Apps
65 lines (64 loc) • 2.65 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleCsv = void 0;
const parse_utils_1 = require("../common/parse-utils");
const managed_utf8_1 = require("../common/managed-utf8");
// We might make this configurable if the need arises.
const CSV_SEPARATOR = ",";
function parseCsvStruct(args) {
const lines = args.utf8.split("\n");
if (!lines || lines.length < 2) {
(0, parse_utils_1.logParseError)("Expected at least 2 CSV lines (header + content)", args.args);
}
const rawHeader = lines[0];
const header = rawHeader.split(CSV_SEPARATOR);
if (!header || header.length < 2) {
(0, parse_utils_1.logParseError)(`Expected at least 2 columns in CSV header with separator '${CSV_SEPARATOR}'`, args.args);
}
const languageCodes = header.slice(1);
const languageIndex = 1 + languageCodes.findIndex((value) => value.trim() === args.args.lng);
if (languageIndex <= 0) {
(0, parse_utils_1.logParseError)(`Did not find language '${args.args.lng}' in CSV header '${rawHeader}'`, args.args);
}
const contentLines = lines.slice(1);
contentLines.forEach((line, index) => {
contentLines[index] = line.replace("\r", "");
});
return {
rawHeader,
languageIndex,
contentLines,
};
}
class SimpleCsv {
readTFile(args) {
const utf8 = (0, managed_utf8_1.readManagedUtf8)(args.path);
const csvStruct = parseCsvStruct({ utf8, args });
const tSet = new Map();
csvStruct.contentLines.forEach((line) => {
const tokens = line.split(CSV_SEPARATOR);
if (tokens.length <= csvStruct.languageIndex) {
return;
}
const key = tokens[0];
const value = tokens[csvStruct.languageIndex];
if (tSet.has(key)) {
(0, parse_utils_1.logParseError)(`duplicate key '${key}' -> Currently, the usage of duplicate translation-keys is discouraged.`, args);
}
tSet.set(key, value);
});
return Promise.resolve(tSet);
}
writeTFile(args) {
console.log("Warning: Currently, 'attranslate' may overwrite pre-existing CSV-content. This might change in future versions.");
const lines = [];
const header = ["keys", args.lng].join(CSV_SEPARATOR);
lines.push(header);
args.tSet.forEach((value, key) => {
lines.push([key, value].join(CSV_SEPARATOR));
});
const csv = lines.join("\n");
(0, managed_utf8_1.writeManagedUtf8)({ path: args.path, utf8: csv });
}
}
exports.SimpleCsv = SimpleCsv;