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 67
gulp.task('generate-xtbs', [
  'extract-translations',
  'remove-unused-translations',
  'remove-duplicated-translations',
  'sort-translations',
]);
R
Rob Franken 已提交
68

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
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 已提交
96

97 98
/**
 * Extracts all translation messages into XTB bundles.
99
 *
100
 * Cleans up the data from the previous run to prevent cross-pollination between branches.
101
 */
102 103 104 105 106 107
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);
    });
108

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
/**
 * 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
 * updated in source code). It has to be runned before 'sort-translations' as original translation
 * 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 已提交
127 128
});

129 130
/**
 * Task to used to find translations used in JavaScript files. Do not run manually. It should be
131
 * invoked as a part of 'remove-unused-translations'.
132 133 134 135 136 137 138 139 140 141 142
 */
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);
  }));
});

/**
143 144
 * Task to remove unused translations. Do not run manually. It should be invoked as a part of
 * 'generate-xtbs'.
145 146
 */
gulp.task(
147
    'remove-unused-translations', ['angular-templates', 'find-translations-used-in-js'],
148 149 150 151 152 153
    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) => {
154
            let unused = new Set();
155 156 157 158 159

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

164 165
            // Remove unused translations.
            unused.forEach((r) => {
166 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
              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,
  };
})();

211 212 213 214 215 216
// 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
//   both [[ message | desription ]] and [[ message ]] work.
// * Second is non-capturing and optional. It has a capturing group inside. This is to
//   extract description that is optional.
217
const I18N_REGEX = /\[\[([^|]*?)(?:\|(.*?))?\]\]/g;
218 219 220

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

  /**
   * 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();
239 240
        // replace {{$variableName}} with {{ $variableName}} to avoid {$ getting recognised as
        // google.getMsg format
241 242 243 244 245 246 247 248 249 250 251 252 253
        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};
254 255 256 257 258 259 260 261 262 263 264
      });
    }
    return [];
  }

  let i18nMessages = findI18nMessages(content);

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

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

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

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

  file.messages = messageVariables.join('\n');
292 293 294
  // 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}'`);
295
  file.moduleContent = `` +
S
Sebastian Florek 已提交
296
      `import module from '/index_module';\n\n${file.messages}\n` +
297 298 299 300 301 302
      `module.run(['$templateCache', ($templateCache) => {\n` +
      `    $templateCache.put('${filePath}', '${content}');\n` +
      `}]);\n`;

  return minifiedHtml;
}