UNPKG

@zohodesk/client_build_tool

Version:

A CLI tool to build web applications and client libraries

129 lines (107 loc) 2.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getAllI18n = getAllI18n; exports.getPropertiesAsJSON = getPropertiesAsJSON; exports.jsonToString = jsonToString; var _fs = require("fs"); var _path = require("path"); var _constants = require("../../../../../constants"); function isComment(line) { return line[0] === '#'; } function getPropertiesAsJSON(filePath) { try { const data = (0, _fs.readFileSync)(filePath); const source = data.toString(); const i18nObj = {}; source.split(/\r?\n\r?/).forEach(fline => { const line = fline.trim(); if (!line || isComment(line)) { return; } const ind = line.indexOf('='); const key = line.slice(0, ind).replace(/\\ /g, ' '); const value = line.slice(ind + 1); if (key && value) { i18nObj[key] = value; } }, {}); return i18nObj; } catch (err) { return {}; } } // TODO: need to make it as custom option and dynamic function getLang(file) { const underScoreIndex = file.indexOf('_'); let language = 'en_US'; if (underScoreIndex !== -1) { language = file.substring(underScoreIndex + 1); language = language.slice(0, language.indexOf('.')); } return language; } function getAllI18n({ folderPath, disableDefault, jsResourceI18nKeys, exclude = /^[^_]+$/, include = /\.properties$/ }) { try { const files = (0, _fs.readdirSync)(folderPath, 'utf8'); const allLangI18n = {}; const context = (0, _constants.joinWithAppPath)(folderPath); files.forEach(file => { const filePath = (0, _path.join)(context, file); if (exclude.test(filePath) || !include.test(filePath)) { return; } const i18n = getPropertiesAsJSON(filePath); allLangI18n[getLang(file)] = disableDefault ? i18n : { ...jsResourceI18nKeys, ...i18n }; }); return allLangI18n; } catch (err) { console.log(err); return {}; } } function jsonToString(json, keySeperator) { let str = '{'; const keys = Object.keys(json); keys.forEach((key, i) => { const value = json[key]; if (!value) { return; } str += `"${keySeperator ? key.replace(/(\.|\\(\s+))/g, keySeperator) : key}":"${value.replace(/.?"/g, match => { if (match[0] === '\\') { return match; } if (match.length === 2) { return `${match[0]}\\${match[1]}`; } return `\\${match}`; }).replace(/(\r\n|\n|\r)/g, '')}"`; if (i !== keys.length - 1) { str += ','; } }); str += '}'; return str; } /** * not useable due to special charector * return `{${Object.keys(data).map(key => `"${key}": "${data[key]}"`).join(",")}}` // return JSON.stringify(data); let str = "{"; for (const key of Object.keys(data)) { str+= `"${key}": "${data[key]}",` } str+="}"; return str; */