UNPKG

@mediafly/translate

Version:

Translate strings extracted from apps using Google Translate

95 lines (78 loc) 2.38 kB
var _ = require('lodash') var path = require('path') var config = require(path.join(process.cwd(), 'mediafly-translate.config')) var flatten = require('flat') var xmlJs = require('xml-js') function removeFirstAndLastChar(string) { return string.substr(1).slice(0, -1) } function separateByNewLines(string) { return string.split(/\r?\n/).filter(s => s.trim().length > 0) } function escapeCharsForiOS(string) { return string.replace(/\\/g, '\\\\') .replace(/"/g, '\\"') } function removeEscapedCharsForiOS(string) { return string.replace(/\\"/g, '"') .replace(/\\\\/g, '\\') } function escapeCharsForAndroid(string) { return string.replace(/'/g, "\\'") } function removeEscapedCharsForAndroid(string) { if (!string) { return string } return string.replace(/\\'/g, "'") } function parseKey(string) { var whiteSpaceRemoved = string.split('=')[0].trim() var quotesRemoved = removeFirstAndLastChar(whiteSpaceRemoved) return removeEscapedCharsForiOS(quotesRemoved) } function parseValue(string) { var whiteSpaceRemoved = string.split('=')[1].trim() var semiColonRemoved = _.trimEnd(whiteSpaceRemoved, ';') var quotesRemoved = removeFirstAndLastChar(semiColonRemoved) return removeEscapedCharsForiOS(quotesRemoved) } function transform(obj) { //transform JavaScript object to a string that will be written to disk if (config.format === 'strings') { var objWithEscapedChars = _.mapValues( _.mapKeys(obj, (value, key) => escapeCharsForiOS(key)), (value) => escapeCharsForiOS(value) ) var keys = Object.keys(objWithEscapedChars) return keys .map(key => `"${key}" = "${objWithEscapedChars[key]}";`) .join('\n') } if (config.format === 'xml') { var xmlObj = { _declaration: {"_attributes":{"version":"1.0","encoding":"UTF-8"}}, resources: { string: [] } } _.forOwn(obj, (value, key) => xmlObj.resources.string.push({ _text: escapeCharsForAndroid(value), _attributes: { name: key } })) return xmlJs.js2xml(xmlObj, { compact: true, spaces: 4 }) } var unflattenedObj = flatten.unflatten(obj) if (config.format === 'js') { return 'export default ' + JSON.stringify(unflattenedObj, null, 4) } if (!config.format || config.format === 'json') { return JSON.stringify(unflattenedObj, null, 4) } } module.exports = { removeEscapedCharsForAndroid, separateByNewLines, parseKey, parseValue, transform }