i18n.js 9.6 KB
Newer Older
C
Christoph Held 已提交
1
// Copyright 2017 The Kubernetes Authors.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Gulp tasks for the extraction of translatable messages.
 */
import childProcess from 'child_process';
import fileExists from 'file-exists';
import gulp from 'gulp';
21
import cheerio from 'gulp-cheerio';
22
import freplace from 'gulp-findreplace';
23
import gulpUtil from 'gulp-util';
R
Rob Franken 已提交
24
import xslt from 'gulp-xslt';
25
import jsesc from 'jsesc';
26 27
import path from 'path';
import q from 'q';
28
import regexpClone from 'regexp-clone';
29 30 31 32 33

import conf from './conf';

/**
 * Extracts the translatable text messages for the given language key from the pre-compiled
34
 * files under conf.paths.{serve|messagesForExtraction}.
35 36 37 38 39 40 41
 * @param  {string} langKey - the locale key
 * @return {!Promise} A promise object.
 */
function extractForLanguage(langKey) {
  let deferred = q.defer();

  let translationBundle = path.join(conf.paths.base, `i18n/messages-${langKey}.xtb`);
42 43
  let codeSource = path.join(conf.paths.serve, '**.js');
  let messagesSource = path.join(conf.paths.messagesForExtraction, '**.js');
44
  let command = `java -jar ${conf.paths.xtbgenerator} --lang ${langKey}` +
45
      ` --xtb_output_file ${translationBundle} --js ${codeSource} --js ${messagesSource}`;
46
  if (fileExists.sync(translationBundle)) {
47 48 49 50 51 52 53 54 55
    command = `${command} --translations_file ${translationBundle}`;
  }

  childProcess.exec(command, function(err, stdout, stderr) {
    if (err) {
      gulpUtil.log(stdout);
      gulpUtil.log(stderr);
      deferred.reject(new Error(err));
    }
R
Rob Franken 已提交
56
    deferred.resolve();
57 58 59 60 61
  });

  return deferred.promise;
}

62 63 64 65 66
gulp.task('generate-xtbs', [
  'extract-translations',
  'remove-unused-translations',
  'remove-duplicated-translations',
  'sort-translations',
S
Sebastian Florek 已提交
67
  'set-prod-node-env',
68
]);
R
Rob Franken 已提交
69

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
let prevMsgs = {};

gulp.task('buildExistingI18nCache', function() {
  return gulp.src('i18n/messages-en.xtb').pipe(cheerio((doc) => {
    doc('translation').each((i, translation) => {
      let key = translation.attribs.key;
      let index = key.lastIndexOf('_');
      if (index !== -1) {
        let lastpart = key.substring(index + 1);
        if (/^[0-9]+$/.test(lastpart)) {
          let indexSuffix = Number(lastpart);
          let filePrefix = key.substring(0, index);
          if (!prevMsgs[filePrefix]) {
            prevMsgs[filePrefix] = [];
          }
          prevMsgs[filePrefix].push({
            index: indexSuffix,
            key: key,
            text: doc(translation).text(),
            desc: translation.attribs.desc,
            used: false,
          });
        }
      }
    });
  }));
});
R
Rob Franken 已提交
97

98 99
/**
 * Extracts all translation messages into XTB bundles.
100
 *
101
 * Cleans up the data from the previous run to prevent cross-pollination between branches.
102
 */
103 104 105 106 107 108
gulp.task(
    'extract-translations', ['scripts', 'angular-templates', 'clean-messages-for-extraction'],
    function() {
      let promises = conf.translations.map((translation) => extractForLanguage(translation.key));
      return q.all(promises);
    });
109

110 111 112 113 114 115 116 117 118 119 120
/**
 * Task to sort translations.
 */
gulp.task('sort-translations', ['remove-duplicated-translations'], function() {
  return gulp.src('i18n/messages-*.xtb')
      .pipe(xslt('build/sort-translations.xslt'))
      .pipe(gulp.dest('i18n'));
});

/**
 * Task to remove duplicated translations (should remove old translations from XTB when entries are
S
sheng zhang 已提交
121
 * updated in source code). It has to be ran before 'sort-translations' as original translation
122 123 124 125 126 127
 * order is required.
 */
gulp.task('remove-duplicated-translations', ['extract-translations'], function() {
  return gulp.src('i18n/messages-*.xtb')
      .pipe(xslt('build/remove-duplicated-translations.xslt'))
      .pipe(gulp.dest('i18n'));
R
Rob Franken 已提交
128 129
});

130 131
/**
 * Task to used to find translations used in JavaScript files. Do not run manually. It should be
132
 * invoked as a part of 'remove-unused-translations'.
133 134 135 136 137 138 139 140 141 142 143
 */
gulp.task('find-translations-used-in-js', function() {
  let jsSource = path.join(conf.paths.frontendSrc, '**/*.js');
  return gulp.src(jsSource).pipe(freplace(/MSG_\w*/g, function(match) {
    // Mark every message found in JavaScript files as used, it will allow deletion of unused
    // messages afterwards.
    translationsManager.addUsed(match);
  }));
});

/**
144 145
 * Task to remove unused translations. Do not run manually. It should be invoked as a part of
 * 'generate-xtbs'.
146 147
 */
gulp.task(
148
    'remove-unused-translations', ['angular-templates', 'find-translations-used-in-js'],
149 150 151 152 153 154
    function() {
      // Get translations used in JavaScript and HTML files. These will not be removed.
      let used = translationsManager.getUsed();

      return gulp.src('i18n/messages-*.xtb')
          .pipe(cheerio((doc) => {
155
            let unused = new Set();
156 157 158 159 160

            // Find translations to remove.
            doc('translation').each((i, translation) => {
              let key = translation.attribs.key;
              if (!used.has(key)) {
161
                unused.add(key);
162 163 164
              }
            });

165 166
            // Remove unused translations.
            unused.forEach((r) => {
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
              doc(`translation[key=${r}]`).remove();
            });
          }))
          .pipe(gulp.dest('i18n/'));
    });

/**
 * Translations manager is a closure function allowing to manage translations.
 * Allows removing unused translations after marking certain as used.
 *
 * @type {{markAsUsed, removeUnused}}
 */
export let translationsManager = (function() {

  /**
   * Set of translations marked as used.
   *
   * @type {Set}
   */
  let used = new Set();

  /**
   * Function used to mark translations as used.
   *
   * @param {string} key
   */
  function addUsed(key) {
    used.add(key);
  }

  /**
   * Function used to get used translations.
   *
   * @return {Set}
   */
  function getUsed() {
    return used;
  }

  return {
    addUsed: addUsed,
    getUsed: getUsed,
  };
})();

212 213 214
// Regex to match [[Foo | Bar]] or [[Foo]] i18n placeholders.
// Technical details:
// * First capturing group is lazy math for any string not-containing |. This is to make
S
sheng zhang 已提交
215
//   both [[ message | description ]] and [[ message ]] work.
216 217
// * Second is non-capturing and optional. It has a capturing group inside. This is to
//   extract description that is optional.
218
const I18N_REGEX = /\[\[([^|]*?)(?:\|(.*?))?\]\]/g;
219 220 221

export function processI18nMessages(file, minifiedHtml) {
  let content = jsesc(minifiedHtml);
222
  let pureHtmlContent = `${content}`;
223 224
  let filePath = path.relative(file.base, file.path);
  let messageVarPrefix = filePath.toUpperCase().split('/').join('_').replace('.HTML', '');
225
  let used = new Set();
226 227 228 229 230 231 232 233 234 235 236 237 238 239

  /**
   * Finds all i18n messages inside a template and returns its text, description and original
   * string.
   * @param {string} htmlContent
   * @return {!Array<{text: string, desc: string, original: string}>}
   */
  function findI18nMessages(htmlContent) {
    let matches = htmlContent.match(I18N_REGEX);
    if (matches) {
      return matches.map((match) => {
        let exec = regexpClone(I18N_REGEX).exec(match);
        // Default to no description when it is not provided.
        let desc = (exec[2] || '(no description provided)').trim();
240 241
        // replace {{$variableName}} with {{ $variableName}} to avoid {$ getting recognised as
        // google.getMsg format
242 243 244 245 246 247 248 249 250 251 252 253 254
        let text = exec[1].replace('{$', '{ $');
        let varName = undefined;
        if (prevMsgs[`MSG_${messageVarPrefix}`]) {
          for (let msg of prevMsgs[`MSG_${messageVarPrefix}`]) {
            if (msg.text === text && msg.desc === desc && !msg.used) {
              varName = msg.key;
              msg.used = true;
              used.add(msg.index);
              break;
            }
          }
        }
        return {text: text, desc: desc, original: match, varName: varName};
255 256 257 258 259 260 261 262 263 264 265
      });
    }
    return [];
  }

  let i18nMessages = findI18nMessages(content);

  /**
   * @param {number} index
   * @return {string}
   */
266 267 268 269 270 271 272
  function createMessageVarName() {
    for (let i = 0;; i++) {
      if (!used.has(i)) {
        used.add(i);
        return `MSG_${messageVarPrefix}_${i}`;
      }
    }
273 274
  }

275 276
  i18nMessages.forEach((message) => {
    message.varName = message.varName || createMessageVarName();
277 278
    // Replace i18n messages with english messages for testing and MSG_ vars invocations
    // for compiler passses.
279
    content = content.replace(message.original, `' + ${message.varName} + '`);
280
    pureHtmlContent = pureHtmlContent.replace(message.original, message.text);
281 282 283 284

    // Mark every message found in this HTML file as used, it will allow deletion of unused messages
    // afterwards.
    translationsManager.addUsed(message.varName);
285 286
  });

287
  let messageVariables = i18nMessages.map((message) => {
288
    return `/** @desc ${message.desc} */\n` +
289
        `var ${message.varName} = goog.getMsg('${message.text}');\n`;
290 291 292
  });

  file.messages = messageVariables.join('\n');
293 294 295
  // Eval pure HTML content, because it has been jsescaped previously. This is safe to eval since
  // it was escaped by jsecs previously.
  file.pureHtmlContent = eval(`'${pureHtmlContent}'`);
296
  file.moduleContent = `` +
S
Sebastian Florek 已提交
297
      `import module from '/index_module';\n\n${file.messages}\n` +
298 299 300 301 302 303
      `module.run(['$templateCache', ($templateCache) => {\n` +
      `    $templateCache.put('${filePath}', '${content}');\n` +
      `}]);\n`;

  return minifiedHtml;
}