UNPKG

polyglot-cli

Version:
82 lines (70 loc) 2.64 kB
const fs = require('fs'); const {mapValues} = require('lodash'); const co = require('co'); const polyglotUtils = require('../common/polyglot'); const utils = require('../common/utils'); const network = require('../common/network'); const config = require('../common/config'); const importTranslations = co.wrap(function* (fileSystem, remoteTranslations = [], cwd, project = config.project) { /* * Mapping of remote keys in the following format: * @example * { * key: "remoteKeyId" * } */ const remoteKeysObj = yield network.read(`/translation_keys?filter[project_id]=${project.id}`); const remoteKeys = utils.getTranslationKeys(remoteKeysObj); utils.debug(`Number of remote keys: ${Object.keys(remoteKeys).length}`); /* * The default project language * * @prop {String} locale - The language locale * @prop {String} id - The remote language id */ const language = yield polyglotUtils.getDefaultLanguage(); const locale = utils.getParsedLocale(language.locale); utils.debug(`Default language: ${language.locale} / ${locale}`); /* * Key/value local translations for the default project language */ const localTranslations = polyglotUtils.loadTranslations(fileSystem, locale, config.project, cwd); /* * A list of local keys */ const localKeys = Object.keys(localTranslations); utils.debug(`Number of local keys: ${localKeys.length}`); /* * Mapping of all (existing and new) keys in the following format: * @example * { * key: "remoteKeyId" * } */ const keys = yield polyglotUtils.ensureRemoteKeys(localKeys, remoteKeys); utils.debug(`Number of total keys: ${Object.keys(keys).length}`); /* * Translations that need to be sent to the server. If remote is defined, the translation needs to be updated */ const translations = mapValues(localTranslations, function(value, key) { const remote = remoteTranslations.find((item) => item.translation_key.name === key); return { value, remote: remote && remote.id }; }); utils.debug(JSON.stringify(translations)); yield polyglotUtils.sendTranslations(language.id, keys, translations, localTranslations); }); module.exports = function(program, fileSystem = fs, cwd) { const err = polyglotUtils.checkInitErrors(); if (err) { return err; } return polyglotUtils.getRemoteTranslations().then((translations) => { if (translations.length && !program.force) { return utils.error('Can\'t push if remote translations already exist. Use --force to override.'); } return importTranslations(fileSystem, translations, cwd); }); };