all files / lib/ pull.js

95.24% Statements 40/42
100% Branches 10/10
100% Functions 1/1
95.24% Lines 40/42
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                 10× 10× 10× 10×                                    
const fs = require('fs');
const fse = require('fs-extra');
const path = require('path');
const {sortBy} = require('lodash');
 
const serializers = require('../serializers');
const config = require('../common/config');
const utils = require('../common/utils');
const polyglotUtils = require('../common/polyglot');
 
module.exports = function(program, fileSystem = fs, cwd = process.cwd()) {
  const err = polyglotUtils.checkInitErrors();
  if (err) {
    return err;
  }
 
  return polyglotUtils.getLastUpdatedAt()
    .then((lastUpdatedAt) => Promise.all([lastUpdatedAt, polyglotUtils.getRemoteTranslations()]))
    .then(([lastUpdatedAt, translations]) => {
      utils.debug('Deserialize using', config.project.serializer);
      utils.debug(Object.keys(translations[0]));
 
      const data = {};
 
      const sorted = sortBy(translations, 'translation_key.name');
 
      for (let index = 0; index < sorted.length; index++) {
        const translation = sorted[index];
        const locale = utils.getParsedLocale(translation.language.locale);
        data[locale] = data[locale] || {};
        data[locale][translation.translation_key.name] = translation.value;
      }
 
      const processed = serializers.forLocal(data, config.project);
 
      if (!config.project.skipConfigUpdates) {
        config.project.lastUpdatedAt = lastUpdatedAt;
      }
 
      if (config.project.filetype === '1') {
        const folder = path.dirname(path.join(cwd, config.project.path));
        fse.mkdirsSync(folder, {fs: fileSystem});
        utils.debug('Saving to', path.join(cwd, config.project.path));
        fileSystem.writeFileSync(path.join(cwd, config.project.path), JSON.stringify(processed));
      } else {
        const folder = path.join(cwd, config.project.path);
        fse.mkdirsSync(folder, {fs: fileSystem});
        Object.keys(processed).forEach((locale) => {
          try {
            utils.debug('Saving to', `${folder}/${locale}.json`);
            fileSystem.writeFileSync(`${folder}/${locale}.json`, JSON.stringify(processed[locale], null, 2));
          } catch (e) {
            utils.error(e);
            process.exit(1);
          }
        });
      }
 
      if (!config.project.skipConfigUpdates) {
        polyglotUtils.saveProject(fileSystem);
      }
 
      return processed;
    });
};