i18n.ts 34.6 KB
Newer Older
D
Dirk Baeumer 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as path from 'path';
import * as fs from 'fs';

9
import { through, readable } from 'event-stream';
D
Dirk Baeumer 已提交
10 11 12
import { ThroughStream } from 'through';
import File = require('vinyl');
import * as Is from 'is';
13
import * as xml2js from 'xml2js';
14
import * as glob from 'glob';
15
import * as https from 'https';
D
Dirk Baeumer 已提交
16 17

var util = require('gulp-util');
18
var iconv = require('iconv-lite');
J
Joao Moreno 已提交
19

20 21
const NUMBER_OF_CONCURRENT_DOWNLOADS = 1;

D
Dirk Baeumer 已提交
22
function log(message: any, ...rest: any[]): void {
J
Joao Moreno 已提交
23
	util.log(util.colors.green('[i18n]'), message, ...rest);
D
Dirk Baeumer 已提交
24 25 26 27 28 29
}

interface Map<V> {
	[key: string]: V;
}

30 31 32 33 34 35
interface Item {
	id: string;
	message: string;
	comment: string;
}

36
export interface Resource {
37 38 39 40
	name: string;
	project: string;
}

41 42 43 44 45 46
interface ParsedXLF {
	messages: Map<string>;
	originalFilePath: string;
	language: string;
}

D
Dirk Baeumer 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
interface LocalizeInfo {
	key: string;
	comment: string[];
}

module LocalizeInfo {
	export function is(value: any): value is LocalizeInfo {
		let candidate = value as LocalizeInfo;
		return Is.defined(candidate) && Is.string(candidate.key) && (Is.undef(candidate.comment) || (Is.array(candidate.comment) && candidate.comment.every(element => Is.string(element))));
	}
}

interface BundledFormat {
	keys: Map<(string | LocalizeInfo)[]>;
	messages: Map<string[]>;
	bundles: Map<string[]>;
}

module BundledFormat {
	export function is(value: any): value is BundledFormat {
		if (Is.undef(value)) {
			return false;
		}

		let candidate = value as BundledFormat;
		let length = Object.keys(value).length;

		return length === 3 && Is.defined(candidate.keys) && Is.defined(candidate.messages) && Is.defined(candidate.bundles);
	}
}

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
interface ValueFormat {
	message: string;
	comment: string[];
}

interface PackageJsonFormat {
	[key: string]: string | ValueFormat;
}

module PackageJsonFormat {
	export function is(value: any): value is PackageJsonFormat {
		if (Is.undef(value) || !Is.object(value)) {
			return false;
		}
		return Object.keys(value).every(key => {
			let element = value[key];
			return Is.string(element) || (Is.object(element) && Is.defined(element.message) && Is.defined(element.comment));
		});
	}
}

interface ModuleJsonFormat {
	messages: string[];
	keys: (string | LocalizeInfo)[];
}

module ModuleJsonFormat {
	export function is(value: any): value is ModuleJsonFormat {
		let candidate = value as ModuleJsonFormat;
		return Is.defined(candidate)
			&& Is.array(candidate.messages) && candidate.messages.every(message => Is.string(message))
			&& Is.array(candidate.keys) && candidate.keys.every(key => Is.string(key) || LocalizeInfo.is(key));
	}
}

export class Line {
	private buffer: string[] = [];

	constructor(private indent: number = 0) {
		if (indent > 0) {
			this.buffer.push(new Array(indent + 1).join(' '));
		}
	}

	public append(value: string): Line {
		this.buffer.push(value);
		return this;
	}

	public toString(): string {
		return this.buffer.join('');
	}
}

class TextModel {
	private _lines: string[];

	constructor(contents: string) {
		this._lines = contents.split(/\r\n|\r|\n/);
	}

	public get lines(): string[] {
		return this._lines;
	}
}

export class XLF {
J
Joao Moreno 已提交
145
	private buffer: string[];
146 147
	private files: Map<Item[]>;

J
Joao Moreno 已提交
148 149
	constructor(public project: string) {
		this.buffer = [];
150 151 152
		this.files = Object.create(null);
	}

J
Joao Moreno 已提交
153 154
	public toString(): string {
		this.appendHeader();
155 156 157 158 159 160

		for (let file in this.files) {
			this.appendNewLine(`<file original="${file}" source-language="en" datatype="plaintext"><body>`, 2);
			for (let item of this.files[file]) {
				this.addStringItem(item);
			}
J
Joao Moreno 已提交
161
			this.appendNewLine('</body></file>', 2);
162 163 164 165 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
		}

		this.appendFooter();
		return this.buffer.join('\r\n');
	}

	public addFile(original: string, keys: any[], messages: string[]) {
		this.files[original] = [];
		let existingKeys = [];

		for (let key of keys) {
			// Ignore duplicate keys because Transifex does not populate those with translated values.
			if (existingKeys.indexOf(key) !== -1) {
				continue;
			}
			existingKeys.push(key);

			let message: string = encodeEntities(messages[keys.indexOf(key)]);
			let comment: string = undefined;

			// Check if the message contains description (if so, it becomes an object type in JSON)
			if (Is.string(key)) {
				this.files[original].push({ id: key, message: message, comment: comment });
			} else {
				if (key['comment'] && key['comment'].length > 0) {
					comment = key['comment'].map(comment => encodeEntities(comment)).join('\r\n');
				}

				this.files[original].push({ id: key['key'], message: message, comment: comment });
			}
		}
	}

J
Joao Moreno 已提交
195 196
	private addStringItem(item: Item): void {
		if (!item.id || !item.message) {
D
Dirk Baeumer 已提交
197
			throw new Error(`No item ID or value specified: ${JSON.stringify(item)}`);
J
Joao Moreno 已提交
198
		}
199

J
Joao Moreno 已提交
200 201
		this.appendNewLine(`<trans-unit id="${item.id}">`, 4);
		this.appendNewLine(`<source xml:lang="en">${item.message}</source>`, 6);
202

J
Joao Moreno 已提交
203 204 205
		if (item.comment) {
			this.appendNewLine(`<note>${item.comment}</note>`, 6);
		}
206

J
Joao Moreno 已提交
207
		this.appendNewLine('</trans-unit>', 4);
208 209
	}

J
Joao Moreno 已提交
210 211 212
	private appendHeader(): void {
		this.appendNewLine('<?xml version="1.0" encoding="utf-8"?>', 0);
		this.appendNewLine('<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">', 0);
213 214
	}

J
Joao Moreno 已提交
215 216 217
	private appendFooter(): void {
		this.appendNewLine('</xliff>', 0);
	}
218

J
Joao Moreno 已提交
219 220 221 222 223
	private appendNewLine(content: string, indent?: number): void {
		let line = new Line(indent);
		line.append(content);
		this.buffer.push(line.toString());
	}
224

J
Joao Moreno 已提交
225
	static parse = function (xlfString: string): Promise<ParsedXLF[]> {
226 227 228 229 230
		return new Promise((resolve, reject) => {
			let parser = new xml2js.Parser();

			let files: { messages: Map<string>, originalFilePath: string, language: string }[] = [];

J
Joao Moreno 已提交
231
			parser.parseString(xlfString, function (err, result) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
				if (err) {
					reject(`Failed to parse XLIFF string. ${err}`);
				}

				const fileNodes: any[] = result['xliff']['file'];
				if (!fileNodes) {
					reject('XLIFF file does not contain "xliff" or "file" node(s) required for parsing.');
				}

				fileNodes.forEach((file) => {
					const originalFilePath = file.$.original;
					if (!originalFilePath) {
						reject('XLIFF file node does not contain original attribute to determine the original location of the resource file.');
					}
					const language = file.$['target-language'].toLowerCase();
					if (!language) {
						reject('XLIFF file node does not contain target-language attribute to determine translated language.');
					}

					let messages: Map<string> = {};
					const transUnits = file.body[0]['trans-unit'];

					transUnits.forEach(unit => {
						const key = unit.$.id;
						if (!unit.target) {
							return; // No translation available
						}

						const val = unit.target.toString();
						if (key && val) {
							messages[key] = decodeEntities(val);
						} else {
							reject('XLIFF file does not contain full localization data. ID or target translation for one of the trans-unit nodes is not present.');
						}
					});

					files.push({ messages: messages, originalFilePath: originalFilePath, language: language });
				});

				resolve(files);
			});
		});
	};
}

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
export interface ITask<T> {
	(): T;
}

interface ILimitedTaskFactory<T> {
	factory: ITask<Promise<T>>;
	c: (value?: T | Thenable<T>) => void;
	e: (error?: any) => void;
}

export class Limiter<T> {
	private runningPromises: number;
	private outstandingPromises: ILimitedTaskFactory<any>[];

	constructor(private maxDegreeOfParalellism: number) {
		this.outstandingPromises = [];
		this.runningPromises = 0;
	}

	queue(factory: ITask<Promise<T>>): Promise<T> {
		return new Promise<T>((c, e) => {
			this.outstandingPromises.push({factory, c, e});
			this.consume();
		});
	}

	private consume(): void {
		while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {
			const iLimitedTask = this.outstandingPromises.shift();
			this.runningPromises++;

			const promise = iLimitedTask.factory();
			promise.then(iLimitedTask.c).catch(iLimitedTask.e);
			promise.then(() => this.consumed()).catch(() => this.consumed());
		}
	}

	private consumed(): void {
		this.runningPromises--;
		this.consume();
	}
}

D
Dirk Baeumer 已提交
320
const iso639_3_to_2: Map<string> = {
321 322
	'chs': 'zh-cn',
	'cht': 'zh-tw',
323
	'csy': 'cs-cz',
D
Dirk Baeumer 已提交
324 325 326 327 328 329 330 331 332 333
	'deu': 'de',
	'enu': 'en',
	'esn': 'es',
	'fra': 'fr',
	'hun': 'hu',
	'ita': 'it',
	'jpn': 'ja',
	'kor': 'ko',
	'nld': 'nl',
	'plk': 'pl',
334
	'ptb': 'pt-br',
D
Dirk Baeumer 已提交
335 336
	'ptg': 'pt',
	'rus': 'ru',
337
	'sve': 'sv-se',
D
Dirk Baeumer 已提交
338 339 340
	'trk': 'tr'
};

341 342 343
/**
 * Used to map Transifex to VS Code language code representation.
 */
344
const iso639_2_to_3: Map<string> = {
345 346
	'zh-hans': 'chs',
	'zh-hant': 'cht',
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
	'cs-cz': 'csy',
	'de': 'deu',
	'en': 'enu',
	'es': 'esn',
	'fr': 'fra',
	'hu': 'hun',
	'it': 'ita',
	'ja': 'jpn',
	'ko': 'kor',
	'nl': 'nld',
	'pl': 'plk',
	'pt-br': 'ptb',
	'pt': 'ptg',
	'ru': 'rus',
	'sv-se': 'sve',
	'tr': 'trk'
};
364

D
Dirk Baeumer 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
interface IDirectoryInfo {
	name: string;
	iso639_2: string;
}

function sortLanguages(directoryNames: string[]): IDirectoryInfo[] {
	return directoryNames.map((dirName) => {
		var lower = dirName.toLowerCase();
		return {
			name: lower,
			iso639_2: iso639_3_to_2[lower]
		};
	}).sort((a: IDirectoryInfo, b: IDirectoryInfo): number => {
		if (!a.iso639_2 && !b.iso639_2) {
			return 0;
		}
		if (!a.iso639_2) {
			return -1;
		}
		if (!b.iso639_2) {
			return 1;
		}
		return a.iso639_2 < b.iso639_2 ? -1 : (a.iso639_2 > b.iso639_2 ? 1 : 0);
	});
}

function stripComments(content: string): string {
	/**
	* First capturing group matches double quoted string
	* Second matches single quotes string
	* Third matches block comments
	* Fourth matches line comments
	*/
	var regexp: RegExp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
	let result = content.replace(regexp, (match, m1, m2, m3, m4) => {
		// Only one of m1, m2, m3, m4 matches
		if (m3) {
			// A block comment. Replace with nothing
			return '';
		} else if (m4) {
			// A line comment. If it ends in \r?\n then keep it.
			let length = m4.length;
			if (length > 2 && m4[length - 1] === '\n') {
J
Joao Moreno 已提交
408
				return m4[length - 2] === '\r' ? '\r\n' : '\n';
D
Dirk Baeumer 已提交
409 410 411 412 413 414 415 416 417
			} else {
				return '';
			}
		} else {
			// We match a string
			return match;
		}
	});
	return result;
418
}
D
Dirk Baeumer 已提交
419

J
Joao Moreno 已提交
420 421
function escapeCharacters(value: string): string {
	var result: string[] = [];
D
Dirk Baeumer 已提交
422 423
	for (var i = 0; i < value.length; i++) {
		var ch = value.charAt(i);
J
Joao Moreno 已提交
424
		switch (ch) {
D
Dirk Baeumer 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
			case '\'':
				result.push('\\\'');
				break;
			case '"':
				result.push('\\"');
				break;
			case '\\':
				result.push('\\\\');
				break;
			case '\n':
				result.push('\\n');
				break;
			case '\r':
				result.push('\\r');
				break;
			case '\t':
				result.push('\\t');
				break;
			case '\b':
				result.push('\\b');
				break;
			case '\f':
				result.push('\\f');
				break;
			default:
				result.push(ch);
		}
	}
	return result.join('');
}

456
function processCoreBundleFormat(fileHeader: string, languages: string[], json: BundledFormat, emitter: any) {
D
Dirk Baeumer 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
	let keysSection = json.keys;
	let messageSection = json.messages;
	let bundleSection = json.bundles;

	let statistics: Map<number> = Object.create(null);

	let total: number = 0;
	let defaultMessages: Map<Map<string>> = Object.create(null);
	let modules = Object.keys(keysSection);
	modules.forEach((module) => {
		let keys = keysSection[module];
		let messages = messageSection[module];
		if (!messages || keys.length !== messages.length) {
			emitter.emit('error', `Message for module ${module} corrupted. Mismatch in number of keys and messages.`);
			return;
		}
		let messageMap: Map<string> = Object.create(null);
		defaultMessages[module] = messageMap;
		keys.map((key, i) => {
			total++;
			if (Is.string(key)) {
				messageMap[key] = messages[i];
			} else {
				messageMap[key.key] = messages[i];
			}
		});
	});

	let languageDirectory = path.join(__dirname, '..', '..', 'i18n');
486
	let languageDirs;
487
	if (languages) {
488 489 490 491 492
		languageDirs = sortLanguages(languages);
	} else {
		languageDirs = sortLanguages(fs.readdirSync(languageDirectory).filter((item) => fs.statSync(path.join(languageDirectory, item)).isDirectory()));
	}
	languageDirs.forEach((language) => {
D
Dirk Baeumer 已提交
493 494 495 496
		if (!language.iso639_2) {
			return;
		}

J
Joao Moreno 已提交
497 498 499 500
		if (process.env['VSCODE_BUILD_VERBOSE']) {
			log(`Generating nls bundles for: ${language.iso639_2}`);
		}

D
Dirk Baeumer 已提交
501 502 503 504 505 506 507 508 509 510 511
		statistics[language.iso639_2] = 0;
		let localizedModules: Map<string[]> = Object.create(null);
		let cwd = path.join(languageDirectory, language.name, 'src');
		modules.forEach((module) => {
			let order = keysSection[module];
			let i18nFile = path.join(cwd, module) + '.i18n.json';
			let messages: Map<string> = null;
			if (fs.existsSync(i18nFile)) {
				let content = stripComments(fs.readFileSync(i18nFile, 'utf8'));
				messages = JSON.parse(content);
			} else {
J
Joao Moreno 已提交
512 513 514
				if (process.env['VSCODE_BUILD_VERBOSE']) {
					log(`No localized messages found for module ${module}. Using default messages.`);
				}
D
Dirk Baeumer 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527
				messages = defaultMessages[module];
				statistics[language.iso639_2] = statistics[language.iso639_2] + Object.keys(messages).length;
			}
			let localizedMessages: string[] = [];
			order.forEach((keyInfo) => {
				let key: string = null;
				if (Is.string(keyInfo)) {
					key = keyInfo;
				} else {
					key = keyInfo.key;
				}
				let message: string = messages[key];
				if (!message) {
J
Joao Moreno 已提交
528 529 530
					if (process.env['VSCODE_BUILD_VERBOSE']) {
						log(`No localized message found for key ${key} in module ${module}. Using default message.`);
					}
D
Dirk Baeumer 已提交
531 532 533 534 535 536 537 538 539 540
					message = defaultMessages[module][key];
					statistics[language.iso639_2] = statistics[language.iso639_2] + 1;
				}
				localizedMessages.push(message);
			});
			localizedModules[module] = localizedMessages;
		});
		Object.keys(bundleSection).forEach((bundle) => {
			let modules = bundleSection[bundle];
			let contents: string[] = [
A
Alex Dima 已提交
541
				fileHeader,
D
Dirk Baeumer 已提交
542 543 544 545 546 547 548 549 550 551
				`define("${bundle}.nls.${language.iso639_2}", {`
			];
			modules.forEach((module, index) => {
				contents.push(`\t"${module}": [`);
				let messages = localizedModules[module];
				if (!messages) {
					emitter.emit('error', `Didn't find messages for module ${module}.`);
					return;
				}
				messages.forEach((message, index) => {
J
Joao Moreno 已提交
552
					contents.push(`\t\t"${escapeCharacters(message)}${index < messages.length ? '",' : '"'}`);
D
Dirk Baeumer 已提交
553 554 555 556
				});
				contents.push(index < modules.length - 1 ? '\t],' : '\t]');
			});
			contents.push('});');
J
Joao Moreno 已提交
557
			emitter.emit('data', new File({ path: bundle + '.nls.' + language.iso639_2 + '.js', contents: new Buffer(contents.join('\n'), 'utf-8') }));
D
Dirk Baeumer 已提交
558 559 560 561
		});
	});
	Object.keys(statistics).forEach(key => {
		let value = statistics[key];
J
Joao Moreno 已提交
562
		log(`${key} has ${value} untranslated strings.`);
D
Dirk Baeumer 已提交
563
	});
564 565
	languageDirs.forEach(dir => {
		const language = dir.name;
D
Dirk Baeumer 已提交
566 567 568 569 570 571
		let iso639_2 = iso639_3_to_2[language];
		if (!iso639_2) {
			log(`\tCouldn't find iso639 2 mapping for language ${language}. Using default language instead.`);
		} else {
			let stats = statistics[iso639_2];
			if (Is.undef(stats)) {
J
Joao Moreno 已提交
572
				log(`\tNo translations found for language ${language}. Using default language instead.`);
D
Dirk Baeumer 已提交
573 574 575 576 577
			}
		}
	});
}

578
export function processNlsFiles(opts: { fileHeader: string; languages: string[] }): ThroughStream {
J
Joao Moreno 已提交
579
	return through(function (file: File) {
D
Dirk Baeumer 已提交
580 581 582 583
		let fileName = path.basename(file.path);
		if (fileName === 'nls.metadata.json') {
			let json = null;
			if (file.isBuffer()) {
584
				json = JSON.parse((<Buffer>file.contents).toString('utf8'));
D
Dirk Baeumer 已提交
585
			} else {
J
Joao Moreno 已提交
586
				this.emit('error', `Failed to read component file: ${file.relative}`);
D
Dirk Baeumer 已提交
587 588
			}
			if (BundledFormat.is(json)) {
589
				processCoreBundleFormat(opts.fileHeader, opts.languages, json, this);
D
Dirk Baeumer 已提交
590 591 592 593
			}
		}
		this.emit('data', file);
	});
594 595 596 597 598 599
}

export function prepareXlfFiles(projectName?: string, extensionName?: string): ThroughStream {
	return through(
		function (file: File) {
			if (!file.isBuffer()) {
600
				throw new Error(`Failed to read component file: ${file.relative}`);
601 602 603 604 605 606 607 608 609 610 611
			}

			const extension = path.extname(file.path);
			if (extension === '.json') {
				const json = JSON.parse((<Buffer>file.contents).toString('utf8'));

				if (BundledFormat.is(json)) {
					importBundleJson(file, json, this);
				} else if (PackageJsonFormat.is(json) || ModuleJsonFormat.is(json)) {
					importModuleOrPackageJson(file, json, projectName, this, extensionName);
				} else {
612
					throw new Error(`JSON format cannot be deduced for ${file.relative}.`);
613 614 615 616 617 618 619 620
				}
			} else if (extension === '.isl') {
				importIsl(file, this);
			}
		}
	);
}

621
const editorProject: string = 'vscode-editor',
622
	workbenchProject: string = 'vscode-workbench',
623
	extensionsProject: string = 'vscode-extensions',
624
	setupProject: string = 'vscode-setup';
625

626
export function getResource(sourceFile: string): Resource {
627 628
	let resource: string;

J
Joao Moreno 已提交
629
	if (/^vs\/platform/.test(sourceFile)) {
630
		return { name: 'vs/platform', project: editorProject };
J
Joao Moreno 已提交
631
	} else if (/^vs\/editor\/contrib/.test(sourceFile)) {
632
		return { name: 'vs/editor/contrib', project: editorProject };
J
Joao Moreno 已提交
633
	} else if (/^vs\/editor/.test(sourceFile)) {
634
		return { name: 'vs/editor', project: editorProject };
J
Joao Moreno 已提交
635
	} else if (/^vs\/base/.test(sourceFile)) {
636
		return { name: 'vs/base', project: editorProject };
J
Joao Moreno 已提交
637
	} else if (/^vs\/code/.test(sourceFile)) {
638
		return { name: 'vs/code', project: workbenchProject };
J
Joao Moreno 已提交
639
	} else if (/^vs\/workbench\/parts/.test(sourceFile)) {
640 641
		resource = sourceFile.split('/', 4).join('/');
		return { name: resource, project: workbenchProject };
J
Joao Moreno 已提交
642
	} else if (/^vs\/workbench\/services/.test(sourceFile)) {
643 644
		resource = sourceFile.split('/', 4).join('/');
		return { name: resource, project: workbenchProject };
J
Joao Moreno 已提交
645
	} else if (/^vs\/workbench/.test(sourceFile)) {
646 647 648
		return { name: 'vs/workbench', project: workbenchProject };
	}

J
Joao Moreno 已提交
649
	throw new Error(`Could not identify the XLF bundle for ${sourceFile}`);
650 651 652 653
}


function importBundleJson(file: File, json: BundledFormat, stream: ThroughStream): void {
654
	let bundleXlfs: Map<XLF> = Object.create(null);
655 656 657 658 659 660 661 662 663

	for (let source in json.keys) {
		const projectResource = getResource(source);
		const resource = projectResource.name;
		const project = projectResource.project;

		const keys = json.keys[source];
		const messages = json.messages[source];
		if (keys.length !== messages.length) {
664
			throw new Error(`There is a mismatch between keys and messages in ${file.relative}`);
665 666
		}

667
		let xlf = bundleXlfs[resource] ? bundleXlfs[resource] : bundleXlfs[resource] = new XLF(project);
668
		xlf.addFile('src/' + source, keys, messages);
669 670
	}

671 672
	for (let resource in bundleXlfs) {
		const newFilePath = `${bundleXlfs[resource].project}/${resource.replace(/\//g, '_')}.xlf`;
J
Joao Moreno 已提交
673
		const xlfFile = new File({ path: newFilePath, contents: new Buffer(bundleXlfs[resource].toString(), 'utf-8') });
674 675 676 677 678 679 680 681
		stream.emit('data', xlfFile);
	}
}

// Keeps existing XLF instances and a state of how many files were already processed for faster file emission
var extensions: Map<{ xlf: XLF, processed: number }> = Object.create(null);
function importModuleOrPackageJson(file: File, json: ModuleJsonFormat | PackageJsonFormat, projectName: string, stream: ThroughStream, extensionName?: string): void {
	if (ModuleJsonFormat.is(json) && json['keys'].length !== json['messages'].length) {
682
		throw new Error(`There is a mismatch between keys and messages in ${file.relative}`);
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
	}

	// Prepare the source path for <original/> attribute in XLF & extract messages from JSON
	const formattedSourcePath = file.relative.replace(/\\/g, '/');
	const messages = Object.keys(json).map((key) => json[key].toString());

	// Stores the amount of localization files to be transformed to XLF before the emission
	let localizationFilesCount,
		originalFilePath;
	// If preparing XLF for external extension, then use different glob pattern and source path
	if (extensionName) {
		localizationFilesCount = glob.sync('**/*.nls.json').length;
		originalFilePath = `${formattedSourcePath.substr(0, formattedSourcePath.length - '.nls.json'.length)}`;
	} else {
		// Used for vscode/extensions folder
		extensionName = formattedSourcePath.split('/')[0];
		localizationFilesCount = glob.sync(`./extensions/${extensionName}/**/*.nls.json`).length;
		originalFilePath = `extensions/${formattedSourcePath.substr(0, formattedSourcePath.length - '.nls.json'.length)}`;
	}

	let extension = extensions[extensionName] ?
		extensions[extensionName] : extensions[extensionName] = { xlf: new XLF(projectName), processed: 0 };

706 707 708 709
	// .nls.json can come with empty array of keys and messages, check for it
	if (ModuleJsonFormat.is(json) && json.keys.length !== 0) {
		extension.xlf.addFile(originalFilePath, json.keys, json.messages);
	} else if (PackageJsonFormat.is(json) && Object.keys(json).length !== 0) {
710 711 712 713 714 715
		extension.xlf.addFile(originalFilePath, Object.keys(json), messages);
	}

	// Check if XLF is populated with file nodes to emit it
	if (++extensions[extensionName].processed === localizationFilesCount) {
		const newFilePath = path.join(projectName, extensionName + '.xlf');
J
Joao Moreno 已提交
716
		const xlfFile = new File({ path: newFilePath, contents: new Buffer(extension.xlf.toString(), 'utf-8') });
717 718 719 720 721
		stream.emit('data', xlfFile);
	}
}

function importIsl(file: File, stream: ThroughStream) {
722 723 724 725 726 727 728 729 730
	let projectName: string,
		resourceFile: string;
	if (path.basename(file.path) === 'Default.isl') {
		projectName = setupProject;
		resourceFile = 'setup_default.xlf';
	} else {
		projectName = workbenchProject;
		resourceFile = 'setup_messages.xlf';
	}
731

732
	let xlf = new XLF(projectName),
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
		keys: string[] = [],
		messages: string[] = [];

	let model = new TextModel(file.contents.toString());
	let inMessageSection = false;
	model.lines.forEach(line => {
		if (line.length === 0) {
			return;
		}
		let firstChar = line.charAt(0);
		switch (firstChar) {
			case ';':
				// Comment line;
				return;
			case '[':
				inMessageSection = '[Messages]' === line || '[CustomMessages]' === line;
				return;
		}
		if (!inMessageSection) {
			return;
		}
		let sections: string[] = line.split('=');
		if (sections.length !== 2) {
756
			throw new Error(`Badly formatted message found: ${line}`);
757 758 759 760 761 762 763 764 765 766
		} else {
			let key = sections[0];
			let value = sections[1];
			if (key.length > 0 && value.length > 0) {
				keys.push(key);
				messages.push(value);
			}
		}
	});

J
Joao Moreno 已提交
767
	const originalPath = file.path.substring(file.cwd.length + 1, file.path.split('.')[0].length).replace(/\\/g, '/');
768 769 770
	xlf.addFile(originalPath, keys, messages);

	// Emit only upon all ISL files combined into single XLF instance
771
	const newFilePath = path.join(projectName, resourceFile);
J
Joao Moreno 已提交
772
	const xlfFile = new File({ path: newFilePath, contents: new Buffer(xlf.toString(), 'utf-8') });
773
	stream.emit('data', xlfFile);
774 775
}

776
export function pushXlfFiles(apiHostname: string, username: string, password: string): ThroughStream {
777 778 779
	let tryGetPromises = [];
	let updateCreatePromises = [];

J
Joao Moreno 已提交
780
	return through(function (file: File) {
781 782 783
		const project = path.dirname(file.relative);
		const fileName = path.basename(file.path);
		const slug = fileName.substr(0, fileName.length - '.xlf'.length);
784
		const credentials = `${username}:${password}`;
785 786

		// Check if resource already exists, if not, then create it.
787
		let promise = tryGetResource(project, slug, apiHostname, credentials);
788 789
		tryGetPromises.push(promise);
		promise.then(exists => {
790
			if (exists) {
791
				promise = updateResource(project, slug, file, apiHostname, credentials);
792
			} else {
793
				promise = createResource(project, slug, file, apiHostname, credentials);
794
			}
795 796 797
			updateCreatePromises.push(promise);
		});

J
Joao Moreno 已提交
798
	}, function () {
799 800 801 802
		// End the pipe only after all the communication with Transifex API happened
		Promise.all(tryGetPromises).then(() => {
			Promise.all(updateCreatePromises).then(() => {
				this.emit('end');
803 804
			}).catch((reason) => { throw new Error(reason); });
		}).catch((reason) => { throw new Error(reason); });
805 806 807
	});
}

808
function tryGetResource(project: string, slug: string, apiHostname: string, credentials: string): Promise<boolean> {
809
	return new Promise((resolve, reject) => {
810 811 812 813 814 815 816
		const options = {
			hostname: apiHostname,
			path: `/api/2/project/${project}/resource/${slug}/?details`,
			auth: credentials,
			method: 'GET'
		};

817
		const request = https.request(options, (response) => {
818 819 820 821 822
			if (response.statusCode === 404) {
				resolve(false);
			} else if (response.statusCode === 200) {
				resolve(true);
			} else {
823
				reject(`Failed to query resource ${project}/${slug}. Response: ${response.statusCode} ${response.statusMessage}`);
824
			}
825 826
		});
		request.on('error', (err) => {
827
			reject(`Failed to get ${project}/${slug} on Transifex: ${err}`);
828
		});
829 830

		request.end();
831 832 833
	});
}

834 835 836 837 838 839 840 841
function createResource(project: string, slug: string, xlfFile: File, apiHostname: string, credentials: any): Promise<any> {
	return new Promise((resolve, reject) => {
		const data = JSON.stringify({
			'content': xlfFile.contents.toString(),
			'name': slug,
			'slug': slug,
			'i18n_type': 'XLIFF'
		});
842
		const options = {
843 844 845 846 847
			hostname: apiHostname,
			path: `/api/2/project/${project}/resources`,
			headers: {
				'Content-Type': 'application/json',
				'Content-Length': Buffer.byteLength(data)
848
			},
849 850
			auth: credentials,
			method: 'POST'
851
		};
852

853
		let request = https.request(options, (res) => {
854 855 856
			if (res.statusCode === 201) {
				log(`Resource ${project}/${slug} successfully created on Transifex.`);
			} else {
857
				reject(`Something went wrong in the request creating ${slug} in ${project}. ${res.statusCode}`);
858
			}
859 860
		});
		request.on('error', (err) => {
861
			reject(`Failed to create ${project}/${slug} on Transifex: ${err}`);
862
		});
863 864 865

		request.write(data);
		request.end();
866 867 868 869 870 871 872
	});
}

/**
 * The following link provides information about how Transifex handles updates of a resource file:
 * https://dev.befoolish.co/tx-docs/public/projects/updating-content#what-happens-when-you-update-files
 */
J
Joao Moreno 已提交
873
function updateResource(project: string, slug: string, xlfFile: File, apiHostname: string, credentials: string): Promise<any> {
874 875
	return new Promise((resolve, reject) => {
		const data = JSON.stringify({ content: xlfFile.contents.toString() });
876
		const options = {
877 878 879 880 881 882 883 884
			hostname: apiHostname,
			path: `/api/2/project/${project}/resource/${slug}/content`,
			headers: {
				'Content-Type': 'application/json',
				'Content-Length': Buffer.byteLength(data)
			},
			auth: credentials,
			method: 'PUT'
885
		};
886

887
		let request = https.request(options, (res) => {
888
			if (res.statusCode === 200) {
889 890 891 892 893 894 895 896 897 898 899
				res.setEncoding('utf8');

				let responseBuffer: string = '';
				res.on('data', function (chunk) {
					responseBuffer += chunk;
				});
				res.on('end', () => {
					const response = JSON.parse(responseBuffer);
					log(`Resource ${project}/${slug} successfully updated on Transifex. Strings added: ${response.strings_added}, updated: ${response.strings_added}, deleted: ${response.strings_added}`);
					resolve();
				});
900
			} else {
901
				reject(`Something went wrong in the request updating ${slug} in ${project}. ${res.statusCode}`);
902
			}
903 904
		});
		request.on('error', (err) => {
905
			reject(`Failed to update ${project}/${slug} on Transifex: ${err}`);
906
		});
907 908 909

		request.write(data);
		request.end();
910 911 912 913
	});
}

function obtainProjectResources(projectName: string): Resource[] {
914
	let resources: Resource[] = [];
915

916
	if (projectName === editorProject) {
M
Michel Kaporin 已提交
917 918
		const json = fs.readFileSync('./build/lib/i18n.resources.json', 'utf8');
		resources = JSON.parse(json).editor;
919
	} else if (projectName === workbenchProject) {
M
Michel Kaporin 已提交
920 921
		const json = fs.readFileSync('./build/lib/i18n.resources.json', 'utf8');
		resources = JSON.parse(json).workbench;
922
	} else if (projectName === extensionsProject) {
923 924 925 926 927 928 929 930 931
		let extensionsToLocalize: string[] = glob.sync('./extensions/**/*.nls.json').map(extension => extension.split('/')[2]);
		let resourcesToPull: string[] = [];

		extensionsToLocalize.forEach(extension => {
			if (resourcesToPull.indexOf(extension) === -1) { // remove duplicate elements returned by glob
				resourcesToPull.push(extension);
				resources.push({ name: extension, project: projectName });
			}
		});
932
	} else if (projectName === setupProject) {
933
		resources.push({ name: 'setup_default', project: setupProject });
934 935 936 937 938
	}

	return resources;
}

939
export function pullXlfFiles(projectName: string, apiHostname: string, username: string, password: string, languages: string[], resources?: Resource[]): NodeJS.ReadableStream {
940 941 942 943 944 945 946
	if (!resources) {
		resources = obtainProjectResources(projectName);
	}
	if (!resources) {
		throw new Error('Transifex projects and resources must be defined to be able to pull translations from Transifex.');
	}

947
	const credentials = `${username}:${password}`;
948
	let expectedTranslationsCount = languages.length * resources.length;
949 950
	let translationsRetrieved = 0, called = false;

J
Joao Moreno 已提交
951
	return readable(function (count, callback) {
952 953 954 955 956 957 958 959 960
		// Mark end of stream when all resources were retrieved
		if (translationsRetrieved === expectedTranslationsCount) {
			return this.emit('end');
		}

		if (!called) {
			called = true;
			const stream = this;

961
			// Retrieve XLF files from main projects
J
Joao Moreno 已提交
962 963
			languages.map(function (language) {
				resources.map(function (resource) {
964 965 966 967
					retrieveResource(language, resource, apiHostname, credentials).then((file: File) => {
						stream.emit('data', file);
						translationsRetrieved++;
					}).catch(error => { throw new Error(error); });
968 969 970 971 972 973 974
				});
			});
		}

		callback();
	});
}
975
const limiter = new Limiter<File>(NUMBER_OF_CONCURRENT_DOWNLOADS);
976

977
function retrieveResource(language: string, resource: Resource, apiHostname, credentials): Promise<File> {
978
	return limiter.queue(() => new Promise<File>((resolve, reject) => {
979 980
		const slug = resource.name.replace(/\//g, '_');
		const project = resource.project;
981
		const iso639 = language.toLowerCase();
982 983 984 985
		const options = {
			hostname: apiHostname,
			path: `/api/2/project/${project}/resource/${slug}/translation/${iso639}?file&mode=onlyreviewed`,
			auth: credentials,
986
			port: 443,
987 988 989
			method: 'GET'
		};

990
		let request = https.request(options, (res) => {
J
Joao Moreno 已提交
991 992 993 994
			let xlfBuffer: Buffer[] = [];
			res.on('data', (chunk: Buffer) => xlfBuffer.push(chunk));
			res.on('end', () => {
				if (res.statusCode === 200) {
995
					console.log('success: ' + options.path);
J
Joao Moreno 已提交
996 997 998 999
					resolve(new File({ contents: Buffer.concat(xlfBuffer), path: `${project}/${iso639_2_to_3[language]}/${slug}.xlf` }));
				}
				reject(`${slug} in ${project} returned no data. Response code: ${res.statusCode}.`);
			});
1000 1001
		});
		request.on('error', (err) => {
1002
			reject(`Failed to query resource ${slug} with the following error: ${err}. ${options.path}`);
1003 1004
		});
		request.end();
1005 1006
		console.log('started: ' + options.path);
	}));
1007 1008
}

1009
export function prepareJsonFiles(): ThroughStream {
1010 1011
	let parsePromises: Promise<ParsedXLF[]>[] = [];

J
Joao Moreno 已提交
1012
	return through(function (xlf: File) {
1013
		let stream = this;
1014 1015 1016
		let parsePromise = XLF.parse(xlf.contents.toString());
		parsePromises.push(parsePromise);
		parsePromise.then(
J
Joao Moreno 已提交
1017
			function (resolvedFiles) {
1018 1019 1020 1021
				resolvedFiles.forEach(file => {
					let messages = file.messages, translatedFile;

					// ISL file path always starts with 'build/'
J
Joao Moreno 已提交
1022
					if (/^build\//.test(file.originalFilePath)) {
1023
						const defaultLanguages = { 'zh-hans': true, 'zh-hant': true, 'ko': true };
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
						if (path.basename(file.originalFilePath) === 'Default' && !defaultLanguages[file.language]) {
							return;
						}

						translatedFile = createIslFile('..', file.originalFilePath, messages, iso639_2_to_3[file.language]);
					} else {
						translatedFile = createI18nFile(iso639_2_to_3[file.language], file.originalFilePath, messages);
					}

					stream.emit('data', translatedFile);
				});
			},
J
Joao Moreno 已提交
1036
			function (rejectReason) {
1037
				throw new Error(`XLF parsing error: ${rejectReason}`);
1038 1039
			}
		);
J
Joao Moreno 已提交
1040
	}, function () {
1041 1042 1043
		Promise.all(parsePromises)
			.then(() => { this.emit('end'); })
			.catch(reason => { throw new Error(reason); });
1044 1045 1046
	});
}

1047
function createI18nFile(base: string, originalFilePath: string, messages: Map<string>): File {
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
	let content = [
		'/*---------------------------------------------------------------------------------------------',
		' *  Copyright (c) Microsoft Corporation. All rights reserved.',
		' *  Licensed under the MIT License. See License.txt in the project root for license information.',
		' *--------------------------------------------------------------------------------------------*/',
		'// Do not edit this file. It is machine generated.'
	].join('\n') + '\n' + JSON.stringify(messages, null, '\t').replace(/\r\n/g, '\n');

	return new File({
		path: path.join(base, originalFilePath + '.i18n.json'),
		contents: new Buffer(content, 'utf8')
	});
}


const languageNames: Map<string> = {
	'chs': 'Simplified Chinese',
	'cht': 'Traditional Chinese',
	'kor': 'Korean'
};

const languageIds: Map<string> = {
	'chs': '$0804',
	'cht': '$0404',
	'kor': '$0412'
};

const encodings: Map<string> = {
	'chs': 'CP936',
	'cht': 'CP950',
	'jpn': 'CP932',
	'kor': 'CP949',
	'deu': 'CP1252',
	'fra': 'CP1252',
	'esn': 'CP1252',
	'rus': 'CP1251',
1084
	'ita': 'CP1252',
1085 1086 1087
    'ptb': 'CP1252',
	'hun': 'CP1250',
	'trk': 'CP1254'
1088 1089
};

1090
function createIslFile(base: string, originalFilePath: string, messages: Map<string>, language: string): File {
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
	let content: string[] = [];
	let originalContent: TextModel;
	if (path.basename(originalFilePath) === 'Default') {
		originalContent = new TextModel(fs.readFileSync(originalFilePath + '.isl', 'utf8'));
	} else {
		originalContent = new TextModel(fs.readFileSync(originalFilePath + '.en.isl', 'utf8'));
	}

	originalContent.lines.forEach(line => {
		if (line.length > 0) {
			let firstChar = line.charAt(0);
			if (firstChar === '[' || firstChar === ';') {
				if (line === '; *** Inno Setup version 5.5.3+ English messages ***') {
					content.push(`; *** Inno Setup version 5.5.3+ ${languageNames[language]} messages ***`);
				} else {
					content.push(line);
				}
			} else {
				let sections: string[] = line.split('=');
				let key = sections[0];
				let translated = line;
				if (key) {
					if (key === 'LanguageName') {
						translated = `${key}=${languageNames[language]}`;
					} else if (key === 'LanguageID') {
						translated = `${key}=${languageIds[language]}`;
					} else if (key === 'LanguageCodePage') {
						translated = `${key}=${encodings[language].substr(2)}`;
					} else {
						let translatedMessage = messages[key];
						if (translatedMessage) {
							translated = `${key}=${translatedMessage}`;
						}
					}
				}

				content.push(translated);
			}
		}
	});

1132 1133 1134
	const tag = iso639_3_to_2[language];
	const basename = path.basename(originalFilePath);
	const filePath = `${path.join(base, path.dirname(originalFilePath), basename)}.${tag}.isl`;
1135 1136 1137

	return new File({
		path: filePath,
1138
		contents: iconv.encode(new Buffer(content.join('\r\n'), 'utf8'), encodings[language])
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
	});
}

function encodeEntities(value: string): string {
	var result: string[] = [];
	for (var i = 0; i < value.length; i++) {
		var ch = value[i];
		switch (ch) {
			case '<':
				result.push('&lt;');
				break;
			case '>':
				result.push('&gt;');
				break;
			case '&':
				result.push('&amp;');
				break;
			default:
				result.push(ch);
		}
	}
	return result.join('');
}

J
Joao Moreno 已提交
1163
function decodeEntities(value: string): string {
1164
	return value.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
D
Dirk Baeumer 已提交
1165
}